Index: branches/HTM-14.1-update-dev0/.cproject
===================================================================
--- branches/HTM-14.1-update-dev0/.cproject	(revision 1199)
+++ branches/HTM-14.1-update-dev0/.cproject	(revision 1200)
@@ -3,881 +3,297 @@
 
 <cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
-<storageModule moduleId="org.eclipse.cdt.core.settings">
-<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627">
-<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627" moduleId="org.eclipse.cdt.core.settings" name="Default">
-<externalSettings/>
-<extensions>
-<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
-<extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-</extensions>
-</storageModule>
-<storageModule moduleId="cdtBuildSystem" version="4.0.0">
-<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
-<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1589457155" name="/" resourcePath="">
-<toolChain id="cdt.managedbuild.toolchain.gnu.base.1526218680" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
-<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.1070174461" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
-<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.303360531" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
-<tool id="cdt.managedbuild.tool.gnu.archiver.base.1865065310" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
-<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
-<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1377965043" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
-<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1723893286" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1887435720" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
-<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.239564785" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
-<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.747702219" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
-<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
-<additionalInput kind="additionalinput" paths="$(LIBS)"/>
-</inputType>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.assembler.base.105114263" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
-<inputType id="cdt.managedbuild.tool.gnu.assembler.input.418556763" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
-</tool>
-</toolChain>
-</folderInfo>
-</configuration>
-</storageModule>
-<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
-<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
-<storageModule moduleId="scannerConfiguration">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948;cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-</scannerConfigBuildInfo>
-<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.c.compiler.base.1377965043;cdt.managedbuild.tool.gnu.c.compiler.input.1723893286">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-</scannerConfigBuildInfo>
-</storageModule>
-<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
-</cconfiguration>
-<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760">
-<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760" moduleId="org.eclipse.cdt.core.settings" name="Release">
-<externalSettings/>
-<extensions>
-<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
-<extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-</extensions>
-</storageModule>
-<storageModule moduleId="cdtBuildSystem" version="4.0.0">
-<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760" name="Release" parent="org.eclipse.cdt.build.core.emptycfg">
-<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760." name="/" resourcePath="">
-<toolChain id="cdt.managedbuild.toolchain.gnu.base.941850140" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
-<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.570056820" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
-<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.1205969576" incrementalBuildTarget="release" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
-<tool id="cdt.managedbuild.tool.gnu.archiver.base.419981059" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
-<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1468586530" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
-<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1380809592" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.2080920992" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
-<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.906164461" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1417941276" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
-<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.993562450" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
-<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1181959465" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
-<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
-<additionalInput kind="additionalinput" paths="$(LIBS)"/>
-</inputType>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.assembler.base.1616904926" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
-<inputType id="cdt.managedbuild.tool.gnu.assembler.input.594859024" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
-</tool>
-</toolChain>
-</folderInfo>
-</configuration>
-</storageModule>
-<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
-<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
-<storageModule moduleId="scannerConfiguration">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948;cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-</scannerConfigBuildInfo>
-<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.c.compiler.base.1377965043;cdt.managedbuild.tool.gnu.c.compiler.input.1723893286">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-</scannerConfigBuildInfo>
-</storageModule>
-<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
-</cconfiguration>
-<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818">
-<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818" moduleId="org.eclipse.cdt.core.settings" name="Debug">
-<externalSettings/>
-<extensions>
-<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
-<extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
-</extensions>
-</storageModule>
-<storageModule moduleId="cdtBuildSystem" version="4.0.0">
-<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818" name="Debug" parent="org.eclipse.cdt.build.core.emptycfg">
-<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818." name="/" resourcePath="">
-<toolChain id="cdt.managedbuild.toolchain.gnu.base.92180794" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
-<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.1739497298" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
-<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.538875865" incrementalBuildTarget="debug" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
-<tool id="cdt.managedbuild.tool.gnu.archiver.base.1027985338" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
-<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.418565259" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
-<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.740162987" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1577556745" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
-<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.866758036" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1386401723" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
-<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.378790356" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
-<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.749934366" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
-<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
-<additionalInput kind="additionalinput" paths="$(LIBS)"/>
-</inputType>
-</tool>
-<tool id="cdt.managedbuild.tool.gnu.assembler.base.459153765" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
-<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1722272588" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
-</tool>
-</toolChain>
-</folderInfo>
-</configuration>
-</storageModule>
-<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
-<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
-<storageModule moduleId="scannerConfiguration">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948;cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-</scannerConfigBuildInfo>
-<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.c.compiler.base.1377965043;cdt.managedbuild.tool.gnu.c.compiler.input.1723893286">
-<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="makefileGenerator">
-<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
-<buildOutputProvider>
-<openAction enabled="true" filePath=""/>
-<parser enabled="true"/>
-</buildOutputProvider>
-<scannerInfoProvider id="specsFile">
-<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
-<parser enabled="true"/>
-</scannerInfoProvider>
-</profile>
-</scannerConfigBuildInfo>
-</storageModule>
-<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
-</cconfiguration>
-</storageModule>
-<storageModule moduleId="cdtBuildSystem" version="4.0.0">
-<project id="HM.null.1881189133" name="HM"/>
-</storageModule>
+	<storageModule moduleId="org.eclipse.cdt.core.settings">
+		<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627">
+			<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627" moduleId="org.eclipse.cdt.core.settings" name="Default">
+				<externalSettings/>
+				<extensions>
+					<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+					<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+				</extensions>
+			</storageModule>
+			<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+				<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
+					<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1589457155" name="/" resourcePath="">
+						<toolChain id="cdt.managedbuild.toolchain.gnu.base.1526218680" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
+							<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.1070174461" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
+							<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.303360531" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" parallelBuildOn="true" parallelizationNumber="3" stopOnErr="false" superClass="cdt.managedbuild.target.gnu.builder.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.archiver.base.1865065310" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1377965043" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1723893286" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1887435720" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.239564785" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
+								<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.747702219" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+									<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+									<additionalInput kind="additionalinput" paths="$(LIBS)"/>
+								</inputType>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.assembler.base.105114263" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.assembler.input.418556763" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+							</tool>
+						</toolChain>
+					</folderInfo>
+				</configuration>
+			</storageModule>
+			<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+			<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
+			<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
+		</cconfiguration>
+		<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760">
+			<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760" moduleId="org.eclipse.cdt.core.settings" name="Release">
+				<externalSettings/>
+				<extensions>
+					<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+					<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+				</extensions>
+			</storageModule>
+			<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+				<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760" name="Release" parent="org.eclipse.cdt.build.core.emptycfg">
+					<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760." name="/" resourcePath="">
+						<toolChain id="cdt.managedbuild.toolchain.gnu.base.941850140" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
+							<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.570056820" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
+							<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.1205969576" incrementalBuildTarget="release" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.archiver.base.419981059" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1468586530" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1380809592" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.2080920992" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.906164461" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1417941276" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.993562450" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
+								<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1181959465" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+									<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+									<additionalInput kind="additionalinput" paths="$(LIBS)"/>
+								</inputType>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.assembler.base.1616904926" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.assembler.input.594859024" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+							</tool>
+						</toolChain>
+					</folderInfo>
+				</configuration>
+			</storageModule>
+			<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+			<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
+			<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
+		</cconfiguration>
+		<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818">
+			<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+				<externalSettings/>
+				<extensions>
+					<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+					<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+				</extensions>
+			</storageModule>
+			<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+				<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818" name="Debug" parent="org.eclipse.cdt.build.core.emptycfg">
+					<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818." name="/" resourcePath="">
+						<toolChain id="cdt.managedbuild.toolchain.gnu.base.92180794" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
+							<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.1739497298" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
+							<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.538875865" incrementalBuildTarget="debug" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.archiver.base.1027985338" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.418565259" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.740162987" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1577556745" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.866758036" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1386401723" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
+							<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.378790356" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
+								<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.749934366" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+									<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+									<additionalInput kind="additionalinput" paths="$(LIBS)"/>
+								</inputType>
+							</tool>
+							<tool id="cdt.managedbuild.tool.gnu.assembler.base.459153765" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
+								<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1722272588" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+							</tool>
+						</toolChain>
+					</folderInfo>
+				</configuration>
+			</storageModule>
+			<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+			<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
+			<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
+		</cconfiguration>
+	</storageModule>
+	<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+		<project id="HM.null.1881189133" name="HM"/>
+	</storageModule>
+	<storageModule moduleId="refreshScope"/>
+	<storageModule moduleId="scannerConfiguration">
+		<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+		<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+			<buildOutputProvider>
+				<openAction enabled="true" filePath=""/>
+				<parser enabled="true"/>
+			</buildOutputProvider>
+			<scannerInfoProvider id="specsFile">
+				<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+				<parser enabled="true"/>
+			</scannerInfoProvider>
+		</profile>
+		<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+			<buildOutputProvider>
+				<openAction enabled="true" filePath=""/>
+				<parser enabled="true"/>
+			</buildOutputProvider>
+			<scannerInfoProvider id="makefileGenerator">
+				<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+				<parser enabled="true"/>
+			</scannerInfoProvider>
+		</profile>
+		<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+			<buildOutputProvider>
+				<openAction enabled="true" filePath=""/>
+				<parser enabled="true"/>
+			</buildOutputProvider>
+			<scannerInfoProvider id="specsFile">
+				<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+				<parser enabled="true"/>
+			</scannerInfoProvider>
+		</profile>
+		<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+			<buildOutputProvider>
+				<openAction enabled="true" filePath=""/>
+				<parser enabled="true"/>
+			</buildOutputProvider>
+			<scannerInfoProvider id="specsFile">
+				<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+				<parser enabled="true"/>
+			</scannerInfoProvider>
+		</profile>
+		<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+			<buildOutputProvider>
+				<openAction enabled="true" filePath=""/>
+				<parser enabled="true"/>
+			</buildOutputProvider>
+			<scannerInfoProvider id="specsFile">
+				<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+				<parser enabled="true"/>
+			</scannerInfoProvider>
+		</profile>
+		<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.c.compiler.base.1377965043;cdt.managedbuild.tool.gnu.c.compiler.input.1723893286">
+			<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
+			<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="specsFile">
+					<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+			<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="makefileGenerator">
+					<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+			<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="specsFile">
+					<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+			<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="specsFile">
+					<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+			<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="specsFile">
+					<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+		</scannerConfigBuildInfo>
+		<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948;cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573">
+			<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
+			<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="specsFile">
+					<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+			<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="makefileGenerator">
+					<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+			<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="specsFile">
+					<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+			<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="specsFile">
+					<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+			<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+				<buildOutputProvider>
+					<openAction enabled="true" filePath=""/>
+					<parser enabled="true"/>
+				</buildOutputProvider>
+				<scannerInfoProvider id="specsFile">
+					<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+					<parser enabled="true"/>
+				</scannerInfoProvider>
+			</profile>
+		</scannerConfigBuildInfo>
+	</storageModule>
 </cproject>
Index: branches/HTM-14.1-update-dev0/COPYING
===================================================================
--- branches/HTM-14.1-update-dev0/COPYING	(revision 1199)
+++ branches/HTM-14.1-update-dev0/COPYING	(revision 1200)
@@ -4,5 +4,5 @@
 granted under this license.   
 
-Copyright (c) 2010-2014, ITU/ISO/IEC
+Copyright (c) 2010-2015, ITU/ISO/IEC
 All rights reserved.
 
Index: branches/HTM-14.1-update-dev0/HM.xcodeproj/project.pbxproj
===================================================================
--- branches/HTM-14.1-update-dev0/HM.xcodeproj/project.pbxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/HM.xcodeproj/project.pbxproj	(revision 1200)
@@ -8,4 +8,11 @@
 
 /* Begin PBXBuildFile section */
+		61601BB615A74998008F8892 /* Debug.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 61601BAF15A74998008F8892 /* Debug.cpp */; };
+		61601BB715A74998008F8892 /* Debug.h in Headers */ = {isa = PBXBuildFile; fileRef = 61601BB015A74998008F8892 /* Debug.h */; };
+		61601BB815A74998008F8892 /* TComChromaFormat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 61601BB115A74998008F8892 /* TComChromaFormat.cpp */; };
+		61601BB915A74998008F8892 /* TComChromaFormat.h in Headers */ = {isa = PBXBuildFile; fileRef = 61601BB215A74998008F8892 /* TComChromaFormat.h */; };
+		61601BBA15A74998008F8892 /* TComRectangle.h in Headers */ = {isa = PBXBuildFile; fileRef = 61601BB315A74998008F8892 /* TComRectangle.h */; };
+		61601BBB15A74998008F8892 /* TComTU.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 61601BB415A74998008F8892 /* TComTU.cpp */; };
+		61601BBC15A74998008F8892 /* TComTU.h in Headers */ = {isa = PBXBuildFile; fileRef = 61601BB515A74998008F8892 /* TComTU.h */; };
 		65EA1B88135744C400988950 /* libmd5.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B85135744C400988950 /* libmd5.h */; };
 		65EA1B89135744C400988950 /* libmd5.c in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B86135744C400988950 /* libmd5.c */; };
@@ -13,6 +20,4 @@
 		65EA1B8E135744EA00988950 /* SEIread.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B8C135744EA00988950 /* SEIread.h */; };
 		65EA1B8F135744EA00988950 /* SEIread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B8D135744EA00988950 /* SEIread.cpp */; };
-		65EA1B92135744FE00988950 /* SEIwrite.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B90135744FE00988950 /* SEIwrite.h */; };
-		65EA1B93135744FE00988950 /* SEIwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B91135744FE00988950 /* SEIwrite.cpp */; };
 		65EA1B951357451300988950 /* SEI.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B941357451300988950 /* SEI.h */; };
 		65EA1B97135745D500988950 /* TComPicYuvMD5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */; };
@@ -77,5 +82,4 @@
 		6767961211AD623900421804 /* TDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767960411AD623900421804 /* TDecTop.cpp */; };
 		6767961311AD623900421804 /* TDecTop.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767960511AD623900421804 /* TDecTop.h */; };
-		6767963311AD628100421804 /* TEncAnalyze.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767961E11AD628100421804 /* TEncAnalyze.cpp */; };
 		6767963411AD628100421804 /* TEncAnalyze.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767961F11AD628100421804 /* TEncAnalyze.h */; };
 		6767963511AD628100421804 /* TEncCavlc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962011AD628100421804 /* TEncCavlc.cpp */; };
@@ -125,4 +129,8 @@
 		7184647713FAE75800747BF9 /* program_options_lite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7184647513FAE75800747BF9 /* program_options_lite.cpp */; };
 		7184647813FAE75800747BF9 /* program_options_lite.h in Headers */ = {isa = PBXBuildFile; fileRef = 7184647613FAE75800747BF9 /* program_options_lite.h */; };
+		719E0DAB1A927238000361D4 /* SEIEncoder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 719E0DA91A927238000361D4 /* SEIEncoder.cpp */; };
+		719E0DAC1A927238000361D4 /* SEIEncoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 719E0DAA1A927238000361D4 /* SEIEncoder.h */; };
+		719E0DAF1A927294000361D4 /* SEIwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 719E0DAD1A927294000361D4 /* SEIwrite.cpp */; };
+		719E0DB01A927294000361D4 /* SEIwrite.h in Headers */ = {isa = PBXBuildFile; fileRef = 719E0DAE1A927294000361D4 /* SEIwrite.h */; };
 		71AD603911EBC28500F5F1FE /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
 		71AD603A11EBC28D00F5F1FE /* libTLibEncoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767961911AD626F00421804 /* libTLibEncoder.a */; };
@@ -210,4 +218,11 @@
 
 /* Begin PBXFileReference section */
+		61601BAF15A74998008F8892 /* Debug.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Debug.cpp; path = source/Lib/TLibCommon/Debug.cpp; sourceTree = "<group>"; };
+		61601BB015A74998008F8892 /* Debug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Debug.h; path = source/Lib/TLibCommon/Debug.h; sourceTree = "<group>"; };
+		61601BB115A74998008F8892 /* TComChromaFormat.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComChromaFormat.cpp; path = source/Lib/TLibCommon/TComChromaFormat.cpp; sourceTree = "<group>"; };
+		61601BB215A74998008F8892 /* TComChromaFormat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComChromaFormat.h; path = source/Lib/TLibCommon/TComChromaFormat.h; sourceTree = "<group>"; };
+		61601BB315A74998008F8892 /* TComRectangle.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComRectangle.h; path = source/Lib/TLibCommon/TComRectangle.h; sourceTree = "<group>"; };
+		61601BB415A74998008F8892 /* TComTU.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComTU.cpp; path = source/Lib/TLibCommon/TComTU.cpp; sourceTree = "<group>"; };
+		61601BB515A74998008F8892 /* TComTU.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComTU.h; path = source/Lib/TLibCommon/TComTU.h; sourceTree = "<group>"; };
 		65EA1B85135744C400988950 /* libmd5.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = libmd5.h; path = source/Lib/libmd5/libmd5.h; sourceTree = "<group>"; };
 		65EA1B86135744C400988950 /* libmd5.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = libmd5.c; path = source/Lib/libmd5/libmd5.c; sourceTree = "<group>"; };
@@ -215,6 +230,4 @@
 		65EA1B8C135744EA00988950 /* SEIread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEIread.h; path = source/Lib/TLibDecoder/SEIread.h; sourceTree = "<group>"; };
 		65EA1B8D135744EA00988950 /* SEIread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEIread.cpp; path = source/Lib/TLibDecoder/SEIread.cpp; sourceTree = "<group>"; };
-		65EA1B90135744FE00988950 /* SEIwrite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEIwrite.h; path = source/Lib/TLibEncoder/SEIwrite.h; sourceTree = "<group>"; };
-		65EA1B91135744FE00988950 /* SEIwrite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEIwrite.cpp; path = source/Lib/TLibEncoder/SEIwrite.cpp; sourceTree = "<group>"; };
 		65EA1B941357451300988950 /* SEI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEI.h; path = source/Lib/TLibCommon/SEI.h; sourceTree = "<group>"; };
 		65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPicYuvMD5.cpp; path = source/Lib/TLibCommon/TComPicYuvMD5.cpp; sourceTree = "<group>"; };
@@ -282,5 +295,4 @@
 		6767960511AD623900421804 /* TDecTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecTop.h; path = source/Lib/TLibDecoder/TDecTop.h; sourceTree = "<group>"; };
 		6767961911AD626F00421804 /* libTLibEncoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibEncoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
-		6767961E11AD628100421804 /* TEncAnalyze.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncAnalyze.cpp; path = source/Lib/TLibEncoder/TEncAnalyze.cpp; sourceTree = "<group>"; };
 		6767961F11AD628100421804 /* TEncAnalyze.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncAnalyze.h; path = source/Lib/TLibEncoder/TEncAnalyze.h; sourceTree = "<group>"; };
 		6767962011AD628100421804 /* TEncCavlc.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncCavlc.cpp; path = source/Lib/TLibEncoder/TEncCavlc.cpp; sourceTree = "<group>"; };
@@ -333,4 +345,8 @@
 		7184647513FAE75800747BF9 /* program_options_lite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = program_options_lite.cpp; path = source/Lib/TAppCommon/program_options_lite.cpp; sourceTree = "<group>"; };
 		7184647613FAE75800747BF9 /* program_options_lite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = program_options_lite.h; path = source/Lib/TAppCommon/program_options_lite.h; sourceTree = "<group>"; };
+		719E0DA91A927238000361D4 /* SEIEncoder.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEIEncoder.cpp; path = source/Lib/TLibEncoder/SEIEncoder.cpp; sourceTree = "<group>"; };
+		719E0DAA1A927238000361D4 /* SEIEncoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEIEncoder.h; path = source/Lib/TLibEncoder/SEIEncoder.h; sourceTree = "<group>"; };
+		719E0DAD1A927294000361D4 /* SEIwrite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEIwrite.cpp; path = source/Lib/TLibEncoder/SEIwrite.cpp; sourceTree = "<group>"; };
+		719E0DAE1A927294000361D4 /* SEIwrite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEIwrite.h; path = source/Lib/TLibEncoder/SEIwrite.h; sourceTree = "<group>"; };
 		DB7795BE13F1226500C92469 /* TEncPic.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncPic.cpp; path = source/Lib/TLibEncoder/TEncPic.cpp; sourceTree = "<group>"; };
 		DB7795BF13F1226500C92469 /* TEncPic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncPic.h; path = source/Lib/TLibEncoder/TEncPic.h; sourceTree = "<group>"; };
@@ -458,21 +474,25 @@
 			children = (
 				712FAEA81379BA2F00DB5314 /* AccessUnit.h */,
-				712FAEA91379BA2F00DB5314 /* NAL.h */,
-				65EA1B85135744C400988950 /* libmd5.h */,
-				65EA1B86135744C400988950 /* libmd5.c */,
-				65EA1B87135744C400988950 /* MD5.h */,
 				6767959911AD61FC00421804 /* CommonDef.h */,
-				6767959A11AD61FC00421804 /* ContextTables.h */,
 				671E0D3811B6AD8C00F3747B /* ContextModel.cpp */,
 				671E0D3911B6AD8C00F3747B /* ContextModel.h */,
 				671E0D3A11B6AD8C00F3747B /* ContextModel3DBuffer.cpp */,
 				671E0D3B11B6AD8C00F3747B /* ContextModel3DBuffer.h */,
+				6767959A11AD61FC00421804 /* ContextTables.h */,
+				61601BAF15A74998008F8892 /* Debug.cpp */,
+				61601BB015A74998008F8892 /* Debug.h */,
+				65EA1B86135744C400988950 /* libmd5.c */,
+				65EA1B85135744C400988950 /* libmd5.h */,
+				65EA1B87135744C400988950 /* MD5.h */,
+				712FAEA91379BA2F00DB5314 /* NAL.h */,
+				71161E9E16A7253F0021E8A8 /* SEI.cpp */,
+				65EA1B941357451300988950 /* SEI.h */,
 				671E0D3E11B6AD8C00F3747B /* TComBitCounter.h */,
+				676795A311AD61FC00421804 /* TComBitStream.cpp */,
+				676795A411AD61FC00421804 /* TComBitStream.h */,
 				671E0D3F11B6AD8C00F3747B /* TComCABACTables.cpp */,
 				671E0D4011B6AD8C00F3747B /* TComCABACTables.h */,
-				671E0D4111B6AD8C00F3747B /* TComMv.h */,
-				676795A311AD61FC00421804 /* TComBitStream.cpp */,
-				65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */,
-				676795A411AD61FC00421804 /* TComBitStream.h */,
+				61601BB115A74998008F8892 /* TComChromaFormat.cpp */,
+				61601BB215A74998008F8892 /* TComChromaFormat.h */,
 				676795A511AD61FC00421804 /* TComDataCU.cpp */,
 				676795A611AD61FC00421804 /* TComDataCU.h */,
@@ -484,4 +504,5 @@
 				676795AA11AD61FC00421804 /* TComMotionInfo.cpp */,
 				676795AB11AD61FC00421804 /* TComMotionInfo.h */,
+				671E0D4111B6AD8C00F3747B /* TComMv.h */,
 				676795AD11AD61FC00421804 /* TComPattern.cpp */,
 				676795AE11AD61FC00421804 /* TComPattern.h */,
@@ -492,4 +513,5 @@
 				676795B311AD61FC00421804 /* TComPicYuv.cpp */,
 				676795B411AD61FC00421804 /* TComPicYuv.h */,
+				65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */,
 				676795B711AD61FC00421804 /* TComPrediction.cpp */,
 				676795B811AD61FC00421804 /* TComPrediction.h */,
@@ -498,4 +520,5 @@
 				DBC9C9471447847400A77A93 /* TComRdCostWeightPrediction.cpp */,
 				DBC9C9481447847400A77A93 /* TComRdCostWeightPrediction.h */,
+				61601BB315A74998008F8892 /* TComRectangle.h */,
 				676795BB11AD61FC00421804 /* TComRom.cpp */,
 				676795BC11AD61FC00421804 /* TComRom.h */,
@@ -504,10 +527,8 @@
 				676795BD11AD61FC00421804 /* TComSlice.cpp */,
 				676795BE11AD61FC00421804 /* TComSlice.h */,
-				65EA1B941357451300988950 /* SEI.h */,
-				71161E9E16A7253F0021E8A8 /* SEI.cpp */,
-				65EA1B90135744FE00988950 /* SEIwrite.h */,
-				65EA1B91135744FE00988950 /* SEIwrite.cpp */,
 				676795BF11AD61FC00421804 /* TComTrQuant.cpp */,
 				676795C011AD61FC00421804 /* TComTrQuant.h */,
+				61601BB415A74998008F8892 /* TComTU.cpp */,
+				61601BB515A74998008F8892 /* TComTU.h */,
 				DBC9C9491447847400A77A93 /* TComWeightPrediction.cpp */,
 				DBC9C94A1447847400A77A93 /* TComWeightPrediction.h */,
@@ -522,12 +543,12 @@
 			isa = PBXGroup;
 			children = (
-				71206CD416066EC700A354E7 /* SyntaxElementParser.cpp */,
-				71206CD516066EC700A354E7 /* SyntaxElementParser.h */,
 				712FAEB21379BA6600DB5314 /* AnnexBread.cpp */,
 				712FAEB31379BA6600DB5314 /* AnnexBread.h */,
 				712FAEB41379BA6600DB5314 /* NALread.cpp */,
 				712FAEB51379BA6600DB5314 /* NALread.h */,
+				65EA1B8D135744EA00988950 /* SEIread.cpp */,
 				65EA1B8C135744EA00988950 /* SEIread.h */,
-				65EA1B8D135744EA00988950 /* SEIread.cpp */,
+				71206CD416066EC700A354E7 /* SyntaxElementParser.cpp */,
+				71206CD516066EC700A354E7 /* SyntaxElementParser.h */,
 				671E0D5611B6ADD300F3747B /* TDecBinCoder.h */,
 				671E0D5711B6ADD300F3747B /* TDecBinCoderCABAC.cpp */,
@@ -554,9 +575,14 @@
 			isa = PBXGroup;
 			children = (
-				71206CD916066EDD00A354E7 /* SyntaxElementWriter.cpp */,
-				71206CDA16066EDD00A354E7 /* SyntaxElementWriter.h */,
 				712FAEAC1379BA4900DB5314 /* AnnexBwrite.h */,
 				712FAEAD1379BA4900DB5314 /* NALwrite.cpp */,
 				712FAEAE1379BA4900DB5314 /* NALwrite.h */,
+				719E0DA91A927238000361D4 /* SEIEncoder.cpp */,
+				719E0DAA1A927238000361D4 /* SEIEncoder.h */,
+				719E0DAD1A927294000361D4 /* SEIwrite.cpp */,
+				719E0DAE1A927294000361D4 /* SEIwrite.h */,
+				71206CD916066EDD00A354E7 /* SyntaxElementWriter.cpp */,
+				71206CDA16066EDD00A354E7 /* SyntaxElementWriter.h */,
+				6767961F11AD628100421804 /* TEncAnalyze.h */,
 				671E0D7211B6ADE900F3747B /* TEncBinCoder.h */,
 				671E0D7311B6ADE900F3747B /* TEncBinCoderCABAC.cpp */,
@@ -564,6 +590,4 @@
 				DBA796C61499ADE2003F7D5D /* TEncBinCoderCABACCounter.cpp */,
 				DBA796C71499ADE3003F7D5D /* TEncBinCoderCABACCounter.h */,
-				6767961E11AD628100421804 /* TEncAnalyze.cpp */,
-				6767961F11AD628100421804 /* TEncAnalyze.h */,
 				6767962011AD628100421804 /* TEncCavlc.cpp */,
 				6767962111AD628100421804 /* TEncCavlc.h */,
@@ -687,4 +711,8 @@
 				DBC9C94C1447847400A77A93 /* TComRdCostWeightPrediction.h in Headers */,
 				DBC9C94E1447847400A77A93 /* TComWeightPrediction.h in Headers */,
+				61601BB715A74998008F8892 /* Debug.h in Headers */,
+				61601BB915A74998008F8892 /* TComChromaFormat.h in Headers */,
+				61601BBA15A74998008F8892 /* TComRectangle.h in Headers */,
+				61601BBC15A74998008F8892 /* TComTU.h in Headers */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
@@ -719,12 +747,13 @@
 				6767963911AD628100421804 /* TEncCu.h in Headers */,
 				6767963B11AD628100421804 /* TEncEntropy.h in Headers */,
+				719E0DAC1A927238000361D4 /* SEIEncoder.h in Headers */,
 				6767963D11AD628100421804 /* TEncGOP.h in Headers */,
 				6767963F11AD628100421804 /* TEncSbac.h in Headers */,
 				6767964111AD628100421804 /* TEncSearch.h in Headers */,
 				6767964311AD628100421804 /* TEncSlice.h in Headers */,
+				719E0DB01A927294000361D4 /* SEIwrite.h in Headers */,
 				6767964511AD628100421804 /* TEncTop.h in Headers */,
 				671E0D8011B6ADE900F3747B /* TEncBinCoder.h in Headers */,
 				671E0D8211B6ADE900F3747B /* TEncBinCoderCABAC.h in Headers */,
-				65EA1B92135744FE00988950 /* SEIwrite.h in Headers */,
 				712FAEAF1379BA4900DB5314 /* AnnexBwrite.h in Headers */,
 				712FAEB11379BA4900DB5314 /* NALwrite.h in Headers */,
@@ -945,4 +974,7 @@
 				DBC9C94B1447847400A77A93 /* TComRdCostWeightPrediction.cpp in Sources */,
 				DBC9C94D1447847400A77A93 /* TComWeightPrediction.cpp in Sources */,
+				61601BB615A74998008F8892 /* Debug.cpp in Sources */,
+				61601BB815A74998008F8892 /* TComChromaFormat.cpp in Sources */,
+				61601BBB15A74998008F8892 /* TComTU.cpp in Sources */,
 				71161E9F16A7253F0021E8A8 /* SEI.cpp in Sources */,
 			);
@@ -972,15 +1004,15 @@
 			buildActionMask = 2147483647;
 			files = (
-				6767963311AD628100421804 /* TEncAnalyze.cpp in Sources */,
 				6767963511AD628100421804 /* TEncCavlc.cpp in Sources */,
 				6767963811AD628100421804 /* TEncCu.cpp in Sources */,
 				6767963A11AD628100421804 /* TEncEntropy.cpp in Sources */,
 				6767963C11AD628100421804 /* TEncGOP.cpp in Sources */,
+				719E0DAF1A927294000361D4 /* SEIwrite.cpp in Sources */,
 				6767963E11AD628100421804 /* TEncSbac.cpp in Sources */,
+				719E0DAB1A927238000361D4 /* SEIEncoder.cpp in Sources */,
 				6767964011AD628100421804 /* TEncSearch.cpp in Sources */,
 				6767964211AD628100421804 /* TEncSlice.cpp in Sources */,
 				6767964411AD628100421804 /* TEncTop.cpp in Sources */,
 				671E0D8111B6ADE900F3747B /* TEncBinCoderCABAC.cpp in Sources */,
-				65EA1B93135744FE00988950 /* SEIwrite.cpp in Sources */,
 				712FAEB01379BA4900DB5314 /* NALwrite.cpp in Sources */,
 				DBC9C94514477FAE00A77A93 /* TEncSampleAdaptiveOffset.cpp in Sources */,
@@ -1083,6 +1115,7 @@
 				GCC_WARN_UNUSED_VARIABLE = YES;
 				HEADER_SEARCH_PATHS = source/Lib;
+				MACOSX_DEPLOYMENT_TARGET = 10.7;
 				ONLY_ACTIVE_ARCH = YES;
-				SDKROOT = "";
+				SDKROOT = macosx;
 			};
 			name = Debug;
@@ -1091,5 +1124,5 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				ARCHS = "$(NATIVE_ARCH_ACTUAL)";
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
 				GCC_C_LANGUAGE_STANDARD = gnu99;
 				GCC_OPTIMIZATION_LEVEL = 3;
@@ -1098,5 +1131,6 @@
 				GCC_WARN_UNUSED_VARIABLE = YES;
 				HEADER_SEARCH_PATHS = source/Lib;
-				SDKROOT = "";
+				MACOSX_DEPLOYMENT_TARGET = 10.7;
+				SDKROOT = macosx;
 			};
 			name = Release;
Index: branches/HTM-14.1-update-dev0/README
===================================================================
--- branches/HTM-14.1-update-dev0/README	(revision 1200)
+++ branches/HTM-14.1-update-dev0/README	(revision 1200)
@@ -0,0 +1,8 @@
+This software package is the reference software for Rec. ITU-T H.265 | ISO/IEC 23008-2 High efficiency video coding (HEVC). The reference software includes both encoder and decoder functionality.
+
+Reference software is useful in aiding users of a video coding standard to establish and test conformance and interoperability, and to educate users and demonstrate the capabilities of the standard. For these purposes, this software is provided as an aid for the study and implementation of Rec. ITU-T H.265 | ISO/IEC 23008-2 High efficiency video coding.
+
+The software has been jointly developed by the ITU-T Video Coding Experts Group (VCEG, Question 6 of ITU-T Study Group 16) and the ISO/IEC Moving Picture Experts Group (MPEG, Working Group 11 of Subcommittee 29 of ISO/IEC Joint Technical Committee 1).
+
+A software manual, which contains usage instructions, can be found in the "doc" subdirectory of this software package.
+
Index: branches/HTM-14.1-update-dev0/README-newconfig.txt
===================================================================
--- branches/HTM-14.1-update-dev0/README-newconfig.txt	(revision 1199)
+++ 	(revision )
@@ -1,103 +1,0 @@
-The 0.5 TMuC release introduces new unified config file and command line
-parsing code.  This allows all configuration file options to be specified
-on the command line and permits the use of multiple config files.
-
-Compatability with command line options in previous TMuC releases is
-maintained with the following exceptions:
-  - Commandline -1/-0 FEN does not implicitly set ASR,
-    this now matches the behaviour of the config file.
-  - FramesToBeEncoded is now the preferred name for FrameToBeEncoded
-    (the old option still exists for compatibility)
-  - Commandline & Config, setting of GOPSize nolonger unconditionally
-    sets RateGOPSize.  If RateGOPSize is never set, it assumes as its
-    default value, the value of GOPSize.
-
-    Unless it is specifically required, do not set the RateGOPSize to a
-    value other than -1.  This value (the default) causes RateGOPSize
-    to inherit the final value of GOPSize.  While setting config files
-    to have RateGOPSize = GOPSize does no immediate harm, it causes
-    confusion when GOPSize is altered (without altering RateGOPSize) and
-    behaviour changes relating to GPB.
-
-All configuration options may be specified on the command line using the
-following syntax:
-  --CfgOptionName=value
-For example,
-  --InputFile=Kimono1_1920x1080_24.yuv
-
-A list of all options avaliable is provided by running the encoder with
-either no options, or the option "--help".
-
-The command line is evaluated in the order of options given, for example:
-    ./encoder -c file1.cfg --UseFoo=7 -c file2.cfg
-
-The following may be observed:
- - file2.cfg overrides any arguments set in file1.
- - file1.cfg overrides any default arguments
- - if file2.cfg specifies "UseFoo", this value will be used
-   otherwise, "UseFoo" will have the value 7.
-
-====================
-Notes for developers
-====================
-The new unified config file and command line parsing code allows all
-configuration options, storage location, defaults, help text to be specified
-in a single place.  No custom value parsing code is required.
-
-Options are specified in TAppEncCfg::parseCfg() using the following syntax:
-{{{
-  /* storage for options */
-  int storage_variable_int;
-  unsigned storage_variable_unsigned;
-  float storage_variable_float;
-  bool storage_variable_bool;
-  string storage_variable_string;
-
-  /* set up configuration */
-  namespace po = df::program_options_lite;
-  po::Options opts;
-  opts.addOptions()
-  /*( option spec  , reference to storage,    default,        help text)*/
-    ("option_spec0", storage_variable_int,       -42,        "help text")
-    ("option_spec1", storage_variable_unsigned,   17u,       "help text")
-    ("option_spec2", storage_variable_bool,     true,        "help text")
-    ("option_spec3", storage_variable_float,     4.0f,       "help text")
-    ("option_spec4", storage_variable_string, string("foo"), "help text")
-    ;
-}}}
-
-NB, the help text is optional.
-
-Where, the option_spec is a string containing comma separated names in
-the following forms:
-  - multi-charcter names are longopts that are handled in gnu style
-    (and may be handled in a config file)
-  - single-character names are short opts that are handled in posix style
-    (and are not handled in a config file)
-    prefixing a multi-character name stops it being handled in the config.
-
-For example:
-     option spec | config file formats | command line formats
-       "Name"    | Name:value          | --Name=value
-       "n"       | --none--            | -n value
-       "-name"   | --none--            | -name value
-       "Name,n"  | Name:value          | "--Name=value" or "-n value"
-
-Caveats:
- - The default values need to be specified in the same type as the storage
-   variable.  Eg, an unsigned int, would need to be specified as "17u" not
-   "17"
-
-Help text formatting:
- - Help text will be automatically wrapped and aligned if longer than the
-   available space.
- - To force wrapping at a particular point, insert a newline character '\n'
-   Eg: "Foo values:\n  value1 - a\n  value2 - b\n  value3 - c"
-   Gives:
-       Foo values:
-         value1 - a
-         value2 - b
-         value3 - c
-
-Please report any issues, or requests for support with the configuration to:
-  David Flynn <davidf@rd.bbc.co.uk>
Index: branches/HTM-14.1-update-dev0/build/HM_vc10.sln
===================================================================
--- branches/HTM-14.1-update-dev0/build/HM_vc10.sln	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/HM_vc10.sln	(revision 1200)
@@ -23,4 +23,8 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppExtractor", "vc10\TAppExtractor_vc10.vcxproj", "{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoderAnalyser", "vc10\TAppDecoderAnalyser_vc10.vcxproj", "{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoderAnalyser", "vc10\TLibDecoderAnalyser_vc10.vcxproj", "{68C1251A-55D8-47C9-9052-62F785BD437A}"
 EndProject
 Global
@@ -120,4 +124,20 @@
 		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.ActiveCfg = Release|x64
 		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.Build.0 = Release|x64
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Debug|Win32.Build.0 = Debug|Win32
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Debug|x64.ActiveCfg = Debug|x64
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Debug|x64.Build.0 = Debug|x64
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Release|Win32.ActiveCfg = Release|Win32
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Release|Win32.Build.0 = Release|Win32
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Release|x64.ActiveCfg = Release|x64
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Release|x64.Build.0 = Release|x64
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Debug|Win32.ActiveCfg = Debug|Win32
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Debug|Win32.Build.0 = Debug|Win32
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Debug|x64.ActiveCfg = Debug|x64
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Debug|x64.Build.0 = Debug|x64
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Release|Win32.ActiveCfg = Release|Win32
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Release|Win32.Build.0 = Release|Win32
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Release|x64.ActiveCfg = Release|x64
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Release|x64.Build.0 = Release|x64
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
Index: branches/HTM-14.1-update-dev0/build/linux/app/TAppDecoder/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/app/TAppDecoder/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/app/TAppDecoder/makefile	(revision 1200)
@@ -16,9 +16,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR				= ./objects
+OBJ_DIR				= ./objects$(HBD)
 
 # set executable name
-PRJ_NAME			= TAppDecoder
+PRJ_NAME			= TAppDecoder$(HBD)
 
 # defines to set
@@ -41,13 +47,13 @@
 
 
-DYN_DEBUG_LIBS		= -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
-DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
-STAT_DEBUG_LIBS		= -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
-STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+DYN_DEBUG_LIBS		= -lTLibDecoder$(HBD)d -lTLibCommon$(HBD)d -lTLibVideoIO$(HBD)d -lTAppCommon$(HBD)d
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoder$(HBD)d.a $(LIB_DIR)/libTLibCommon$(HBD)d.a $(LIB_DIR)/libTLibVideoIO$(HBD)d.a $(LIB_DIR)/libTAppCommon$(HBD)d.a
+STAT_DEBUG_LIBS		= -lTLibDecoder$(HBD)Staticd -lTLibCommon$(HBD)Staticd -lTLibVideoIO$(HBD)Staticd -lTAppCommon$(HBD)Staticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoder$(HBD)Staticd.a $(LIB_DIR)/libTLibCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibVideoIO$(HBD)Staticd.a $(LIB_DIR)/libTAppCommon$(HBD)Staticd.a
 
-DYN_RELEASE_LIBS	= -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
-DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
-STAT_RELEASE_LIBS	= -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
-STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+DYN_RELEASE_LIBS	= -lTLibDecoder$(HBD) -lTLibCommon$(HBD) -lTLibVideoIO$(HBD) -lTAppCommon$(HBD)
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder$(HBD).a $(LIB_DIR)/libTLibCommon$(HBD).a $(LIB_DIR)/libTLibVideoIO$(HBD).a $(LIB_DIR)/libTAppCommon$(HBD).a
+STAT_RELEASE_LIBS	= -lTLibDecoder$(HBD)Static -lTLibCommon$(HBD)Static -lTLibVideoIO$(HBD)Static -lTAppCommon$(HBD)Static
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a
 
 
Index: branches/HTM-14.1-update-dev0/build/linux/app/TAppDecoderAnalyser/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/app/TAppDecoderAnalyser/makefile	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/linux/app/TAppDecoderAnalyser/makefile	(revision 1200)
@@ -0,0 +1,64 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppDecoder
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR) 
+USER_LIB_DIRS	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects$(HBD)
+
+# set executable name
+PRJ_NAME			= TAppDecoderAnalyser$(HBD)
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE -DRExt__DECODER_DEBUG_BIT_STATISTICS=1
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/decmain.o \
+					$(OBJ_DIR)/TAppDecCfg.o \
+					$(OBJ_DIR)/TAppDecTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibDecoderAnalyser$(HBD)d -lTLibCommon$(HBD)d -lTLibVideoIO$(HBD)d -lTAppCommon$(HBD)d
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderAnalyser$(HBD)d.a $(LIB_DIR)/libTLibCommon$(HBD)d.a $(LIB_DIR)/libTLibVideoIO$(HBD)d.a $(LIB_DIR)/libTAppCommon$(HBD)d.a
+STAT_DEBUG_LIBS		= -lTLibDecoderAnalyser$(HBD)Staticd -lTLibCommon$(HBD)Staticd -lTLibVideoIO$(HBD)Staticd -lTAppCommon$(HBD)Staticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderAnalyser$(HBD)Staticd.a $(LIB_DIR)/libTLibCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibVideoIO$(HBD)Staticd.a $(LIB_DIR)/libTAppCommon$(HBD)Staticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoderAnalyser$(HBD) -lTLibCommon$(HBD) -lTLibVideoIO$(HBD) -lTAppCommon$(HBD)
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderAnalyser$(HBD).a $(LIB_DIR)/libTLibCommon$(HBD).a $(LIB_DIR)/libTLibVideoIO$(HBD).a $(LIB_DIR)/libTAppCommon$(HBD).a
+STAT_RELEASE_LIBS	= -lTLibDecoderAnalyser$(HBD)Static -lTLibCommon$(HBD)Static -lTLibVideoIO$(HBD)Static -lTAppCommon$(HBD)Static
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderAnalyser$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: branches/HTM-14.1-update-dev0/build/linux/app/TAppEncoder/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/app/TAppEncoder/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/app/TAppEncoder/makefile	(revision 1200)
@@ -16,9 +16,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR				= ./objects
+OBJ_DIR				= ./objects$(HBD)
 
 # set executable name
-PRJ_NAME			= TAppEncoder
+PRJ_NAME			= TAppEncoder$(HBD)
 
 # defines to set
@@ -41,13 +47,13 @@
 
 
-DYN_DEBUG_LIBS		= -lTLibEncoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond -lTLibRendererd
-DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a $(LIB_DIR)/libTLibRendererd.a
-STAT_DEBUG_LIBS		= -lTLibEncoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd -lTLibRendererStaticd
-STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a $(LIB_DIR)/libTLibRendererStaticd.a
+DYN_DEBUG_LIBS		= -lTLibEncoder$(HBD)d -lTLibCommon$(HBD)d -lTLibVideoIO$(HBD)d -lTAppCommon$(HBD)d -lTLibRenderer$(HBD)d
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoder$(HBD)d.a $(LIB_DIR)/libTLibCommon$(HBD)d.a $(LIB_DIR)/libTLibVideoIO$(HBD)d.a $(LIB_DIR)/libTAppCommon$(HBD)d.a  $(LIB_DIR)/libTLibRenderer$(HBD)d.a
+STAT_DEBUG_LIBS		= -lTLibEncoder$(HBD)Staticd -lTLibCommon$(HBD)Staticd -lTLibVideoIO$(HBD)Staticd -lTAppCommon$(HBD)Staticd -lTLibRendererStatic$(HBD)d
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoder$(HBD)Staticd.a $(LIB_DIR)/libTLibCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibVideoIO$(HBD)Staticd.a $(LIB_DIR)/libTAppCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibRendererStatic$(HBD)d.a
 
-DYN_RELEASE_LIBS	= -lTLibEncoder -lTLibCommon -lTLibVideoIO -lTAppCommon -lTLibRenderer
-DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a $(LIB_DIR)/libTLibRenderer.a
-STAT_RELEASE_LIBS	= -lTLibEncoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic -lTLibRendererStatic
-STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a $(LIB_DIR)/libTLibRendererStatic.a
+DYN_RELEASE_LIBS	= -lTLibEncoder$(HBD) -lTLibCommon$(HBD) -lTLibVideoIO$(HBD) -lTAppCommon$(HBD)  -lTLibRenderer$(HBD)
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoder$(HBD).a $(LIB_DIR)/libTLibCommon$(HBD).a $(LIB_DIR)/libTLibVideoIO$(HBD).a $(LIB_DIR)/libTAppCommon$(HBD).a  $(LIB_DIR)/libTLibRenderer$(HBD).a
+STAT_RELEASE_LIBS	= -lTLibEncoder$(HBD)Static -lTLibCommon$(HBD)Static -lTLibVideoIO$(HBD)Static -lTAppCommon$(HBD)Static -lTLibRenderer$(HBD)Static
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoder$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a  $(LIB_DIR)/libTLibRenderer$(HBD)Static.a
 
 
Index: branches/HTM-14.1-update-dev0/build/linux/app/TAppExtractor/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/app/TAppExtractor/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/app/TAppExtractor/makefile	(revision 1200)
@@ -4,5 +4,5 @@
 # set directories to your wanted values
 SRC_DIR				= ../../../../source/App/TAppExtractor
-INC_DIR				= ../../../../source/App/TAppExtractor
+INC_DIR				= ../../../../source/Lib
 LIB_DIR				= ../../../../lib
 BIN_DIR				= ../../../../bin
@@ -16,9 +16,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR				= ./objects
+OBJ_DIR				= ./objects$(HBD)
 
 # set executable name
-PRJ_NAME			= TAppExtractor
+PRJ_NAME			= TAppExtractor$(HBD)
 
 # defines to set
@@ -41,13 +47,13 @@
 
 
-DYN_DEBUG_LIBS		= -lTLibExtractord -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
-DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibExtractord.a $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
-STAT_DEBUG_LIBS		= -lTLibExtractorStaticd -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
-STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibExtractorStaticd.a $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+DYN_DEBUG_LIBS		= -lTLibExtractor$(HBD)d -lTLibDecoder$(HBD)d -lTLibCommon$(HBD)d -lTLibVideoIO$(HBD)d -lTAppCommon$(HBD)d
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibExtractor$(HBD)d.a $(LIB_DIR)/libTLibDecoder$(HBD)d.a $(LIB_DIR)/libTLibCommon$(HBD)d.a $(LIB_DIR)/libTLibVideoIO$(HBD)d.a $(LIB_DIR)/libTAppCommon$(HBD)d.a
+STAT_DEBUG_LIBS		= -lTLibExtractor$(HBD)Staticd -lTLibDecoderStatic$(HBD)d -lTLibCommon$(HBD)Staticd -lTLibVideoIO$(HBD)Staticd -lTAppCommon$(HBD)Staticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibExtractor$(HBD)Staticd.a $(LIB_DIR)/libTLibDecoder$(HBD)Staticd.a $(LIB_DIR)/libTLibCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibVideoIO$(HBD)Staticd.a $(LIB_DIR)/libTAppCommon$(HBD)Staticd.a
 
-DYN_RELEASE_LIBS	= -lTLibExtractor -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
-DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibExtractor.a $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
-STAT_RELEASE_LIBS	= -lTLibExtractorStatic -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
-STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibExtractorStatic.a $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+DYN_RELEASE_LIBS	= -lTLibExtractor$(HBD) -lTLibDecoder$(HBD) -lTLibCommon$(HBD) -lTLibVideoIO$(HBD) -lTAppCommon$(HBD)
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibExtractor$(HBD).a $(LIB_DIR)/libTLibDecoder$(HBD).a $(LIB_DIR)/libTLibCommon$(HBD).a $(LIB_DIR)/libTLibVideoIO$(HBD).a $(LIB_DIR)/libTAppCommon$(HBD).a
+STAT_RELEASE_LIBS	= -lTLibExtractor$(HBD)Static -lTLibDecoder$(HBD)Static -lTLibCommon$(HBD)Static -lTLibVideoIO$(HBD)Static -lTAppCommon$(HBD)Static
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibExtractor$(HBD)Static.a $(LIB_DIR)/libTLibDecoder$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a
 
 
Index: branches/HTM-14.1-update-dev0/build/linux/app/TAppRenderer/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/app/TAppRenderer/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/app/TAppRenderer/makefile	(revision 1200)
@@ -16,9 +16,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR				= ./objects
+OBJ_DIR				= ./objects$(HBD)
 
 # set executable name
-PRJ_NAME			= TAppRenderer
+PRJ_NAME			= TAppRenderer$(HBD)
 
 # defines to set
@@ -41,13 +47,13 @@
 
 
-DYN_DEBUG_LIBS		= -lTLibRendererd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_LIBS		= -lTLibRenderer$(HBD)d -lTLibCommon$(HBD)d -lTLibVideoIO$(HBD)d -lTAppCommond
 DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibRendererd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
-STAT_DEBUG_LIBS		= -lTLibRendererStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
-STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibRendererStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+STAT_DEBUG_LIBS		= -lTLibRenderer$(HBD)Staticd -lTLibCommon$(HBD)Staticd -lTLibVideoIO$(HBD)Staticd -lTAppCommon$(HBD)Staticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibRenderer$(HBD)Staticd.a $(LIB_DIR)/libTLibCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibVideoIO$(HBD)Staticd.a $(LIB_DIR)/libTAppCommon$(HBD)Staticd.a
 
-DYN_RELEASE_LIBS	= -lTLibRenderer -lTLibCommon -lTLibVideoIO -lTAppCommon
-DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibRenderer.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
-STAT_RELEASE_LIBS	= -lTLibRendererStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
-STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibRendererStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+DYN_RELEASE_LIBS	= -lTLibRenderer$(HBD) -lTLibCommon$(HBD) -lTLibVideoIO$(HBD) -lTAppCommon$(HBD)
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibRenderer$(HBD).a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO$(HBD).a $(LIB_DIR)/libTAppCommon$(HBD).a
+STAT_RELEASE_LIBS	= -lTLibRenderer$(HBD)Static -lTLibCommon$(HBD)Static -lTLibVideoIO$(HBD)Static -lTAppCommon$(HBD)Static
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibRenderer$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a
 
 
Index: branches/HTM-14.1-update-dev0/build/linux/common/makefile.base
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/common/makefile.base	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/common/makefile.base	(revision 1200)
@@ -13,5 +13,5 @@
 #########################################################
 
-CPP   	= g++
+CPP     = g++
 CC      = gcc
 AR    	= ar
@@ -48,5 +48,5 @@
 # default cpp flags for all configurations
 #CPPFLAGS          = -Wall -fPIC $(DEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS)
-CPPFLAGS          = -fPIC $(DEFS) $(ADDDEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS) -Wall -Wshadow -Wno-sign-compare -Werror
+CPPFLAGS          = -fPIC $(DEFS)  $(ADDDEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS) -Wall -Wshadow -Wno-sign-compare -Werror
 
 ########## 
@@ -58,4 +58,8 @@
 endif
 ##########
+
+ifeq ($(HIGHBITDEPTH), 1)
+CPPFLAGS+="-DRExt__HIGH_BIT_DEPTH_SUPPORT=1"
+endif
 
 #
Index: branches/HTM-14.1-update-dev0/build/linux/lib/TAppCommon/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/lib/TAppCommon/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/lib/TAppCommon/makefile	(revision 1200)
@@ -17,9 +17,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR			= ./objects
+OBJ_DIR			= ./objects$(HBD)
 
 # the library name
-PRJ_NAME	 	= TAppCommon
+PRJ_NAME	 	= TAppCommon$(HBD)
 
 # version information
Index: branches/HTM-14.1-update-dev0/build/linux/lib/TLibCommon/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/lib/TLibCommon/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/lib/TLibCommon/makefile	(revision 1200)
@@ -17,9 +17,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR			= ./objects
+OBJ_DIR			= ./objects$(HBD)
 
 # the library name
-PRJ_NAME	 	= TLibCommon
+PRJ_NAME	 	= TLibCommon$(HBD)
 
 # version information
@@ -33,4 +39,7 @@
 # set objects
 OBJS          	= \
+			$(OBJ_DIR)/Debug.o \
+			$(OBJ_DIR)/TComPicYuv.o \
+			$(OBJ_DIR)/TComYuv.o \
 			$(OBJ_DIR)/ContextModel.o \
 			$(OBJ_DIR)/ContextModel3DBuffer.o \
@@ -39,4 +48,5 @@
 			$(OBJ_DIR)/TComSampleAdaptiveOffset.o \
 			$(OBJ_DIR)/TComBitStream.o \
+			$(OBJ_DIR)/TComChromaFormat.o \
 			$(OBJ_DIR)/TComDataCU.o \
 			$(OBJ_DIR)/TComLoopFilter.o \
@@ -45,5 +55,4 @@
 			$(OBJ_DIR)/TComPic.o \
 			$(OBJ_DIR)/TComPicSym.o \
-			$(OBJ_DIR)/TComPicYuv.o \
 			$(OBJ_DIR)/TComPicYuvMD5.o \
 			$(OBJ_DIR)/TComPrediction.o \
@@ -52,5 +61,5 @@
 			$(OBJ_DIR)/TComSlice.o \
 			$(OBJ_DIR)/TComTrQuant.o \
-			$(OBJ_DIR)/TComYuv.o \
+			$(OBJ_DIR)/TComTU.o \
 			$(OBJ_DIR)/TComInterpolationFilter.o \
 			$(OBJ_DIR)/libmd5.o \
Index: branches/HTM-14.1-update-dev0/build/linux/lib/TLibDecoder/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/lib/TLibDecoder/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/lib/TLibDecoder/makefile	(revision 1200)
@@ -17,9 +17,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR			= ./objects
+OBJ_DIR			= ./objects$(HBD)
 
 # the library name
-PRJ_NAME	 	= TLibDecoder
+PRJ_NAME	 	= TLibDecoder$(HBD)
 
 # version information
Index: branches/HTM-14.1-update-dev0/build/linux/lib/TLibDecoderAnalyser/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/lib/TLibDecoderAnalyser/makefile	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/linux/lib/TLibDecoderAnalyser/makefile	(revision 1200)
@@ -0,0 +1,72 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibDecoder
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects$(HBD)
+
+# the library name
+PRJ_NAME	 	= TLibDecoderAnalyser$(HBD)
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX -DRExt__DECODER_DEBUG_BIT_STATISTICS=1
+
+# set objects
+OBJS          	= \
+				$(OBJ_DIR)/AnnexBread.o \
+				$(OBJ_DIR)/NALread.o \
+				$(OBJ_DIR)/SEIread.o \
+				$(OBJ_DIR)/SyntaxElementParser.o \
+				$(OBJ_DIR)/TDecBinCoderCABAC.o \
+				$(OBJ_DIR)/TDecCAVLC.o \
+				$(OBJ_DIR)/TDecCu.o \
+				$(OBJ_DIR)/TDecEntropy.o \
+				$(OBJ_DIR)/TDecGop.o \
+				$(OBJ_DIR)/TDecSbac.o \
+				$(OBJ_DIR)/TDecSlice.o \
+				$(OBJ_DIR)/TDecTop.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: branches/HTM-14.1-update-dev0/build/linux/lib/TLibEncoder/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/lib/TLibEncoder/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/lib/TLibEncoder/makefile	(revision 1200)
@@ -17,9 +17,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR			= ./objects
+OBJ_DIR			= ./objects$(HBD)
 
 # the library name
-PRJ_NAME	 	= TLibEncoder
+PRJ_NAME	 	= TLibEncoder$(HBD)
 
 # version information
@@ -34,4 +40,5 @@
 OBJS          	= \
 			$(OBJ_DIR)/NALwrite.o \
+			$(OBJ_DIR)/SEIEncoder.o \
 			$(OBJ_DIR)/SEIwrite.o \
 			$(OBJ_DIR)/SyntaxElementWriter.o \
@@ -39,5 +46,4 @@
 			$(OBJ_DIR)/TEncBinCoderCABACCounter.o \
 			$(OBJ_DIR)/TEncSampleAdaptiveOffset.o \
-			$(OBJ_DIR)/TEncAnalyze.o \
 			$(OBJ_DIR)/TEncCavlc.o \
 			$(OBJ_DIR)/TEncCu.o \
Index: branches/HTM-14.1-update-dev0/build/linux/lib/TLibExtractor/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/lib/TLibExtractor/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/lib/TLibExtractor/makefile	(revision 1200)
@@ -4,5 +4,5 @@
 # set pathes to the correct directories
 SRC_DIR			= ../../../../source/Lib/TLibExtractor
-INC_DIR			= ../../../../source/Lib/TLibExtractor
+INC_DIR			= ../../../../source/Lib
 LIB_DIR			= ../../../../lib
 BIN_DIR			= ../../../../bin
@@ -17,9 +17,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR			= ./objects
+OBJ_DIR			= ./objects$(HBD)
 
 # the library name
-PRJ_NAME	 	= TLibExtractor
+PRJ_NAME	 	= TLibExtractor$(HBD)
 
 # version information
Index: branches/HTM-14.1-update-dev0/build/linux/lib/TLibRenderer/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/lib/TLibRenderer/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/lib/TLibRenderer/makefile	(revision 1200)
@@ -17,9 +17,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR			= ./objects
+OBJ_DIR			= ./objects$(HBD)
 
 # the library name
-PRJ_NAME	 	= TLibRenderer
+PRJ_NAME	 	= TLibRenderer$(HBD)
 
 # version information
Index: branches/HTM-14.1-update-dev0/build/linux/lib/TLibVideoIO/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/lib/TLibVideoIO/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/lib/TLibVideoIO/makefile	(revision 1200)
@@ -17,9 +17,15 @@
 USER_LIB_DIRS	=
 
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
 # intermediate directory for object files
-OBJ_DIR			= ./objects
+OBJ_DIR			= ./objects$(HBD)
 
 # the library name
-PRJ_NAME	 	= TLibVideoIO
+PRJ_NAME	 	= TLibVideoIO$(HBD)
 
 # version information
Index: branches/HTM-14.1-update-dev0/build/linux/makefile
===================================================================
--- branches/HTM-14.1-update-dev0/build/linux/makefile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/linux/makefile	(revision 1200)
@@ -14,6 +14,6 @@
 	$(MAKE) -C lib/TLibDecoder 	MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TLibEncoder 	MM32=$(M32) ADDDEFS=$(ADDDEFS)
-	$(MAKE) -C lib/TLibRenderer  MM32=$(M32) ADDDEFS=$(ADDDEFS)
-	$(MAKE) -C lib/TLibExtractor  MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer     MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor    MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppDecoder      MM32=$(M32) ADDDEFS=$(ADDDEFS)
@@ -23,4 +23,6 @@
 	$(MAKE) -C utils/annexBbytecount       MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C utils/convert_NtoMbit_YCbCr MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoderAnalyser      MM32=$(M32) ADDDEFS=$(ADDDEFS)
 
 debug:
@@ -29,6 +31,6 @@
 	$(MAKE) -C lib/TLibDecoder 	debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TLibEncoder 	debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
-	$(MAKE) -C lib/TLibRenderer  debug	MM32=$(M32) ADDDEFS=$(ADDDEFS)
-	$(MAKE) -C lib/TLibExtractor  debug	MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer     debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor    debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
@@ -38,4 +40,6 @@
 	$(MAKE) -C utils/annexBbytecount       debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C utils/convert_NtoMbit_YCbCr debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoderAnalyser      debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
 
 release:
@@ -44,21 +48,24 @@
 	$(MAKE) -C lib/TLibDecoder 	release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TLibEncoder 	release MM32=$(M32) ADDDEFS=$(ADDDEFS)
-	$(MAKE) -C lib/TLibRenderer  release MM32=$(M32) ADDDEFS=$(ADDDEFS)
-	$(MAKE) -C lib/TLibExtractor  release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer     release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor    release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppDecoder      release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppEncoder      release MM32=$(M32) ADDDEFS=$(ADDDEFS)
-	$(MAKE) -C app/TAppRenderer    release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppRenderer     release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppExtractor    release MM32=$(M32) ADDDEFS=$(ADDDEFS)
-	$(MAKE) -C utils/annexBbytecount       release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C utils/annexBbytecount release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C utils/convert_NtoMbit_YCbCr release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoderAnalyser      release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 
-clean:
+clean: clean_highbitdepth
 	$(MAKE) -C lib/TLibVideoIO 	clean MM32=$(M32)
 	$(MAKE) -C lib/TLibCommon 	clean MM32=$(M32)
 	$(MAKE) -C lib/TLibDecoder 	clean MM32=$(M32)
 	$(MAKE) -C lib/TLibEncoder 	clean MM32=$(M32)
-	$(MAKE) -C lib/TLibRenderer  clean MM32=$(M32)
-	$(MAKE) -C lib/TLibExtractor  clean MM32=$(M32)
+	$(MAKE) -C lib/TLibRenderer     clean MM32=$(M32)
+	$(MAKE) -C lib/TLibExtractor    clean MM32=$(M32)
+
 	$(MAKE) -C lib/TAppCommon       clean MM32=$(M32)
 	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32)
@@ -68,2 +75,66 @@
 	$(MAKE) -C utils/annexBbytecount       clean MM32=$(M32)
 	$(MAKE) -C utils/convert_NtoMbit_YCbCr clean MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	clean MM32=$(M32)
+	$(MAKE) -C app/TAppDecoderAnalyser      clean MM32=$(M32)
+
+all_highbitdepth:
+	$(MAKE) -C lib/TLibVideoIO 	MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibCommon 	MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoder 	MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibEncoder 	MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer     MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor    MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TAppCommon       MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoder      MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppEncoder      MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppRenderer     MM32=$(M32) ADDDEFS=$(ADDDEFS) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppExtractor    MM32=$(M32) ADDDEFS=$(ADDDEFS) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoderAnalyser      MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+
+debug_highbitdepth:
+	$(MAKE) -C lib/TLibVideoIO 	debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibCommon 	debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoder 	debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibEncoder 	debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer     debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor    debug M32=$(M32)  HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TAppCommon       debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppEncoder      debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppRenderer     debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppExtractor    debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoderAnalyser debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoderAnalyser debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+
+release_highbitdepth:
+	$(MAKE) -C lib/TLibVideoIO 	release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibCommon 	release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoder 	release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibEncoder 	release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer     release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor    release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TAppCommon       release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoder      release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppEncoder      release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppRenderer     release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppExtractor    release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoderAnalyser release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoderAnalyser release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+
+clean_highbitdepth:
+	$(MAKE) -C lib/TLibVideoIO 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibCommon 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoder 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibEncoder 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibRenderer     clean MM32=$(M32) HIGHBITDEPTH=1 
+	$(MAKE) -C lib/TLibExtractor    clean MM32=$(M32) HIGHBITDEPTH=1  
+	$(MAKE) -C lib/TAppCommon       clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppEncoder      clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppRenderer     clean MM32=$(M32) HIGHBITDEPTH=1 	
+	$(MAKE) -C app/TAppExtractor    clean MM32=$(M32)HIGHBITDEPTH=1 	
+	$(MAKE) -C lib/TLibDecoderAnalyser 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoderAnalyser      clean MM32=$(M32) HIGHBITDEPTH=1
+
+everything: all all_highbitdepth
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppCommon_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppCommon_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppCommon_vc10.vcxproj	(revision 1200)
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppCommon_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,23 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{fb1894c4-d37c-4d7b-b852-ccd81dc75384}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{ffdca758-d453-4e59-857a-f84074ede5ba}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TAppCommon\program_options_lite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj	(revision 1200)
@@ -0,0 +1,199 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppDecoderAnalyser</ProjectName>
+    <ProjectGuid>{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}</ProjectGuid>
+    <RootNamespace>TAppDecoderAnalyser</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;RExt__DECODER_DEBUG_BIT_STATISTICS=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;RExt__DECODER_DEBUG_BIT_STATISTICS=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc10.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc10.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibDecoderAnalyser_vc10.vcxproj">
+      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc10.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,30 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{400c04e5-8a2d-4e65-8d57-f59c30e78110}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{8fc5970e-5673-47ba-999b-aada746c9b46}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppDecoder_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppDecoder_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppDecoder_vc10.vcxproj	(revision 1200)
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppDecoder_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,32 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{1aa8b291-7006-406d-b440-8af60fbc9eb5}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{5e50c4f1-0ca1-47af-8104-45cc6d910254}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppEncoder_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppEncoder_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppEncoder_vc10.vcxproj	(revision 1200)
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppEncoder_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,32 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{e7545260-6a63-49d7-a40f-c50ca7f27a4b}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{45205fc1-f025-43cb-ac9f-2f6b288020ab}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppEncoder\encmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppExtractor_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppExtractor_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppExtractor_vc10.vcxproj	(revision 1200)
@@ -65,10 +65,10 @@
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
     <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
     <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
@@ -90,4 +90,5 @@
     <ClCompile>
       <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <MinimalRebuild>true</MinimalRebuild>
@@ -96,5 +97,4 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
@@ -102,4 +102,24 @@
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
     </Link>
   </ItemDefinitionGroup>
@@ -110,5 +130,6 @@
       <IntrinsicFunctions>false</IntrinsicFunctions>
       <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -116,5 +137,4 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
@@ -122,23 +142,4 @@
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX86</TargetMachine>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <Midl>
-      <TargetEnvironment>X64</TargetEnvironment>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MinimalRebuild>true</MinimalRebuild>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <WarningLevel>Level3</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <SubSystem>Console</SubSystem>
-      <TargetMachine>MachineX64</TargetMachine>
     </Link>
   </ItemDefinitionGroup>
@@ -152,5 +153,6 @@
       <IntrinsicFunctions>false</IntrinsicFunctions>
       <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
Index: branches/HTM-14.1-update-dev0/build/vc10/TAppRenderer_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TAppRenderer_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TAppRenderer_vc10.vcxproj	(revision 1200)
@@ -65,10 +65,10 @@
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
     <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
     <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
@@ -90,4 +90,5 @@
     <ClCompile>
       <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <MinimalRebuild>true</MinimalRebuild>
@@ -96,25 +97,4 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <SubSystem>Console</SubSystem>
-      <TargetMachine>MachineX86</TargetMachine>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <Optimization>MaxSpeed</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>false</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <WarningLevel>Level3</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
@@ -130,4 +110,5 @@
     <ClCompile>
       <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <MinimalRebuild>true</MinimalRebuild>
@@ -136,5 +117,4 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
@@ -142,4 +122,24 @@
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
     </Link>
   </ItemDefinitionGroup>
@@ -153,5 +153,6 @@
       <IntrinsicFunctions>false</IntrinsicFunctions>
       <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -159,5 +160,4 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
@@ -187,9 +187,5 @@
     <ProjectReference Include="TLibRenderer_vc10.vcxproj">
       <Project>{2b298be6-dff0-4bd2-8f26-395ffe7f9eb4}</Project>
-      <Private>true</Private>
       <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-      <CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies>
-      <LinkLibraryDependencies>true</LinkLibraryDependencies>
-      <UseLibraryDependencyInputs>false</UseLibraryDependencyInputs>
     </ProjectReference>
     <ProjectReference Include="TLibVideoIO_vc10.vcxproj">
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibCommon_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibCommon_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibCommon_vc10.vcxproj	(revision 1200)
@@ -144,10 +144,12 @@
   </ItemDefinitionGroup>
   <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp" />
-    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\Debug.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\SEI.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComChromaFormat.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp" />
@@ -166,4 +168,5 @@
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTU.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComWedgelet.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp" />
@@ -171,4 +174,6 @@
   </ItemGroup>
   <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h" />
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h" />
@@ -176,6 +181,5 @@
     <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h" />
-    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h" />
-    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\Debug.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h" />
@@ -183,4 +187,6 @@
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComChromaFormat.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCodingStatistics.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h" />
@@ -196,8 +202,10 @@
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRectangle.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTU.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComWedgelet.h" />
     <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h" />
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibCommon_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,209 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\SEI.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComChromaFormat.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\Debug.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTU.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\Debug.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComChromaFormat.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRectangle.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTU.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCodingStatistics.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj	(revision 1200)
@@ -0,0 +1,177 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibDecoderAnalyser</ProjectName>
+    <ProjectGuid>{68C1251A-55D8-47C9-9052-62F785BD437A}</ProjectGuid>
+    <RootNamespace>TLibDecoderAnalyser</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;RExt__DECODER_DEBUG_BIT_STATISTICS=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;RExt__DECODER_DEBUG_BIT_STATISTICS=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,90 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{a5214d8c-1011-4ba6-a7a8-636f1748895c}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{66740226-f793-4905-a9b1-120c1c15e160}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibDecoder_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,92 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{744fcd72-a655-425f-bb39-3ab96fb48035}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{714796a5-11ae-4ebd-b4ad-0b93c44f8cfc}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibEncoder_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibEncoder_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibEncoder_vc10.vcxproj	(revision 1200)
@@ -145,7 +145,7 @@
   <ItemGroup>
     <ClCompile Include="..\..\source\Lib\TLibEncoder\NALwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIEncoder.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp" />
-    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp" />
@@ -167,4 +167,5 @@
     <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h" />
     <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIEncoder.h" />
     <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h" />
     <ClInclude Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h" />
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibEncoder_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,146 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{0ac2b7f6-dac6-4568-9bf6-f0bc5d3b0ffd}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{eaaa958a-8c26-425a-9733-07b5d97c71eb}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\NALwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIEncoder.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIEncoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibExtractor_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibExtractor_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibExtractor_vc10.vcxproj	(revision 1200)
@@ -68,4 +68,6 @@
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
@@ -86,4 +88,5 @@
     <ClCompile>
       <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <MinimalRebuild>true</MinimalRebuild>
@@ -92,5 +95,19 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
     </ClCompile>
   </ItemDefinitionGroup>
@@ -101,23 +118,9 @@
       <IntrinsicFunctions>false</IntrinsicFunctions>
       <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
       <FunctionLevelLinking>true</FunctionLevelLinking>
-      <WarningLevel>Level3</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <Midl>
-      <TargetEnvironment>X64</TargetEnvironment>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MinimalRebuild>true</MinimalRebuild>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
@@ -133,5 +136,6 @@
       <IntrinsicFunctions>false</IntrinsicFunctions>
       <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibRenderer_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibRenderer_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibRenderer_vc10.vcxproj	(revision 1200)
@@ -64,8 +64,8 @@
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
     <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
@@ -86,4 +86,5 @@
     <ClCompile>
       <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <MinimalRebuild>true</MinimalRebuild>
@@ -92,5 +93,19 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
       <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
     </ClCompile>
   </ItemDefinitionGroup>
@@ -101,5 +116,6 @@
       <IntrinsicFunctions>false</IntrinsicFunctions>
       <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -107,20 +123,4 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <Midl>
-      <TargetEnvironment>X64</TargetEnvironment>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MinimalRebuild>true</MinimalRebuild>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <WarningLevel>Level3</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
   </ItemDefinitionGroup>
@@ -134,5 +134,6 @@
       <IntrinsicFunctions>false</IntrinsicFunctions>
       <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -140,5 +141,4 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
   </ItemDefinitionGroup>
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibVideoIO_vc10.vcxproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 1200)
Index: branches/HTM-14.1-update-dev0/build/vc10/TLibVideoIO_vc10.vcxproj.filters
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 1200)
+++ branches/HTM-14.1-update-dev0/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 1200)
@@ -0,0 +1,23 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{6deae16b-79a7-4141-88d0-fb015f23f586}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{62ba4b7c-b50d-4cba-abba-51619954bc1e}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: branches/HTM-14.1-update-dev0/build/vc8/TLibCommon_vc8.vcproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc8/TLibCommon_vc8.vcproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc8/TLibCommon_vc8.vcproj	(revision 1200)
@@ -2,5 +2,5 @@
 <VisualStudioProject
 	ProjectType="Visual C++"
-	Version="8,00"
+	Version="8.00"
 	Name="TLibCommon"
 	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
@@ -289,4 +289,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\Debug.cpp"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
 				>
@@ -305,4 +309,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComChromaFormat.cpp"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
 				>
@@ -366,4 +374,8 @@
 			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTU.cpp"
 				>
 			</File>
@@ -407,4 +419,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\Debug.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
 				>
@@ -435,4 +451,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComChromaFormat.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
 				>
@@ -487,4 +507,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRectangle.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
 				>
@@ -500,4 +524,8 @@
 			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTU.h"
 				>
 			</File>
Index: branches/HTM-14.1-update-dev0/build/vc8/TLibEncoder_vc8.vcproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc8/TLibEncoder_vc8.vcproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc8/TLibEncoder_vc8.vcproj	(revision 1200)
@@ -284,4 +284,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIEncoder.cpp"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
 				>
@@ -289,8 +293,4 @@
 			<File
 				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp"
-				>
-			</File>
-			<File
-				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp"
 				>
 			</File>
@@ -366,4 +366,8 @@
 			<File
 				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIEncoder.h"
 				>
 			</File>
Index: branches/HTM-14.1-update-dev0/build/vc9/TLibCommon_vc9.vcproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc9/TLibCommon_vc9.vcproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc9/TLibCommon_vc9.vcproj	(revision 1200)
@@ -2,5 +2,5 @@
 <VisualStudioProject
 	ProjectType="Visual C++"
-	Version="9,00"
+	Version="9.00"
 	Name="TLibCommon"
 	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
@@ -292,4 +292,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\Debug.cpp"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
 				>
@@ -308,4 +312,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComChromaFormat.cpp"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
 				>
@@ -369,4 +377,8 @@
 			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTU.cpp"
 				>
 			</File>
@@ -410,4 +422,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\Debug.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
 				>
@@ -438,4 +454,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComChromaFormat.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
 				>
@@ -490,4 +510,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRectangle.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
 				>
@@ -503,4 +527,8 @@
 			<File
 				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTU.h"
 				>
 			</File>
Index: branches/HTM-14.1-update-dev0/build/vc9/TLibEncoder_vc9.vcproj
===================================================================
--- branches/HTM-14.1-update-dev0/build/vc9/TLibEncoder_vc9.vcproj	(revision 1199)
+++ branches/HTM-14.1-update-dev0/build/vc9/TLibEncoder_vc9.vcproj	(revision 1200)
@@ -287,4 +287,8 @@
 			</File>
 			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIEncoder.cpp"
+				>
+			</File>
+			<File
 				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
 				>
@@ -292,8 +296,4 @@
 			<File
 				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp"
-				>
-			</File>
-			<File
-				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp"
 				>
 			</File>
@@ -369,4 +369,8 @@
 			<File
 				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIEncoder.h"
 				>
 			</File>
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view+depth_AllIntra.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view+depth_AllIntra.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view+depth_AllIntra.cfg	(revision 1200)
@@ -103,10 +103,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view_AllIntra.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view_AllIntra.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view_AllIntra.cfg	(revision 1200)
@@ -88,10 +88,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view+depth_AllIntra.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view+depth_AllIntra.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view+depth_AllIntra.cfg	(revision 1200)
@@ -122,10 +122,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view_AllIntra.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view_AllIntra.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view_AllIntra.cfg	(revision 1200)
@@ -101,10 +101,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/fco/baseCfg_3view+depth.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/fco/baseCfg_3view+depth.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/fco/baseCfg_3view+depth.cfg	(revision 1200)
@@ -171,10 +171,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0 1 1 0 1 0         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/rc/baseCfg_3view+depth_rate_control.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/rc/baseCfg_3view+depth_rate_control.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/NonCTC/rc/baseCfg_3view+depth_rate_control.cfg	(revision 1200)
@@ -171,10 +171,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_2view+depth.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_2view+depth.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_2view+depth.cfg	(revision 1200)
@@ -137,10 +137,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 
@@ -241,4 +241,5 @@
 
 
+WarnUnknowParameter       : 1
 
 ### DO NOT ADD ANYTHING BELOW THIS LINE ###
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_2view.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_2view.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_2view.cfg	(revision 1200)
@@ -107,10 +107,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 
@@ -189,4 +189,6 @@
 DepthBasedBlkPartFlag               : 0                # Depth-based Block Partitioning
 
+WarnUnknowParameter       : 1
+
 ### DO NOT ADD ANYTHING BELOW THIS LINE ###
 ### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_3view+depth.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_3view+depth.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_3view+depth.cfg	(revision 1200)
@@ -171,10 +171,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
@@ -273,4 +273,5 @@
 
 
+WarnUnknowParameter       : 1
 
 ### DO NOT ADD ANYTHING BELOW THIS LINE ###
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_3view.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_3view.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/baseCfg_3view.cfg	(revision 1200)
@@ -128,10 +128,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
@@ -209,4 +209,6 @@
 DepthBasedBlkPartFlag               : 0                # Depth-based Block Partitioning
 
+WarnUnknowParameter	      : 1
+
 ### DO NOT ADD ANYTHING BELOW THIS LINE ###
 ### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/3D-HEVC/fullCfg.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/3D-HEVC/fullCfg.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/3D-HEVC/fullCfg.cfg	(revision 1200)
@@ -236,10 +236,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
@@ -349,4 +349,5 @@
 
 
+WarnUnknowParameter       : 1
 
 ### DO NOT ADD ANYTHING BELOW THIS LINE ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_high_throughput_rext.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_high_throughput_rext.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_high_throughput_rext.cfg	(revision 1200)
@@ -0,0 +1,117 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile definition ==============
+Profile                       : high-throughput-RExt   # Profile name to use for encoding. Use main (for FDIS main), main10 (for FDIS main10), main-still-picture, main-RExt, high-throughput-RExt, main-SCC
+Tier                          : main        # Tier to use for interpretation of --Level (main or high only)"
+IntraConstraintFlag           : 1           # Intra constraint flag - must be 1 in high-throughput-RExt profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#=========== RExt ============
+ExtendedPrecision                   : 0                # Increased internal accuracies to support high bit depths (not valid in V1 profiles)
+TransformSkipLog2MaxSize            : 2                # Specify transform-skip maximum size. Minimum 2. (not valid in V1 profiles)
+ImplicitResidualDPCM                : 1                # Enable implicitly signalled residual DPCM for intra (also known as sample-adaptive intra predict) (not valid in V1 profiles)
+ExplicitResidualDPCM                : 1                # Enable explicitly signalled residual DPCM for inter (not valid in V1 profiles)
+ResidualRotation                    : 1                # Enable rotation of transform-skipped and transquant-bypassed TUs through 180 degrees prior to entropy coding (not valid in V1 profiles)
+SingleSignificanceMapContext        : 1                # Enable, for transform-skipped and transquant-bypassed TUs, the selection of a single significance map context variable for all coefficients (not valid in V1 profiles)
+IntraReferenceSmoothing             : 1                # 0: Disable use of intra reference smoothing. 1: Enable use of intra reference smoothing (not valid in V1 profiles)
+GolombRiceParameterAdaptation       : 1                # Enable the partial retention of the Golomb-Rice parameter value from one coefficient group to the next
+HighPrecisionPredictionWeighting    : 1                # Use high precision option for weighted prediction (not valid in V1 profiles)
+CrossComponentPrediction            : 1                # Enable the use of cross-component prediction (not valid in V1 profiles)
+AlignCABACBeforeBypass              : 1                # Align the CABAC engine to a defined fraction of a bit prior to coding bypass data. 
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main.cfg	(revision 1200)
@@ -0,0 +1,102 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures 
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main10.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main10.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main10.cfg	(revision 1200)
@@ -0,0 +1,102 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main_rext.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main_rext.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_intra_main_rext.cfg	(revision 1200)
@@ -0,0 +1,115 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile definition ==============
+Profile                       : main-RExt   # Profile name to use for encoding. Use main (for FDIS main), main10 (for FDIS main10), main-still-picture, main-RExt, high-throughput-RExt, main-SCC
+Tier                          : main        # Tier to use for interpretation of --Level (main or high only)"
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#=========== RExt ============
+ExtendedPrecision                   : 0                # Increased internal accuracies to support high bit depths (not valid in V1 profiles)
+TransformSkipLog2MaxSize            : 2                # Specify transform-skip maximum size. Minimum 2. (not valid in V1 profiles)
+ImplicitResidualDPCM                : 1                # Enable implicitly signalled residual DPCM for intra (also known as sample-adaptive intra predict) (not valid in V1 profiles)
+ExplicitResidualDPCM                : 1                # Enable explicitly signalled residual DPCM for inter (not valid in V1 profiles)
+ResidualRotation                    : 1                # Enable rotation of transform-skipped and transquant-bypassed TUs through 180 degrees prior to entropy coding (not valid in V1 profiles)
+SingleSignificanceMapContext        : 1                # Enable, for transform-skipped and transquant-bypassed TUs, the selection of a single significance map context variable for all coefficients (not valid in V1 profiles)
+IntraReferenceSmoothing             : 1                # 0: Disable use of intra reference smoothing. 1: Enable use of intra reference smoothing (not valid in V1 profiles)
+GolombRiceParameterAdaptation       : 1                # Enable the partial retention of the Golomb-Rice parameter value from one coefficient group to the next
+HighPrecisionPredictionWeighting    : 1                # Use high precision option for weighted prediction (not valid in V1 profiles)
+CrossComponentPrediction            : 1                # Enable the use of cross-component prediction (not valid in V1 profiles)
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_P_main.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_P_main.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_P_main.cfg	(revision 1200)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_P_main10.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_P_main10.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_P_main10.cfg	(revision 1200)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main.cfg	(revision 1200)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main10.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main10.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main10.cfg	(revision 1200)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main_rext.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main_rext.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_lowdelay_main_rext.cfg	(revision 1200)
@@ -0,0 +1,129 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile definition ==============
+Profile                       : main-RExt   # Profile name to use for encoding. Use main (for FDIS main), main10 (for FDIS main10), main-still-picture, main-RExt, high-throughput-RExt, main-SCC
+Tier                          : main        # Tier to use for interpretation of --Level (main or high only)"
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+#=========== RExt ============
+ExtendedPrecision                   : 0                # Increased internal accuracies to support high bit depths (not valid in V1 profiles)
+TransformSkipLog2MaxSize            : 2                # Specify transform-skip maximum size. Minimum 2. (not valid in V1 profiles)
+ImplicitResidualDPCM                : 1                # Enable implicitly signalled residual DPCM for intra (also known as sample-adaptive intra predict) (not valid in V1 profiles)
+ExplicitResidualDPCM                : 1                # Enable explicitly signalled residual DPCM for inter (not valid in V1 profiles)
+ResidualRotation                    : 1                # Enable rotation of transform-skipped and transquant-bypassed TUs through 180 degrees prior to entropy coding (not valid in V1 profiles)
+SingleSignificanceMapContext        : 1                # Enable, for transform-skipped and transquant-bypassed TUs, the selection of a single significance map context variable for all coefficients (not valid in V1 profiles)
+IntraReferenceSmoothing             : 1                # 0: Disable use of intra reference smoothing. 1: Enable use of intra reference smoothing (not valid in V1 profiles)
+GolombRiceParameterAdaptation       : 1                # Enable the partial retention of the Golomb-Rice parameter value from one coefficient group to the next
+HighPrecisionPredictionWeighting    : 1                # Use high precision option for weighted prediction (not valid in V1 profiles)
+CrossComponentPrediction            : 1                # Enable the use of cross-component prediction (not valid in V1 profiles)
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main.cfg	(revision 1200)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           2                3         -8 -12 -16             0
+Frame2:  B    4   2        0.3536   0            0              1           2                3         -4  -8   4             1       4        4         1 1 0 1
+Frame3:  B    2   3        0.3536   0            0              2           2                4         -2  -6   2 6           1       2        4         1 1 1 1
+Frame4:  B    1   4        0.68     0            0              3           2                4         -1   1   3 7           1       1        5         1 0 1 1 1
+Frame5:  B    3   4        0.68     0            0              3           2                4         -1  -3   1 5           1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              2           2                3         -2  -6   2             1      -3        5         0 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              3           2                4         -1  -5   1 3           1       1        4         1 1 1 1
+Frame8:  B    7   4        0.68     0            0              3           2                4         -1  -3  -7 1           1      -2        5         1 1 1 1 0
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main10.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main10.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main10.cfg	(revision 1200)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           2                3         -8 -12 -16             0
+Frame2:  B    4   2        0.3536   0            0              1           2                3         -4  -8   4             1       4        4         1 1 0 1
+Frame3:  B    2   3        0.3536   0            0              2           2                4         -2  -6   2 6           1       2        4         1 1 1 1
+Frame4:  B    1   4        0.68     0            0              3           2                4         -1   1   3 7           1       1        5         1 0 1 1 1
+Frame5:  B    3   4        0.68     0            0              3           2                4         -1  -3   1 5           1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              2           2                3         -2  -6   2             1      -3        5         0 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              3           2                4         -1  -5   1 3           1       1        4         1 1 1 1
+Frame8:  B    7   4        0.68     0            0              3           2                4         -1  -3  -7 1           1      -2        5         1 1 1 1 0
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main_rext.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main_rext.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/encoder_randomaccess_main_rext.cfg	(revision 1200)
@@ -0,0 +1,134 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile definition ==============
+Profile                       : main-RExt   # Profile name to use for encoding. Use main (for FDIS main), main10 (for FDIS main10), main-still-picture, main-RExt, high-throughput-RExt, main-SCC
+Tier                          : main        # Tier to use for interpretation of --Level (main or high only)"
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           2                3         -8 -12 -16             0
+Frame2:  B    4   2        0.3536   0            0              1           2                3         -4  -8   4             1       4        4         1 1 0 1
+Frame3:  B    2   3        0.3536   0            0              2           2                4         -2  -6   2 6           1       2        4         1 1 1 1
+Frame4:  B    1   4        0.68     0            0              3           2                4         -1   1   3 7           1       1        5         1 0 1 1 1
+Frame5:  B    3   4        0.68     0            0              3           2                4         -1  -3   1 5           1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              2           2                3         -2  -6   2             1      -3        5         0 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              3           2                4         -1  -5   1 3           1       1        4         1 1 1 1
+Frame8:  B    7   4        0.68     0            0              3           2                4         -1  -3  -7 1           1      -2        5         1 1 1 1 0
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across                                                       
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+#=========== RExt ============
+ExtendedPrecision                   : 0                # Increased internal accuracies to support high bit depths (not valid in V1 profiles)
+TransformSkipLog2MaxSize            : 2                # Specify transform-skip maximum size. Minimum 2. (not valid in V1 profiles)
+ImplicitResidualDPCM                : 1                # Enable implicitly signalled residual DPCM for intra (also known as sample-adaptive intra predict) (not valid in V1 profiles)
+ExplicitResidualDPCM                : 1                # Enable explicitly signalled residual DPCM for inter (not valid in V1 profiles)
+ResidualRotation                    : 1                # Enable rotation of transform-skipped and transquant-bypassed TUs through 180 degrees prior to entropy coding (not valid in V1 profiles)
+SingleSignificanceMapContext        : 1                # Enable, for transform-skipped and transquant-bypassed TUs, the selection of a single significance map context variable for all coefficients (not valid in V1 profiles)
+IntraReferenceSmoothing             : 1                # 0: Disable use of intra reference smoothing. 1: Enable use of intra reference smoothing (not valid in V1 profiles)
+GolombRiceParameterAdaptation       : 1                # Enable the partial retention of the Golomb-Rice parameter value from one coefficient group to the next
+HighPrecisionPredictionWeighting    : 1                # Use high precision option for weighted prediction (not valid in V1 profiles)
+CrossComponentPrediction            : 1                # Enable the use of cross-component prediction (not valid in V1 profiles)
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_lowdelay_main_field_coding.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_lowdelay_main_field_coding.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_lowdelay_main_field_coding.cfg	(revision 1200)
@@ -0,0 +1,140 @@
+#======== File I/O =====================
+InputFile                     :             # Input filename
+InputBitDepth                 :             # Input bitdepth
+FrameRate                     :             # Frame Rate per second
+FrameSkip                     :             # Number of frames to be skipped in input
+SourceWidth                   :             # Input  frame width
+SourceHeight                  :             # Input  frame height
+FramesToBeEncoded             :             # Number of frames to be coded
+FieldCoding                   : 1           # (0: Frame based coding, 1: Field based coding)
+TopFieldFirst                 : 1           # Field parity order (1: Top field first, 0: Bottom field first)
+ConformanceMode		          : 1
+
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main
+Level                         : 6.2
+
+#======== SEI ===========================
+VuiParametersPresent          : 1
+SEIActiveParameterSets        : 1
+SEIPictureTiming              : 1
+FrameFieldInfoPresentFlag     : 1
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     				predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    2   3        0.4624   0		 	 0 				0           8                8         -1 -2 -9 -10	-17 -18 -25 -26	    	0
+Frame2:  B    3   4        0.4624   0		 	 0 				0           8                9         -1 -2 -3 -10 -11 -18 -19 -26 -27	    1      	-1       9         1 1 1 1 1 1 1 1 1
+Frame3:  B    4   2        0.4624   0		 	 0 				0           8                8         -1 -2 -3 -4  -11 -12 -19 -20     	1      	-1       10        1 1 1 1 1 1 1 0 0 1          
+Frame4:  B    5   3        0.4624   0		 	 0 				0           8                9         -1 -2 -3 -4  -5  -12 -13 -20 -21   	1      	-1       9         1 1 1 1 1 1 1 1 1
+Frame5:  B    6   3        0.4624   0		 	 0 				0           8                8         -1 -2 -5 -6  -13 -14 -21 -22	    	1      	-1	     10   	   1 0 0 1 1 1 1 1 1 1
+Frame6:  B    7   4        0.4624   0		 	 0 				0           8                9         -1 -2 -3 -6  -7  -14 -15 -22 -23     1      	-1       9         1 1 1 1 1 1 1 1 1
+Frame7:  B    8   1        0.578    0		 	 0 				0           8                8         -1 -2 -7 -8  -15 -16 -23 -24     	1      	-1       10        1 0 0 1 1 1 1 1 1 1            
+Frame8:  B    9   1        0.578    0		 	 0 				0           8                9         -1 -2 -3 -8  -9  -16 -17 -24 -25     1      	-1       9         1 1 1 1 1 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across                                                       
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag          : 0                # Value of PPS flag.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_2tids.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_2tids.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_2tids.cfg	(revision 1200)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0            0              0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.3536   0            0              0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0            0              1           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              1           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              1           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              1           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 0
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1  =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_field_coding.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_field_coding.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_field_coding.cfg	(revision 1200)
@@ -0,0 +1,152 @@
+#======== File I/O =====================
+InputFile                     :             # Input filename
+InputBitDepth                 :             # Input bitdepth
+FrameRate                     :             # Frame Rate per second
+FrameSkip                     : 	        # Number of frames to be skipped in input
+SourceWidth                   :     	    # Input  frame width
+SourceHeight                  : 	        # Input  frame height
+FramesToBeEncoded             :             # Number of frames to be coded
+FieldCoding					  : 1			#(0: Frame based coding, 1: Field based coding)
+TopFieldFirst				  : 1			# Field parity order (1: Top field first, 0: Bottom field first)
+ConformanceMode				  : 1
+
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main
+Level                         : 6.2
+
+#======== SEI ===========================
+VuiParametersPresent          : 1
+SEIActiveParameterSets        : 1
+SEIPictureTiming              : 1
+FrameFieldInfoPresentFlag     : 1
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 16          # GOP Size (number of B slice = GOPSize-1)
+
+# field coding GOP: Exchanged coding order of 16th and 17th field for more efficient encoding
+#                    When EfficientFieldIRAPEnabled=1 is enabled, this has no additional effect
+
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics  reference pictures   predict deltaRPS #ref_idcs reference idcs 
+              
+Frame1:  B    17  1        0.442    0		 	 0 				0           4                4         -16 -17 -20 -21        0
+Frame2:  B    16  1        0.442    0		 	 0 				0           3                3         -15 -16 1              1       1        5         1 1 0 0 1
+Frame3:  B    8   2        0.3536   0		 	 0 				0           2                4         -7 -8 8 9              1       8        4         1 1 1 1
+Frame4:  B    9   2        0.3536   0		 	 0 				0           2                5         -1 -8 -9 7 8           1      -1        5         1 1 1 1 1
+Frame5:  B    4   3        0.3536   0		 	 0 				0           2                6         -3 -4 4 5 12 13        1       5        6         1 1 1 1 1 1
+Frame6:  B    5   3        0.3536   0		 	 0 				0           2                7         -1 -4 -5 3 4 11 12     1      -1        7         1 1 1 1 1 1 1 
+Frame7:  B    2   3        0.3536   0		 	 0 				0           2                8         -1 -2 2 3 6 7 14 15    1       3        8         1 1 1 1 1 1 1 1  
+Frame8:  B    3   4        0.68     0		 	 0 				0           2                8         -1 -2 1 2 5 6 13 14    1      -1        9         1 0 1 1 1 1 1 1 1 
+Frame9:  B    6   3        0.3536   0		 	 0 				0           2                6         -1 -2 2 3 10 11        1      -3        9         0 0 1 1 1 1 1 1 0
+Frame10: B    7   4        0.68     0		 	 0 				0           2                7         -1 -2 -3 1 2 9 10      1      -1        7         1 1 1 1 1 1 1 
+Frame11: B    12  3        0.3536   0		 	 0 				0           2                4         -3 -4 4 5              1      -5        8         0 0 0 1 1 1 1 0
+Frame12: B    13  3        0.3536   0		 	 0 				0           2                5         -1 -4 -5 3 4           1      -1        5         1 1 1 1 1
+Frame13: B    10  3        0.3536   0		 	 0 				0           2                6         -1 -2 2 3 6 7          1       3        6         1 1 1 1 1 1
+Frame14: B    11  4        0.68     0		 	 0 				0           2                7         -1 -2 -3 1 2 5 6       1      -1        7         1 1 1 1 1 1 1
+Frame15: B    14  3        0.3536   0			 0 				0           2                5         -1 -2 -5 2 3           1      -3        8         0 1 0 1 1 1 1 0
+Frame16: B    15  4        0.68     0			 0 				0           2                6         -1 -2 -3 -6 1 2        1      -1        6         1 1 1 1 1 1 
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1  =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_field_coding_simple_GOP.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_field_coding_simple_GOP.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/misc/encoder_randomaccess_main_field_coding_simple_GOP.cfg	(revision 1200)
@@ -0,0 +1,151 @@
+#======== File I/O =====================
+InputFile                     :             # Input filename
+InputBitDepth                 :             # Input bitdepth
+FrameRate                     :             # Frame Rate per second
+FrameSkip                     : 	        # Number of frames to be skipped in input
+SourceWidth                   :     	    # Input  frame width
+SourceHeight                  : 	        # Input  frame height
+FramesToBeEncoded             :             # Number of frames to be coded
+FieldCoding					  : 1			#(0: Frame based coding, 1: Field based coding)
+TopFieldFirst				  : 1			# Field parity order (1: Top field first, 0: Bottom field first)
+ConformanceMode				  : 1
+
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main
+Level                         : 6.2
+
+#======== SEI ===========================
+VuiParametersPresent          : 1
+SEIActiveParameterSets        : 1
+SEIPictureTiming              : 1
+FrameFieldInfoPresentFlag     : 1
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 16          # GOP Size (number of B slice = GOPSize-1)
+
+#  simple field coding GOP: When EfficientFieldIRAPEnabled=1 is enabled, the order of frames 16 and 17 is exchanged
+
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics  reference pictures   predict deltaRPS #ref_idcs reference idcs 
+              
+Frame1:  B    16  1        0.442    0            0              0           8                8         -15 -16 -19 -20 -23 -24 -31 -32        0
+Frame2:  B    17  1        0.442    0            0              0           4                9         -1  -16 -17 -20 -21 -24 -25 -32 -33    1      -1        9         1 1 1 1 1 1 1 1 1
+Frame3:  B    8   2        0.3536   0            0              0           4                6         -7  -8  -11 -12  8   9                 1       9        10        1 1 1 1 1 0 0 0 0 1
+Frame4:  B    9   3        0.3536   0            0              0           4                7         -1  -8  -9  -12 -13  7   8             1      -1        7         1 1 1 1 1 1 1
+Frame5:  B    4   3        0.3536   0            0              0           4                8         -3  -4  -7  -8   4   5   12  13        1       5        8         1 1 1 1 1 1 1 1
+Frame6:  B    5   4        0.68     0            0              0           4                9         -1  -4  -5  -8  -9   3   4   11  12    1      -1        9         1 1 1 1 1 1 1 1 1 
+Frame7:  B    2   3        0.3536   0            0              0           4                8         -1  -2   2   3   6   7   14  15        1       3        10        1 1 1 0 0 1 1 1 1 1  
+Frame8:  B    3   4        0.68     0            0              0           4                9         -1  -2  -3   1   2   5   6   13  14    1      -1        9         1 1 1 1 1 1 1 1 1 
+Frame9:  B    6   3        0.3536   0            0              0           4                8         -1  -2  -5  -6   2   3   10  11        1      -3        10        0 1 1 1 1 1 1 1 1 0
+Frame10: B    7   4        0.68     0            0              0           4                9         -1  -2  -3  -6  -7   1   2   9   10    1      -1        9         1 1 1 1 1 1 1 1 1 
+Frame11: B    12  3        0.3536   0            0              0           4                8         -3  -4  -7  -8  -11 -12  4   5         1      -5        10        0 1 1 1 1 1 1 1 1 0
+Frame12: B    13  4        0.68     0            0              0           4                9         -1  -4  -5  -8  -9  -12 -13  3   4     1      -1        9         1 1 1 1 1 1 1 1 1
+Frame13: B    10  3        0.3536   0            0              0           4                8         -1  -2  -9  -10  2   3   6   7         1       3        10        1 1 1 0 0 1 1 1 1 1
+Frame14: B    11  4        0.68     0            0              0           4                9         -1  -2  -3  -10 -11  1   2   5   6     1      -1        9         1 1 1 1 1 1 1 1 1
+Frame15: B    14  3        0.3536   0            0              0           4                8         -1  -2  -5  -6  -13 -14  2   3         1      -3        10        0 1 1 1 1 1 1 1 1 0
+Frame16: B    15  4        0.68     0            0              0           4                9         -1  -2  -3  -6  -7  -14 -15  1   2     1      -1        9         1 1 1 1 1 1 1 1 1  
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1  =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across                                                       
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQMall.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQMall.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQMall.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BQMall_832x480_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 3.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQSquare.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQSquare.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQSquare.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BQSquare_416x240_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 416         # Input  frame width
+SourceHeight                  : 240         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 2.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQTerrace.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQTerrace.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BQTerrace.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BQTerrace_1920x1080_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 4.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrill.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrill.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrill.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BasketballDrill_832x480_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrillText.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrillText.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrillText.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : BasketballDrillText_832x480_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrive.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrive.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballDrive.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BasketballDrive_1920x1080_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 4.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballPass.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballPass.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballPass.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BasketballPass_416x240_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 416         # Input  frame width
+SourceHeight                  : 240         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 2.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballScreen_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballScreen_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballScreen_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/Basketball_Screen_2560x1440_60p_8b444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 322         # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1440        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballScreen_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballScreen_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BasketballScreen_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/Basketball_Screen_2560x1440_60p_8b444.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 322         # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1440        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BirdsInCage_444_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BirdsInCage_444_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BirdsInCage_444_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_444/BirdsInCage_1920x1080_60_10bit_444.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BlowingBubbles.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BlowingBubbles.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/BlowingBubbles.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BlowingBubbles_416x240_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 416         # Input  frame width
+SourceHeight                  : 240         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 2.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Bubbles_RGB_16bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Bubbles_RGB_16bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Bubbles_RGB_16bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB_16bit/Bubbles_4096x2160_24_16bit_444.rgb
+InputBitDepth                 : 16          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 4096        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 120         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_cad_waveform_1920x1080_20_8bit_200_444_r1.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_cad_waveform_1920x1080_20_8bit_200_gbr.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CADWaveform_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_cad_waveform_1920x1080_20_8bit_200_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Cactus.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Cactus.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Cactus.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/Cactus_1920x1080_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 4.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Cardiac_400_12bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Cardiac_400_12bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Cardiac_400_12bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_400/CT_Cardiac_512x512_12bit_400.yuv
+InputBitDepth                 : 12          # Input bitdepth
+InputChromaFormat             : 400         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 512         # Input  frame width
+SourceHeight                  : 512         # Input  frame height
+FramesToBeEncoded             : 281         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ChinaSpeed.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ChinaSpeed.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ChinaSpeed.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ChinaSpeed_1024x768_30.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1024        # Input  frame width
+SourceHeight                  : 768         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Console_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Console_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Console_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_console_1920x1080_60_8bit_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Console_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Console_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Console_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_console_1920x1080_60_8bit_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CrowdRun_444_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CrowdRun_444_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CrowdRun_444_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_444/CrowdRun_1920x1080_50_10bit_444.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CrowdRun_RGB_16bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CrowdRun_RGB_16bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/CrowdRun_RGB_16bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB_16bit/CrowdRun_1920x1080_50_16bit_444.rgb
+InputBitDepth                 : 16          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Desktop_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Desktop_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Desktop_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_desktop_1920x1080_60_8bit_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Desktop_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Desktop_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Desktop_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_desktop_1920x1080_60_8bit_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Doc_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Doc_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Doc_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_doc_1280x720_10_8bit_500_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 10          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Doc_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Doc_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Doc_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_doc_1280x720_10_8bit_500.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 10          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/DucksAndLegs_RGB_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/DucksAndLegs_RGB_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/DucksAndLegs_RGB_10bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/DucksAndLegs_1920x1080_30_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/DucksTakeOff_RGB_16bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/DucksTakeOff_RGB_16bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/DucksTakeOff_RGB_16bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB_16bit/DucksTakeOff_1920x1080_50_16bit_444.rgb
+InputBitDepth                 : 16          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUGraphics_422_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUGraphics_422_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUGraphics_422_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_422/EBUGraphics_1920x1080_50_10bit_422.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 422         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUHorse_422_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUHorse_422_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUHorse_422_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_422/EBUHorse_1920x1080_50_10bit_422.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 422         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUKidsSoccer_422_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUKidsSoccer_422_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUKidsSoccer_422_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_422/EBUKidsSoccer_1920x1080_50_10bit_422.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 422         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBULupoCandlelight_444_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBULupoCandlelight_444_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBULupoCandlelight_444_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_444/EBULupoCandlelight_1920x1080_50_10bit_444.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBULupoCandlelight_RGB_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBULupoCandlelight_RGB_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBULupoCandlelight_RGB_10bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/EBULupoCandlelight_1920x1080_50_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_444_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_444_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_444_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_444/EBURainFruits_1920x1080_50_10bit_444.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+2MSB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+2MSB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+2MSB.cfg	(revision 1200)
@@ -0,0 +1,15 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/EBURainFruits_1920x1080_50_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+MSBExtendedBitDepth           : 12          # bit depth after addition of MSBs
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+4MSB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+4MSB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+4MSB.cfg	(revision 1200)
@@ -0,0 +1,15 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/EBURainFruits_1920x1080_50_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+MSBExtendedBitDepth           : 14          # bit depth after addition of MSBs
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+6MSB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+6MSB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit+6MSB.cfg	(revision 1200)
@@ -0,0 +1,15 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/EBURainFruits_1920x1080_50_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+MSBExtendedBitDepth           : 16          # bit depth after addition of MSBs
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBURainFruits_RGB_10bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/EBURainFruits_1920x1080_50_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUWaterRocksClose_422_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUWaterRocksClose_422_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/EBUWaterRocksClose_422_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_422/EBUWaterRocksClose_1920x1080_50_10bit_422.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 422         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FlyingGraphics_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FlyingGraphics_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FlyingGraphics_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_flyingGraphics_1920x1080_60_8bit_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FlyingGraphics_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FlyingGraphics_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FlyingGraphics_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_flyingGraphics_1920x1080_60_8bit_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FourPeople.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FourPeople.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FourPeople.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/FourPeople_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 4
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FruitStall_RGB_16bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FruitStall_RGB_16bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/FruitStall_RGB_16bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB_16bit/FruitStall_1920x1080_24_16bit_444.rgb
+InputBitDepth                 : 16          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Head_400_16bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Head_400_16bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Head_400_16bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_400/AX_Head_1240x960_16bit_400.yuv
+InputBitDepth                 : 16          # Input bitdepth
+InputChromaFormat             : 400         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1240        # Input  frame width
+SourceHeight                  : 960         # Input  frame height
+FramesToBeEncoded             : 496         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/InToTree_RGB_16bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/InToTree_RGB_16bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/InToTree_RGB_16bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB_16bit/InToTree_1920x1080_50_16bit_444.rgb
+InputBitDepth                 : 16          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Johnny.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Johnny.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Johnny.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/Johnny_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 4
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/Kimono1_1920x1080_24.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level                         : 4
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_422_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_422_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_422_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_422/Kimono1_1920x1080_24_10bit_422.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 422         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_444_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_444_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_444_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_444/Kimono1_1920x1080_24_10bit_444.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+2MSB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+2MSB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+2MSB.cfg	(revision 1200)
@@ -0,0 +1,15 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/Kimono1_1920x1080_24_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+MSBExtendedBitDepth           : 12          # bit depth after addition of MSBs
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+4MSB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+4MSB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+4MSB.cfg	(revision 1200)
@@ -0,0 +1,15 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/Kimono1_1920x1080_24_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+MSBExtendedBitDepth           : 14          # bit depth after addition of MSBs
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+6MSB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+6MSB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit+6MSB.cfg	(revision 1200)
@@ -0,0 +1,15 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/Kimono1_1920x1080_24_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+MSBExtendedBitDepth           : 16          # bit depth after addition of MSBs
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Kimono_RGB_10bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/Kimono1_1920x1080_24_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/KristenAndSara.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/KristenAndSara.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/KristenAndSara.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/KristenAndSara_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 4
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/LongRunShort_400_12bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/LongRunShort_400_12bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/LongRunShort_400_12bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_400/CT_LongrunShort_512x512_12bit_400.yuv
+InputBitDepth                 : 12          # Input bitdepth
+InputChromaFormat             : 400         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 512         # Input  frame width
+SourceHeight                  : 512         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_map_1280x720_60_8bit_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_map_1280x720_60_8bit.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Map_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_map_1280x720_60_8bit.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl2_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl2_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl2_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/MissionControlClip2_2560x1440_60p_8b444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 120         # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1440        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl2_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl2_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl2_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/MissionControlClip2_2560x1440_60p_8b444.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 120         # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1440        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl3_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl3_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl3_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/MissionControlClip3_1920x1080_60p_8b444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl3_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl3_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/MissionControl3_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/MissionControlClip3_1920x1080_60p_8b444.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/NebutaFestival_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/NebutaFestival_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/NebutaFestival_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : NebutaFestival_2560x1600_60_10bit_crop.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/OldTownCross_RGB_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/OldTownCross_RGB_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/OldTownCross_RGB_10bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/OldTownCross_1920x1080_50_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/OldTownCross_RGB_16bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/OldTownCross_RGB_16bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/OldTownCross_RGB_16bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB_16bit/OldTownCross_1920x1080_50_16bit_444.rgb
+InputBitDepth                 : 16          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_pcb_layout_1920x1080_20_8bit_200_444_r1.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_pcb_layout_1920x1080_20_8bit_200_gbr.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PCBLayout_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_pcb_layout_1920x1080_20_8bit_200_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkJoy_RGB_16bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkJoy_RGB_16bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkJoy_RGB_16bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB_16bit/ParkJoy_1920x1080_50_16bit_444.rgb
+InputBitDepth                 : 16          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkScene.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkScene.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkScene.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/ParkScene_1920x1080_24.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level                         : 4
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkScene_RGB_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkScene_RGB_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ParkScene_RGB_10bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/ParkScene_1920x1080_24_10bit_444.rgb
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 240         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PartyScene.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PartyScene.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PartyScene.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/PartyScene_832x480_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PeopleOnStreet.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PeopleOnStreet.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/PeopleOnStreet.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/PeopleOnStreet_2560x1600_30_crop.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level                         : 5
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_programming_1280x720_60_8bit_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_programming_1280x720_60_8bit.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Programming_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_programming_1280x720_60_8bit.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/RaceHorses.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/RaceHorses.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/RaceHorses.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/RaceHorses_416x240_30.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 416         # Input  frame width
+SourceHeight                  : 240         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/RaceHorsesC.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/RaceHorsesC.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/RaceHorsesC.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/RaceHorses_832x480_30.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 3
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Seeking_422_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Seeking_422_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Seeking_422_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_422/Seeking_1920x1080_50_10bit_422.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 422         # Ratio of luminance to chrominance samples
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideEditing.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideEditing.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideEditing.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : SlideEditing_1280x720_30.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 3.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : SlideShow_1280x720_20.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_SlideShow_1280x720_20_8bit_500_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SlideShow_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_SlideShow_1280x720_20_8bit_500.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SocialNetworkMap_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SocialNetworkMap_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SocialNetworkMap_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_socialNetworkMap_1920x1080_60_8bit_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SocialNetworkMap_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SocialNetworkMap_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SocialNetworkMap_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_socialNetworkMap_1920x1080_60_8bit_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : SteamLocomotiveTrain_2560x1600_60_10bit_crop.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/Traffic_2560x1600_30_crop.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level                         : 5
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_422_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_422_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_422_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_422/Traffic_2560x1600_30_10bit_422_crop.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 422         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_444_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_444_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_444_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_444/Traffic_2560x1600_30_10bit_444_crop.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_RGB_12bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_RGB_12bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Traffic_RGB_12bit.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/Traffic_2560x1600_30_12bit_444.rgb
+InputBitDepth                 : 12          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded             : 150         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_cg_twist_tunnel_1280x720_30_8bit_300_444_r1.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_cg_twist_tunnel_1280x720_30_8bit_gbr.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/TwistTunnel_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_cg_twist_tunnel_1280x720_30_8bit_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_444_10bit.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_444_10bit.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_444_10bit.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_444/VenueVu_1920x1080_30_10bit_444.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/VenueVu_1920x1080_30_8bit_444_gbr.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VenueVu_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/RExt_RGB/VenueVu_1920x1080_30_8bit_444.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file. 
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_video_conferencing_doc_sharing_1280x720_30_8bit_300_444_r1.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_video_conferencing_doc_sharing_1280x720_30_8bit_300_gbr.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/VideoConferencingDocSharing_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_video_conferencing_doc_sharing_1280x720_30_8bit_300_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo1.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo1.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo1.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/vidyo1_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 4
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo3.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo3.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo3.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/vidyo3_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 4
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo4.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo4.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Vidyo4.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/vidyo4_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 4
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_web_browsing_1280x720_30_8bit_300_444_r1.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_web_browsing_1280x720_30_8bit_300_gbr.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WebBrowsing_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_web_browsing_1280x720_30_8bit_300_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Web_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Web_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Web_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_Web_1280x720_10_8bit_500_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 10          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Web_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Web_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/Web_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_Web_1280x720_10_8bit_500.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 10          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 500         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_wordEditing_1280x720_60_8bit_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_wordEditing_1280x720_60_8bit.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/WordEditing_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_wordEditing_1280x720_60_8bit.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 600         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_444.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_444.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_444.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_ppt_doc_xls_1920x1080_20_8bit_200_444_r1.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_GBR.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_GBR.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_GBR.cfg	(revision 1200)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_GBR/sc_ppt_doc_xls_1920x1080_20_8bit_200_gbr.gbr
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_RGB.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_RGB.cfg	(revision 1200)
+++ branches/HTM-14.1-update-dev0/cfg/HM/per-sequence/ppt_doc_xls_RGB.cfg	(revision 1200)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_ppt_doc_xls_1920x1080_20_8bit_200_rgb.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 20          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920        # Input  frame width
+SourceHeight                  : 1080        # Input  frame height
+FramesToBeEncoded             : 200         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: branches/HTM-14.1-update-dev0/cfg/MV-HEVC/baseCfg_2view.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/MV-HEVC/baseCfg_2view.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/MV-HEVC/baseCfg_2view.cfg	(revision 1200)
@@ -106,10 +106,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 
Index: branches/HTM-14.1-update-dev0/cfg/MV-HEVC/baseCfg_3view.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/MV-HEVC/baseCfg_3view.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/MV-HEVC/baseCfg_3view.cfg	(revision 1200)
@@ -132,10 +132,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
Index: branches/HTM-14.1-update-dev0/cfg/MV-HEVC/fullCfg.cfg
===================================================================
--- branches/HTM-14.1-update-dev0/cfg/MV-HEVC/fullCfg.cfg	(revision 1199)
+++ branches/HTM-14.1-update-dev0/cfg/MV-HEVC/fullCfg.cfg	(revision 1200)
@@ -238,10 +238,10 @@
 
 #=========== Deblock Filter ============
-DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
-LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
Index: branches/HTM-14.1-update-dev0/doc/Doxyfile
===================================================================
--- branches/HTM-14.1-update-dev0/doc/Doxyfile	(revision 1199)
+++ branches/HTM-14.1-update-dev0/doc/Doxyfile	(revision 1200)
@@ -1,13 +1,16 @@
-# Doxyfile 1.7.5
+# Doxyfile 1.8.9.1
 
 # This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project
-#
-# All text after a hash (#) is considered a comment and will be ignored
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+#
+# All text after a single hash (#) is considered a comment and will be ignored.
 # The format is:
-#       TAG = value [value, ...]
-# For lists items can also be appended using:
-#       TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (" ")
+# TAG = value [value, ...]
+# For lists, items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (\" \").
 
 #---------------------------------------------------------------------------
@@ -15,89 +18,104 @@
 #---------------------------------------------------------------------------
 
-# This tag specifies the encoding used for all characters in the config file 
-# that follow. The default is UTF-8 which is also the encoding used for all 
-# text before the first occurrence of this tag. Doxygen uses libiconv (or the 
-# iconv built into libc) for the transcoding. See 
-# http://www.gnu.org/software/libiconv for the list of possible encodings.
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all text
+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
+# for the list of possible encodings.
+# The default value is: UTF-8.
 
 DOXYFILE_ENCODING      = UTF-8
 
-# The PROJECT_NAME tag is a single word (or sequence of words) that should 
-# identify the project. Note that if you do not use Doxywizard you need 
-# to put quotes around the project name if it contains spaces.
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
 
 PROJECT_NAME           = "HEVC Test Model (HM)"
 
-# The PROJECT_NUMBER tag can be used to enter a project or revision number. 
-# This could be handy for archiving the generated documentation or 
-# if some version control system is used.
-
-PROJECT_NUMBER         = HM-14.0
-
-# Using the PROJECT_BRIEF tag one can provide an optional one line description 
-# for a project that appears at the top of each page and should give viewer 
-# a quick idea about the purpose of the project. Keep the description short.
-
-PROJECT_BRIEF          = 
-
-# With the PROJECT_LOGO tag one can specify an logo or icon that is 
-# included in the documentation. The maximum height of the logo should not 
-# exceed 55 pixels and the maximum width should not exceed 200 pixels. 
-# Doxygen will copy the logo to the output directory.
-
-PROJECT_LOGO           = 
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) 
-# base path where the generated documentation will be put. 
-# If a relative path is entered, it will be relative to the location 
-# where doxygen was started. If left blank the current directory will be used.
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
+# could be handy for archiving the generated documentation or if some version
+# control system is used.
+
+PROJECT_NUMBER         = HM-16.4
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          =
+
+# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
+# in the documentation. The maximum height of the logo should not exceed 55
+# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
+# the logo to the output directory.
+
+PROJECT_LOGO           =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. If a relative path is
+# entered, it will be relative to the location where doxygen was started. If
+# left blank the current directory will be used.
 
 OUTPUT_DIRECTORY       = .
 
-# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 
-# 4096 sub-directories (in 2 levels) under the output directory of each output 
-# format and will distribute the generated files over these directories. 
-# Enabling this option can be useful when feeding doxygen a huge amount of 
-# source files, where putting all generated files in the same directory would 
-# otherwise cause performance problems for the file system.
+# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
+# directories (in 2 levels) under the output directory of each output format and
+# will distribute the generated files over these directories. Enabling this
+# option can be useful when feeding doxygen a huge amount of source files, where
+# putting all generated files in the same directory would otherwise causes
+# performance problems for the file system.
+# The default value is: NO.
 
 CREATE_SUBDIRS         = NO
 
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all 
-# documentation generated by doxygen is written. Doxygen will use this 
-# information to generate all constant output in the proper language. 
-# The default language is English, other supported languages are: 
-# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, 
-# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, 
-# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English 
-# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, 
-# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, 
-# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
+# characters to appear in the names of generated files. If set to NO, non-ASCII
+# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
+# U+3044.
+# The default value is: NO.
+
+ALLOW_UNICODE_NAMES    = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
+# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
+# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
+# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
+# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
+# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
+# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
+# Ukrainian and Vietnamese.
+# The default value is: English.
 
 OUTPUT_LANGUAGE        = English
 
-# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will 
-# include brief member descriptions after the members that are listed in 
-# the file and class documentation (similar to JavaDoc). 
-# Set to NO to disable this.
+# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
+# descriptions after the members that are listed in the file and class
+# documentation (similar to Javadoc). Set to NO to disable this.
+# The default value is: YES.
 
 BRIEF_MEMBER_DESC      = YES
 
-# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend 
-# the brief description of a member or function before the detailed description. 
-# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the 
+# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
+# description of a member or function before the detailed description
+#
+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
 # brief descriptions will be completely suppressed.
+# The default value is: YES.
 
 REPEAT_BRIEF           = YES
 
-# This tag implements a quasi-intelligent brief description abbreviator 
-# that is used to form the text in various listings. Each string 
-# in this list, if found as the leading text of the brief description, will be 
-# stripped from the text and the result after processing the whole list, is 
-# used as the annotated text. Otherwise, the brief description is used as-is. 
-# If left blank, the following values are used ("$name" is automatically 
-# replaced with the name of the entity): "The $name class" "The $name widget" 
-# "The $name file" "is" "provides" "specifies" "contains" 
-# "represents" "a" "an" "the"
+# This tag implements a quasi-intelligent brief description abbreviator that is
+# used to form the text in various listings. Each string in this list, if found
+# as the leading text of the brief description, will be stripped from the text
+# and the result, after processing the whole list, is used as the annotated
+# text. Otherwise, the brief description is used as-is. If left blank, the
+# following values are used ($name is automatically replaced with the name of
+# the entity):The $name class, The $name widget, The $name file, is, provides,
+# specifies, contains, represents, a, an and the.
 
 ABBREVIATE_BRIEF       = "The $name class" \
@@ -113,220 +131,280 @@
                          the
 
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then 
-# Doxygen will generate a detailed section even if there is only a brief 
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# doxygen will generate a detailed section even if there is only a brief
 # description.
+# The default value is: NO.
 
 ALWAYS_DETAILED_SEC    = NO
 
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all 
-# inherited members of a class in the documentation of that class as if those 
-# members were ordinary class members. Constructors, destructors and assignment 
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
 # operators of the base classes will not be shown.
+# The default value is: NO.
 
 INLINE_INHERITED_MEMB  = NO
 
-# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full 
-# path before files name in the file list and in the header files. If set 
-# to NO the shortest path that makes the file name unique will be used.
+# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
+# before files name in the file list and in the header files. If set to NO the
+# shortest path that makes the file name unique will be used
+# The default value is: YES.
 
 FULL_PATH_NAMES        = YES
 
-# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag 
-# can be used to strip a user-defined part of the path. Stripping is 
-# only done if one of the specified strings matches the left-hand part of 
-# the path. The tag can be used to show relative paths in the file list. 
-# If left blank the directory from which doxygen is run is used as the 
-# path to strip.
+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
+# Stripping is only done if one of the specified strings matches the left-hand
+# part of the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the path to
+# strip.
+#
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
 
 STRIP_FROM_PATH        = ../source
 
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of 
-# the path mentioned in the documentation of a class, which tells 
-# the reader which header file to include in order to use a class. 
-# If left blank only the name of the header file containing the class 
-# definition is used. Otherwise one should specify the include paths that 
-# are normally passed to the compiler using the -I flag.
-
-STRIP_FROM_INC_PATH    = 
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter 
-# (but less readable) file names. This can be useful if your file system 
-# doesn't support long names like on DOS, Mac, or CD-ROM.
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
+# path mentioned in the documentation of a class, which tells the reader which
+# header file to include in order to use a class. If left blank only the name of
+# the header file containing the class definition is used. Otherwise one should
+# specify the list of include paths that are normally passed to the compiler
+# using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
+# less readable) file names. This can be useful is your file systems doesn't
+# support long names like on DOS, Mac, or CD-ROM.
+# The default value is: NO.
 
 SHORT_NAMES            = NO
 
-# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen 
-# will interpret the first line (until the first dot) of a JavaDoc-style 
-# comment as the brief description. If set to NO, the JavaDoc 
-# comments will behave just like regular Qt-style comments 
-# (thus requiring an explicit @brief command for a brief description.)
+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
+# first line (until the first dot) of a Javadoc-style comment as the brief
+# description. If set to NO, the Javadoc-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
 
 JAVADOC_AUTOBRIEF      = NO
 
-# If the QT_AUTOBRIEF tag is set to YES then Doxygen will 
-# interpret the first line (until the first dot) of a Qt-style 
-# comment as the brief description. If set to NO, the comments 
-# will behave just like regular Qt-style comments (thus requiring 
-# an explicit \brief command for a brief description.)
+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
+# line (until the first dot) of a Qt-style comment as the brief description. If
+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
 
 QT_AUTOBRIEF           = NO
 
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen 
-# treat a multi-line C++ special comment block (i.e. a block of //! or /// 
-# comments) as a brief description. This used to be the default behaviour. 
-# The new default is to treat a multi-line C++ comment block as a detailed 
-# description. Set this tag to YES if you prefer the old behaviour instead.
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
+# a brief description. This used to be the default behavior. The new default is
+# to treat a multi-line C++ comment block as a detailed description. Set this
+# tag to YES if you prefer the old behavior instead.
+#
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
 
 MULTILINE_CPP_IS_BRIEF = NO
 
-# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented 
-# member inherits the documentation from any documented member that it 
-# re-implements.
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
 
 INHERIT_DOCS           = YES
 
-# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce 
-# a new page for each member. If set to NO, the documentation of a member will 
-# be part of the file/class/namespace that contains it.
+# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
+# page for each member. If set to NO, the documentation of a member will be part
+# of the file/class/namespace that contains it.
+# The default value is: NO.
 
 SEPARATE_MEMBER_PAGES  = NO
 
-# The TAB_SIZE tag can be used to set the number of spaces in a tab. 
-# Doxygen uses this value to replace tabs by spaces in code fragments.
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
+# uses this value to replace tabs by spaces in code fragments.
+# Minimum value: 1, maximum value: 16, default value: 4.
 
 TAB_SIZE               = 8
 
-# This tag can be used to specify a number of aliases that acts 
-# as commands in the documentation. An alias has the form "name=value". 
-# For example adding "sideeffect=\par Side Effects:\n" will allow you to 
-# put the command \sideeffect (or @sideeffect) in the documentation, which 
-# will result in a user-defined paragraph with heading "Side Effects:". 
-# You can put \n's in the value part of an alias to insert newlines.
-
-ALIASES                = 
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C 
-# sources only. Doxygen will then generate output that is more tailored for C. 
-# For instance, some of the names that are used will be different. The list 
-# of all members will be omitted, etc.
+# This tag can be used to specify a number of aliases that act as commands in
+# the documentation. An alias has the form:
+# name=value
+# For example adding
+# "sideeffect=@par Side Effects:\n"
+# will allow you to put the command \sideeffect (or @sideeffect) in the
+# documentation, which will result in a user-defined paragraph with heading
+# "Side Effects:". You can put \n's in the value part of an alias to insert
+# newlines.
+
+ALIASES                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
+# only. Doxygen will then generate output that is more tailored for C. For
+# instance, some of the names that are used will be different. The list of all
+# members will be omitted, etc.
+# The default value is: NO.
 
 OPTIMIZE_OUTPUT_FOR_C  = NO
 
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java 
-# sources only. Doxygen will then generate output that is more tailored for 
-# Java. For instance, namespaces will be presented as packages, qualified 
-# scopes will look different, etc.
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
 
 OPTIMIZE_OUTPUT_JAVA   = NO
 
-# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran 
-# sources only. Doxygen will then generate output that is more tailored for 
-# Fortran.
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
 
 OPTIMIZE_FOR_FORTRAN   = NO
 
-# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL 
-# sources. Doxygen will then generate output that is tailored for 
-# VHDL.
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for VHDL.
+# The default value is: NO.
 
 OPTIMIZE_OUTPUT_VHDL   = NO
 
-# Doxygen selects the parser to use depending on the extension of the files it 
-# parses. With this tag you can assign which parser to use for a given extension. 
-# Doxygen has a built-in mapping, but you can override or extend it using this 
-# tag. The format is ext=language, where ext is a file extension, and language 
-# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, 
-# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make 
-# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C 
-# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions 
-# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
-
-EXTENSION_MAPPING      = 
-
-# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want 
-# to include (a tag file for) the STL sources as input, then you should 
-# set this tag to YES in order to let doxygen match functions declarations and 
-# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. 
-# func(std::string) {}). This also makes the inheritance and collaboration 
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension, and
+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
+# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
+# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
+# Fortran. In the later case the parser tries to guess whether the code is fixed
+# or free formatted code, this is the default for Fortran type files), VHDL. For
+# instance to make doxygen treat .inc files as Fortran files (default is PHP),
+# and .f files as C (default is Fortran), use: inc=Fortran f=C.
+#
+# Note: For files without extension you can use no_extension as a placeholder.
+#
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT       = YES
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by putting a % sign in front of the word or
+# globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should set this
+# tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string);
+# versus func(std::string) {}). This also make the inheritance and collaboration
 # diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
 
 BUILTIN_STL_SUPPORT    = YES
 
-# If you use Microsoft's C++/CLI language, you should set this option to YES to 
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
 # enable parsing support.
+# The default value is: NO.
 
 CPP_CLI_SUPPORT        = NO
 
-# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. 
-# Doxygen will parse them like normal C++ but will assume all classes use public 
-# instead of private inheritance when no explicit protection keyword is present.
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
+# will parse them like normal C++ but will assume all classes use public instead
+# of private inheritance when no explicit protection keyword is present.
+# The default value is: NO.
 
 SIP_SUPPORT            = NO
 
-# For Microsoft's IDL there are propget and propput attributes to indicate getter 
-# and setter methods for a property. Setting this option to YES (the default) 
-# will make doxygen replace the get and set methods by a property in the 
-# documentation. This will only work if the methods are indeed getting or 
-# setting a simple type. If this is not the case, or you want to show the 
-# methods anyway, you should set this option to NO.
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES will make
+# doxygen to replace the get and set methods by a property in the documentation.
+# This will only work if the methods are indeed getting or setting a simple
+# type. If this is not the case, or you want to show the methods anyway, you
+# should set this option to NO.
+# The default value is: YES.
 
 IDL_PROPERTY_SUPPORT   = YES
 
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC 
-# tag is set to YES, then doxygen will reuse the documentation of the first 
-# member in the group (if any) for the other members of the group. By default 
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
 # all members of a group must be documented explicitly.
+# The default value is: NO.
 
 DISTRIBUTE_GROUP_DOC   = NO
 
-# Set the SUBGROUPING tag to YES (the default) to allow class member groups of 
-# the same type (for instance a group of public functions) to be put as a 
-# subgroup of that type (e.g. under the Public Functions section). Set it to 
-# NO to prevent subgrouping. Alternatively, this can be done per class using 
-# the \nosubgrouping command.
+# Set the SUBGROUPING tag to YES to allow class member groups of the same type
+# (for instance a group of public functions) to be put as a subgroup of that
+# type (e.g. under the Public Functions section). Set it to NO to prevent
+# subgrouping. Alternatively, this can be done per class using the
+# \nosubgrouping command.
+# The default value is: YES.
 
 SUBGROUPING            = YES
 
-# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and 
-# unions are shown inside the group in which they are included (e.g. using 
-# @ingroup) instead of on a separate page (for HTML and Man pages) or 
-# section (for LaTeX and RTF).
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+#
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
 
 INLINE_GROUPED_CLASSES = NO
 
-# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and 
-# unions with only public data fields will be shown inline in the documentation 
-# of the scope in which they are defined (i.e. file, namespace, or group 
-# documentation), provided this scope is documented. If set to NO (the default), 
-# structs, classes, and unions are shown on a separate page (for HTML and Man 
-# pages) or section (for LaTeX and RTF).
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
 
 INLINE_SIMPLE_STRUCTS  = NO
 
-# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum 
-# is documented as struct, union, or enum with the name of the typedef. So 
-# typedef struct TypeS {} TypeT, will appear in the documentation as a struct 
-# with name TypeT. When disabled the typedef will appear as a member of a file, 
-# namespace, or class. And the struct will be named TypeS. This can typically 
-# be useful for C code in case the coding convention dictates that all compound 
+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
+# enum is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically be
+# useful for C code in case the coding convention dictates that all compound
 # types are typedef'ed and only the typedef is referenced, never the tag name.
+# The default value is: NO.
 
 TYPEDEF_HIDES_STRUCT   = NO
 
-# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to 
-# determine which symbols to keep in memory and which to flush to disk. 
-# When the cache is full, less often used symbols will be written to disk. 
-# For small to medium size projects (<1000 input files) the default value is 
-# probably good enough. For larger projects a too small cache size can cause 
-# doxygen to be busy swapping symbols to and from disk most of the time 
-# causing a significant performance penalty. 
-# If the system has enough physical memory increasing the cache will improve the 
-# performance by keeping more symbols in memory. Note that the value works on 
-# a logarithmic scale so increasing the size by one will roughly double the 
-# memory usage. The cache size is given by this formula: 
-# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, 
-# corresponding to a cache size of 2^16 = 65536 symbols
-
-SYMBOL_CACHE_SIZE      = 0
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_CACHE_SIZE      = 0
 
 #---------------------------------------------------------------------------
@@ -334,327 +412,381 @@
 #---------------------------------------------------------------------------
 
-# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in 
-# documentation are documented, even if no documentation was available. 
-# Private class members and static file members will be hidden unless 
-# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
+# documentation are documented, even if no documentation was available. Private
+# class members and static file members will be hidden unless the
+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
 
 EXTRACT_ALL            = YES
 
-# If the EXTRACT_PRIVATE tag is set to YES all private members of a class 
-# will be included in the documentation.
+# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
 
 EXTRACT_PRIVATE        = YES
 
-# If the EXTRACT_STATIC tag is set to YES all static members of a file 
-# will be included in the documentation.
+# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
 
 EXTRACT_STATIC         = YES
 
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) 
-# defined locally in source files will be included in the documentation. 
-# If set to NO only classes defined in header files are included.
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
+# locally in source files will be included in the documentation. If set to NO,
+# only classes defined in header files are included. Does not have any effect
+# for Java sources.
+# The default value is: YES.
 
 EXTRACT_LOCAL_CLASSES  = YES
 
-# This flag is only useful for Objective-C code. When set to YES local 
-# methods, which are defined in the implementation section but not in 
-# the interface are included in the documentation. 
-# If set to NO (the default) only methods in the interface are included.
+# This flag is only useful for Objective-C code. If set to YES, local methods,
+# which are defined in the implementation section but not in the interface are
+# included in the documentation. If set to NO, only methods in the interface are
+# included.
+# The default value is: NO.
 
 EXTRACT_LOCAL_METHODS  = NO
 
-# If this flag is set to YES, the members of anonymous namespaces will be 
-# extracted and appear in the documentation as a namespace called 
-# 'anonymous_namespace{file}', where file will be replaced with the base 
-# name of the file that contains the anonymous namespace. By default 
-# anonymous namespaces are hidden.
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base name of
+# the file that contains the anonymous namespace. By default anonymous namespace
+# are hidden.
+# The default value is: NO.
 
 EXTRACT_ANON_NSPACES   = NO
 
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all 
-# undocumented members of documented classes, files or namespaces. 
-# If set to NO (the default) these members will be included in the 
-# various overviews, but no documentation section is generated. 
-# This option has no effect if EXTRACT_ALL is enabled.
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO these
+# members will be included in the various overviews, but no documentation
+# section is generated. This option has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
 
 HIDE_UNDOC_MEMBERS     = NO
 
-# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all 
-# undocumented classes that are normally visible in the class hierarchy. 
-# If set to NO (the default) these classes will be included in the various 
-# overviews. This option has no effect if EXTRACT_ALL is enabled.
+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy. If set
+# to NO, these classes will be included in the various overviews. This option
+# has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
 
 HIDE_UNDOC_CLASSES     = NO
 
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all 
-# friend (class|struct|union) declarations. 
-# If set to NO (the default) these declarations will be included in the 
-# documentation.
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO, these declarations will be
+# included in the documentation.
+# The default value is: NO.
 
 HIDE_FRIEND_COMPOUNDS  = NO
 
-# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any 
-# documentation blocks found inside the body of a function. 
-# If set to NO (the default) these blocks will be appended to the 
-# function's detailed documentation block.
+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
+# documentation blocks found inside the body of a function. If set to NO, these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
 
 HIDE_IN_BODY_DOCS      = NO
 
-# The INTERNAL_DOCS tag determines if documentation 
-# that is typed after a \internal command is included. If the tag is set 
-# to NO (the default) then the documentation will be excluded. 
-# Set it to YES to include the internal documentation.
+# The INTERNAL_DOCS tag determines if documentation that is typed after a
+# \internal command is included. If the tag is set to NO then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
 
 INTERNAL_DOCS          = NO
 
-# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate 
-# file names in lower-case letters. If set to YES upper-case letters are also 
-# allowed. This is useful if you have classes or files whose names only differ 
-# in case and if your file system supports case sensitive file names. Windows 
+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
+# names in lower-case letters. If set to YES, upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
 # and Mac users are advised to set this option to NO.
+# The default value is: system dependent.
 
 CASE_SENSE_NAMES       = NO
 
-# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen 
-# will show members with their full class and namespace scopes in the 
-# documentation. If set to YES the scope will be hidden.
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES, the
+# scope will be hidden.
+# The default value is: NO.
 
 HIDE_SCOPE_NAMES       = NO
 
-# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen 
-# will put a list of the files that are included by a file in the documentation 
-# of that file.
+# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
+# append additional text to a page's title, such as Class Reference. If set to
+# YES the compound reference will be hidden.
+# The default value is: NO.
+
+HIDE_COMPOUND_REFERENCE= NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
 
 SHOW_INCLUDE_FILES     = YES
 
-# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen 
-# will list include files with double quotes in the documentation 
-# rather than with sharp brackets.
+# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
+# grouped member an include statement to the documentation, telling the reader
+# which file to include in order to use the member.
+# The default value is: NO.
+
+SHOW_GROUPED_MEMB_INC  = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
 
 FORCE_LOCAL_INCLUDES   = NO
 
-# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] 
-# is inserted in the documentation for inline members.
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
 
 INLINE_INFO            = YES
 
-# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen 
-# will sort the (detailed) documentation of file and class members 
-# alphabetically by member name. If set to NO the members will appear in 
-# declaration order.
+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
+# (detailed) documentation of file and class members alphabetically by member
+# name. If set to NO, the members will appear in declaration order.
+# The default value is: YES.
 
 SORT_MEMBER_DOCS       = YES
 
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the 
-# brief documentation of file, namespace and class members alphabetically 
-# by member name. If set to NO (the default) the members will appear in 
-# declaration order.
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO, the members will appear in declaration order. Note that
+# this will also influence the order of the classes in the class list.
+# The default value is: NO.
 
 SORT_BRIEF_DOCS        = NO
 
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen 
-# will sort the (brief and detailed) documentation of class members so that 
-# constructors and destructors are listed first. If set to NO (the default) 
-# the constructors will appear in the respective orders defined by 
-# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. 
-# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO 
-# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
+# (brief and detailed) documentation of class members so that constructors and
+# destructors are listed first. If set to NO the constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: NO.
 
 SORT_MEMBERS_CTORS_1ST = NO
 
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the 
-# hierarchy of group names into alphabetical order. If set to NO (the default) 
-# the group names will appear in their defined order.
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
+# of group names into alphabetical order. If set to NO the group names will
+# appear in their defined order.
+# The default value is: NO.
 
 SORT_GROUP_NAMES       = NO
 
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be 
-# sorted by fully-qualified names, including namespaces. If set to 
-# NO (the default), the class list will be sorted only by class name, 
-# not including the namespace part. 
-# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. 
-# Note: This option applies only to the class list, not to the 
-# alphabetical list.
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
+# fully-qualified names, including namespaces. If set to NO, the class list will
+# be sorted only by class name, not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the alphabetical
+# list.
+# The default value is: NO.
 
 SORT_BY_SCOPE_NAME     = NO
 
-# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to 
-# do proper type resolution of all parameters of a function it will reject a 
-# match between the prototype and the implementation of a member function even 
-# if there is only one candidate or it is obvious which candidate to choose 
-# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen 
-# will still accept a match between prototype and implementation in such cases.
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
 
 STRICT_PROTO_MATCHING  = NO
 
-# The GENERATE_TODOLIST tag can be used to enable (YES) or 
-# disable (NO) the todo list. This list is created by putting \todo 
-# commands in the documentation.
+# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
+# list. This list is created by putting \todo commands in the documentation.
+# The default value is: YES.
 
 GENERATE_TODOLIST      = YES
 
-# The GENERATE_TESTLIST tag can be used to enable (YES) or 
-# disable (NO) the test list. This list is created by putting \test 
-# commands in the documentation.
+# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
+# list. This list is created by putting \test commands in the documentation.
+# The default value is: YES.
 
 GENERATE_TESTLIST      = YES
 
-# The GENERATE_BUGLIST tag can be used to enable (YES) or 
-# disable (NO) the bug list. This list is created by putting \bug 
-# commands in the documentation.
+# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
+# list. This list is created by putting \bug commands in the documentation.
+# The default value is: YES.
 
 GENERATE_BUGLIST       = YES
 
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or 
-# disable (NO) the deprecated list. This list is created by putting 
-# \deprecated commands in the documentation.
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
+# the deprecated list. This list is created by putting \deprecated commands in
+# the documentation.
+# The default value is: YES.
 
 GENERATE_DEPRECATEDLIST= YES
 
-# The ENABLED_SECTIONS tag can be used to enable conditional 
-# documentation sections, marked by \if sectionname ... \endif.
-
-ENABLED_SECTIONS       = 
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines 
-# the initial value of a variable or macro consists of for it to appear in 
-# the documentation. If the initializer consists of more lines than specified 
-# here it will be hidden. Use a value of 0 to hide initializers completely. 
-# The appearance of the initializer of individual variables and macros in the 
-# documentation can be controlled using \showinitializer or \hideinitializer 
-# command in the documentation regardless of this setting.
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have for it to appear in the
+# documentation. If the initializer consists of more lines than specified here
+# it will be hidden. Use a value of 0 to hide initializers completely. The
+# appearance of the value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
 
 MAX_INITIALIZER_LINES  = 30
 
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated 
-# at the bottom of the documentation of classes and structs. If set to YES the 
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
+# the bottom of the documentation of classes and structs. If set to YES, the
 # list will mention the files that were used to generate the documentation.
+# The default value is: YES.
 
 SHOW_USED_FILES        = YES
 
-# If the sources in your project are distributed over multiple directories 
-# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy 
-# in the documentation. The default is NO.
-
-SHOW_DIRECTORIES       = NO
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page. 
-# This will remove the Files entry from the Quick Index and from the 
-# Folder Tree View (if specified). The default is YES.
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
+# will remove the Files entry from the Quick Index and from the Folder Tree View
+# (if specified).
+# The default value is: YES.
 
 SHOW_FILES             = YES
 
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the 
-# Namespaces page.  This will remove the Namespaces entry from the Quick Index 
-# and from the Folder Tree View (if specified). The default is YES.
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
+# page. This will remove the Namespaces entry from the Quick Index and from the
+# Folder Tree View (if specified).
+# The default value is: YES.
 
 SHOW_NAMESPACES        = YES
 
-# The FILE_VERSION_FILTER tag can be used to specify a program or script that 
-# doxygen should invoke to get the current version for each file (typically from 
-# the version control system). Doxygen will invoke the program by executing (via 
-# popen()) the command <command> <input-file>, where <command> is the value of 
-# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file 
-# provided by doxygen. Whatever the program writes to standard output 
-# is used as the file version. See the manual for examples.
-
-FILE_VERSION_FILTER    = 
-
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed 
-# by doxygen. The layout file controls the global structure of the generated 
-# output files in an output format independent way. The create the layout file 
-# that represents doxygen's defaults, run doxygen with the -l option. 
-# You can optionally specify a file name after the option, if omitted 
-# DoxygenLayout.xml will be used as the name of the layout file.
-
-LAYOUT_FILE            = 
-
-# The CITE_BIB_FILES tag can be used to specify one or more bib files 
-# containing the references data. This must be a list of .bib files. The 
-# .bib extension is automatically appended if omitted. Using this command 
-# requires the bibtex tool to be installed. See also 
-# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style 
-# of the bibliography can be controlled using LATEX_BIB_STYLE.
-
-CITE_BIB_FILES         = 
-
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated 
-# by doxygen. Possible values are YES and NO. If left blank NO is used.
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command command input-file, where command is the value of the
+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
+# by doxygen. Whatever the program writes to standard output is used as the file
+# version. For an example see the documentation.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option. You can
+# optionally specify a file name after the option, if omitted DoxygenLayout.xml
+# will be used as the name of the layout file.
+#
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
+
+LAYOUT_FILE            =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. See also \cite for info how to create references.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
 
 QUIET                  = NO
 
-# The WARNINGS tag can be used to turn on/off the warning messages that are 
-# generated by doxygen. Possible values are YES and NO. If left blank 
-# NO is used.
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+#
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
 
 WARNINGS               = YES
 
-# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings 
-# for undocumented members. If EXTRACT_ALL is set to YES then this flag will 
-# automatically be disabled.
+# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
+# will automatically be disabled.
+# The default value is: YES.
 
 WARN_IF_UNDOCUMENTED   = YES
 
-# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for 
-# potential errors in the documentation, such as not documenting some 
-# parameters in a documented function, or documenting parameters that 
-# don't exist or using markup commands wrongly.
+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some parameters
+# in a documented function, or documenting parameters that don't exist or using
+# markup commands wrongly.
+# The default value is: YES.
 
 WARN_IF_DOC_ERROR      = YES
 
-# The WARN_NO_PARAMDOC option can be enabled to get warnings for 
-# functions that are documented, but have no documentation for their parameters 
-# or return value. If set to NO (the default) doxygen will only warn about 
-# wrong or incomplete parameter documentation, but not about the absence of 
-# documentation.
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO, doxygen will only warn about wrong or incomplete
+# parameter documentation, but not about the absence of documentation.
+# The default value is: NO.
 
 WARN_NO_PARAMDOC       = NO
 
-# The WARN_FORMAT tag determines the format of the warning messages that 
-# doxygen can produce. The string should contain the $file, $line, and $text 
-# tags, which will be replaced by the file and line number from which the 
-# warning originated and the warning text. Optionally the format may contain 
-# $version, which will be replaced by the version of the file (if it could 
-# be obtained via FILE_VERSION_FILTER)
+# The WARN_FORMAT tag determines the format of the warning messages that doxygen
+# can produce. The string should contain the $file, $line, and $text tags, which
+# will be replaced by the file and line number from which the warning originated
+# and the warning text. Optionally the format may contain $version, which will
+# be replaced by the version of the file (if it could be obtained via
+# FILE_VERSION_FILTER)
+# The default value is: $file:$line: $text.
 
 WARN_FORMAT            = "$file:$line: $text"
 
-# The WARN_LOGFILE tag can be used to specify a file to which warning 
-# and error messages should be written. If left blank the output is written 
-# to stderr.
+# The WARN_LOGFILE tag can be used to specify a file to which warning and error
+# messages should be written. If left blank the output is written to standard
+# error (stderr).
 
 WARN_LOGFILE           = warning.log
 
 #---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag can be used to specify the files and/or directories that contain 
-# documented source files. You may enter file names like "myfile.cpp" or 
-# directories like "/usr/src/myproject". Separate the files or directories 
-# with spaces.
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is used to specify the files and/or directories that contain
+# documented source files. You may enter file names like myfile.cpp or
+# directories like /usr/src/myproject. Separate the files or directories with
+# spaces.
+# Note: If this tag is empty the current directory is searched.
 
 INPUT                  = ../source \
                          mainpage.h
 
-# This tag can be used to specify the character encoding of the source files 
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is 
-# also the default input encoding. Doxygen uses libiconv (or the iconv built 
-# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for 
-# the list of possible encodings.
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
 
 INPUT_ENCODING         = UTF-8
 
-# If the value of the INPUT tag contains directories, you can use the 
-# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp 
-# and *.h) to filter out the source-files in the directories. If left 
-# blank the following patterns are tested: 
-# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh 
-# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py 
-# *.f90 *.f *.for *.vhd *.vhdl
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank the
+# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
+# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
+# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
+# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
+# *.qsf, *.as and *.js.
 
 FILE_PATTERNS          = *.c \
@@ -691,778 +823,1165 @@
                          *.vhdl
 
-# The RECURSIVE tag can be used to turn specify whether or not subdirectories 
-# should be searched for input files as well. Possible values are YES and NO. 
-# If left blank NO is used.
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
 
 RECURSIVE              = YES
 
-# The EXCLUDE tag can be used to specify files and/or directories that should 
-# excluded from the INPUT source files. This way you can easily exclude a 
-# subdirectory from a directory tree whose root is specified with the INPUT tag. 
-# Note that relative paths are relative to directory from which doxygen is run.
-
-EXCLUDE                = 
-
-# The EXCLUDE_SYMLINKS tag can be used select whether or not files or 
-# directories that are symbolic links (a Unix file system feature) are excluded 
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+#
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
 # from the input.
+# The default value is: NO.
 
 EXCLUDE_SYMLINKS       = NO
 
-# If the value of the INPUT tag contains directories, you can use the 
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude 
-# certain files from those directories. Note that the wildcards are matched 
-# against the file with absolute path, so to exclude all test directories 
-# for example use the pattern */test/*
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories.
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories for example use the pattern */test/*
 
 EXCLUDE_PATTERNS       = */.svn
 
-# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names 
-# (namespaces, classes, functions, etc.) that should be excluded from the 
-# output. The symbol name can be a fully qualified name, a word, or if the 
-# wildcard * is used, a substring. Examples: ANamespace, AClass, 
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
 # AClass::ANamespace, ANamespace::*Test
-
-EXCLUDE_SYMBOLS        = 
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or 
-# directories that contain example code fragments that are included (see 
-# the \include command).
-
-EXAMPLE_PATH           = 
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the 
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp 
-# and *.h) to filter out the source-files in the directories. If left 
-# blank all files are included.
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or directories
+# that contain example code fragments that are included (see the \include
+# command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank all
+# files are included.
 
 EXAMPLE_PATTERNS       = *
 
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be 
-# searched for input files to be used with the \include or \dontinclude 
-# commands irrespective of the value of the RECURSIVE tag. 
-# Possible values are YES and NO. If left blank NO is used.
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude commands
+# irrespective of the value of the RECURSIVE tag.
+# The default value is: NO.
 
 EXAMPLE_RECURSIVE      = NO
 
-# The IMAGE_PATH tag can be used to specify one or more files or 
-# directories that contain image that are included in the documentation (see 
-# the \image command).
-
-IMAGE_PATH             = 
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should 
-# invoke to filter for each input file. Doxygen will invoke the filter program 
-# by executing (via popen()) the command <filter> <input-file>, where <filter> 
-# is the value of the INPUT_FILTER tag, and <input-file> is the name of an 
-# input file. Doxygen will then use the output that the filter program writes 
-# to standard output.  If FILTER_PATTERNS is specified, this tag will be 
-# ignored.
-
-INPUT_FILTER           = 
-
-# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern 
-# basis.  Doxygen will compare the file name with each pattern and apply the 
-# filter if there is a match.  The filters are a list of the form: 
-# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further 
-# info on how filters are used. If FILTER_PATTERNS is empty or if 
-# non of the patterns match the file name, INPUT_FILTER is applied.
-
-FILTER_PATTERNS        = 
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using 
-# INPUT_FILTER) will be used to filter the input files when producing source 
-# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be included in the documentation (see the
+# \image command).
+
+IMAGE_PATH             =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command:
+#
+# <filter> <input-file>
+#
+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
+# name of an input file. Doxygen will then use the output that the filter
+# program writes to standard output. If FILTER_PATTERNS is specified, this tag
+# will be ignored.
+#
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis. Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match. The filters are a list of the form: pattern=filter
+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
 
 FILTER_SOURCE_FILES    = NO
 
-# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file 
-# pattern. A pattern will override the setting for FILTER_PATTERN (if any) 
-# and it is also possible to disable source filtering for a specific pattern 
-# using *.ext= (so without naming a filter). This option only has effect when 
-# FILTER_SOURCE_FILES is enabled.
-
-FILTER_SOURCE_PATTERNS = 
-
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will 
-# be generated. Documented entities will be cross-referenced with these sources. 
-# Note: To get rid of all source code in the generated output, make sure also 
-# VERBATIM_HEADERS is set to NO.
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS =
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
+# generated. Documented entities will be cross-referenced with these sources.
+#
+# Note: To get rid of all source code in the generated output, make sure that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
 
 SOURCE_BROWSER         = YES
 
-# Setting the INLINE_SOURCES tag to YES will include the body 
-# of functions and classes directly in the documentation.
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
 
 INLINE_SOURCES         = NO
 
-# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct 
-# doxygen to hide any special comment blocks from generated source code 
-# fragments. Normal C and C++ comments will always remain visible.
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
 
 STRIP_CODE_COMMENTS    = YES
 
-# If the REFERENCED_BY_RELATION tag is set to YES 
-# then for each documented function all documented 
-# functions referencing it will be listed.
+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
+# function all documented functions referencing it will be listed.
+# The default value is: NO.
 
 REFERENCED_BY_RELATION = NO
 
-# If the REFERENCES_RELATION tag is set to YES 
-# then for each documented function all documented entities 
-# called/used by that function will be listed.
+# If the REFERENCES_RELATION tag is set to YES then for each documented function
+# all documented entities called/used by that function will be listed.
+# The default value is: NO.
 
 REFERENCES_RELATION    = NO
 
-# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) 
-# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from 
-# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will 
-# link to the source code.  Otherwise they will link to the documentation.
+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
+# to YES then the hyperlinks from functions in REFERENCES_RELATION and
+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
+# link to the documentation.
+# The default value is: YES.
 
 REFERENCES_LINK_SOURCE = YES
 
-# If the USE_HTAGS tag is set to YES then the references to source code 
-# will point to the HTML generated by the htags(1) tool instead of doxygen 
-# built-in source browser. The htags tool is part of GNU's global source 
-# tagging system (see http://www.gnu.org/software/global/global.html). You 
-# will need version 4.8.6 or higher.
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS        = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code will
+# point to the HTML generated by the htags(1) tool instead of doxygen built-in
+# source browser. The htags tool is part of GNU's global source tagging system
+# (see http://www.gnu.org/software/global/global.html). You will need version
+# 4.8.6 or higher.
+#
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+#
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+#
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
 
 USE_HTAGS              = NO
 
-# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen 
-# will generate a verbatim copy of the header file for each class for 
-# which an include is specified. Set to NO to disable this.
+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
+# verbatim copy of the header file for each class for which an include is
+# specified. Set to NO to disable this.
+# See also: Section \class.
+# The default value is: YES.
 
 VERBATIM_HEADERS       = YES
 
-#---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index 
-# of all compounds will be generated. Enable this if the project 
-# contains a lot of classes, structs, unions or interfaces.
+# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
+# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the
+# cost of reduced performance. This can be particularly helpful with template
+# rich C++ code for which doxygen's built-in parser lacks the necessary type
+# information.
+# Note: The availability of this option depends on whether or not doxygen was
+# compiled with the --with-libclang option.
+# The default value is: NO.
+
+CLANG_ASSISTED_PARSING = NO
+
+# If clang assisted parsing is enabled you can provide the compiler with command
+# line options that you would normally use when invoking the compiler. Note that
+# the include paths will already be set by doxygen for the files and directories
+# specified with INPUT and INCLUDE_PATH.
+# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
+
+CLANG_OPTIONS          =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
+# compounds will be generated. Enable this if the project contains a lot of
+# classes, structs, unions or interfaces.
+# The default value is: YES.
 
 ALPHABETICAL_INDEX     = YES
 
-# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then 
-# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns 
-# in which this list will be split (can be a number in the range [1..20])
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
 
 COLS_IN_ALPHA_INDEX    = 5
 
-# In case all classes in a project start with a common prefix, all 
-# classes will be put under the same header in the alphabetical index. 
-# The IGNORE_PREFIX tag can be used to specify one or more prefixes that 
-# should be ignored while generating the index headers.
-
-IGNORE_PREFIX          = 
-
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES (the default) Doxygen will 
-# generate HTML output.
+# In case all classes in a project start with a common prefix, all classes will
+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
+# can be used to specify a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
+# The default value is: YES.
 
 GENERATE_HTML          = YES
 
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `html' will be used as the default path.
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_OUTPUT            = html
 
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for 
-# each generated HTML page (for example: .htm,.php,.asp). If it is left blank 
-# doxygen will generate files with .html extension.
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
+# generated HTML page (for example: .htm, .php, .asp).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_FILE_EXTENSION    = .html
 
-# The HTML_HEADER tag can be used to specify a personal HTML header for 
-# each generated HTML page. If it is left blank doxygen will generate a 
-# standard header. Note that when using a custom header you are responsible  
-# for the proper inclusion of any scripts and style sheets that doxygen 
-# needs, which is dependent on the configuration options used. 
-# It is adviced to generate a default header using "doxygen -w html 
-# header.html footer.html stylesheet.css YourConfigFile" and then modify 
-# that header. Note that the header is subject to change so you typically 
-# have to redo this when upgrading to a newer version of doxygen or when 
-# changing the value of configuration settings such as GENERATE_TREEVIEW!
-
-HTML_HEADER            = 
-
-# The HTML_FOOTER tag can be used to specify a personal HTML footer for 
-# each generated HTML page. If it is left blank doxygen will generate a 
-# standard footer.
-
-HTML_FOOTER            = 
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading 
-# style sheet that is used by each HTML page. It can be used to 
-# fine-tune the look of the HTML output. If the tag is left blank doxygen 
-# will generate a default style sheet. Note that doxygen will try to copy 
-# the style sheet file to the HTML output directory, so don't put your own 
-# stylesheet in the HTML output directory as well, or it will be erased!
-
-HTML_STYLESHEET        = 
-
-# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or 
-# other source files which should be copied to the HTML output directory. Note 
-# that these files will be copied to the base HTML output directory. Use the 
-# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these 
-# files. In the HTML_STYLESHEET file, use the file name only. Also note that 
-# the files will be copied as-is; there are no commands or markers available.
-
-HTML_EXTRA_FILES       = 
-
-# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. 
-# Doxygen will adjust the colors in the stylesheet and background images 
-# according to this color. Hue is specified as an angle on a colorwheel, 
-# see http://en.wikipedia.org/wiki/Hue for more information. 
-# For instance the value 0 represents red, 60 is yellow, 120 is green, 
-# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. 
-# The allowed range is 0 to 359.
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
+# standard header.
+#
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FOOTER            =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
+# sheet that is used by each HTML page. It can be used to fine-tune the look of
+# the HTML output. If left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# cascading style sheets that are included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefore more robust against future updates.
+# Doxygen will copy the style sheet files to the output directory.
+# Note: The order of the extra style sheet files is of importance (e.g. the last
+# style sheet in the list overrules the setting of the previous ones in the
+# list). For an example see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the style sheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_COLORSTYLE_HUE    = 220
 
-# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of 
-# the colors in the HTML output. For a value of 0 the output will use 
-# grayscales only. A value of 255 will produce the most vivid colors.
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_COLORSTYLE_SAT    = 100
 
-# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to 
-# the luminance component of the colors in the HTML output. Values below 
-# 100 gradually make the output lighter, whereas values above 100 make 
-# the output darker. The value divided by 100 is the actual gamma applied, 
-# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, 
-# and 100 does not change the gamma.
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_COLORSTYLE_GAMMA  = 80
 
-# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML 
-# page will contain the date and time when the page was generated. Setting 
-# this to NO can help when comparing the output of multiple runs.
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_TIMESTAMP         = YES
 
-# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, 
-# files or namespaces will be aligned in HTML using tables. If set to 
-# NO a bullet list will be used.
-
-HTML_ALIGN_MEMBERS     = YES
-
-# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML 
-# documentation will contain sections that can be hidden and shown after the 
-# page has loaded. For this to work a browser that supports 
-# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox 
-# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_DYNAMIC_SECTIONS  = NO
 
-# If the GENERATE_DOCSET tag is set to YES, additional index files 
-# will be generated that can be used as input for Apple's Xcode 3 
-# integrated development environment, introduced with OSX 10.5 (Leopard). 
-# To create a documentation set, doxygen will generate a Makefile in the 
-# HTML output directory. Running make will produce the docset in that 
-# directory and running "make install" will install the docset in 
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find 
-# it at startup. 
-# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html 
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files will be
+# generated that can be used as input for Apple's Xcode 3 integrated development
+# environment (see: http://developer.apple.com/tools/xcode/), introduced with
+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
+# Makefile in the HTML output directory. Running make will produce the docset in
+# that directory and running make install will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
 # for more information.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 GENERATE_DOCSET        = NO
 
-# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the 
-# feed. A documentation feed provides an umbrella under which multiple 
-# documentation sets from a single provider (such as a company or product suite) 
-# can be grouped.
+# This tag determines the name of the docset feed. A documentation feed provides
+# an umbrella under which multiple documentation sets from a single provider
+# (such as a company or product suite) can be grouped.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
 
 DOCSET_FEEDNAME        = "Doxygen generated docs"
 
-# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that 
-# should uniquely identify the documentation set bundle. This should be a 
-# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen 
-# will append .docset to the name.
+# This tag specifies a string that should uniquely identify the documentation
+# set bundle. This should be a reverse domain-name style string, e.g.
+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
 
 DOCSET_BUNDLE_ID       = org.doxygen.Project
 
-# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify 
-# the documentation publisher. This should be a reverse domain-name style 
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
 # string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
 
 DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
 
-# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
 
 DOCSET_PUBLISHER_NAME  = Publisher
 
-# If the GENERATE_HTMLHELP tag is set to YES, additional index files 
-# will be generated that can be used as input for tools like the 
-# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) 
-# of the generated HTML documentation.
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+#
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 GENERATE_HTMLHELP      = NO
 
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can 
-# be used to specify the file name of the resulting .chm file. You 
-# can add a path in front of the file if the result should not be 
+# The CHM_FILE tag can be used to specify the file name of the resulting .chm
+# file. You can add a path in front of the file if the result should not be
 # written to the html output directory.
-
-CHM_FILE               = 
-
-# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can 
-# be used to specify the location (absolute path including file name) of 
-# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run 
-# the HTML help compiler on the generated index.hhp.
-
-HHC_LOCATION           = 
-
-# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag 
-# controls if a separate .chi index file is generated (YES) or that 
-# it should be included in the master .chm file (NO).
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_FILE               =
+
+# The HHC_LOCATION tag can be used to specify the location (absolute path
+# including file name) of the HTML help compiler (hhc.exe). If non-empty,
+# doxygen will try to run the HTML help compiler on the generated index.hhp.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+HHC_LOCATION           =
+
+# The GENERATE_CHI flag controls if a separate .chi index file is generated
+# (YES) or that it should be included in the master .chm file (NO).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 GENERATE_CHI           = NO
 
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING 
-# is used to encode HtmlHelp index (hhk), content (hhc) and project file 
-# content.
-
-CHM_INDEX_ENCODING     = 
-
-# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag 
-# controls whether a binary table of contents is generated (YES) or a 
-# normal table of contents (NO) in the .chm file.
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_INDEX_ENCODING     =
+
+# The BINARY_TOC flag controls whether a binary table of contents is generated
+# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
+# enables the Previous and Next buttons.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 BINARY_TOC             = NO
 
-# The TOC_EXPAND flag can be set to YES to add extra items for group members 
-# to the contents of the HTML help documentation and to the tree view.
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 TOC_EXPAND             = NO
 
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and 
-# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated 
-# that can be used as input for Qt's qhelpgenerator to generate a 
-# Qt Compressed Help (.qch) of the generated HTML documentation.
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
+# (.qch) of the generated HTML documentation.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 GENERATE_QHP           = NO
 
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can 
-# be used to specify the file name of the resulting .qch file. 
-# The path specified is relative to the HTML output folder.
-
-QCH_FILE               = 
-
-# The QHP_NAMESPACE tag specifies the namespace to use when generating 
-# Qt Help Project output. For more information please see 
-# http://doc.trolltech.com/qthelpproject.html#namespace
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
+# the file name of the resulting .qch file. The path specified is relative to
+# the HTML output folder.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
 
 QHP_NAMESPACE          = org.doxygen.Project
 
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating 
-# Qt Help Project output. For more information please see 
-# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
 
 QHP_VIRTUAL_FOLDER     = doc
 
-# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to 
-# add. For more information please see 
-# http://doc.trolltech.com/qthelpproject.html#custom-filters
-
-QHP_CUST_FILTER_NAME   = 
-
-# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the 
-# custom filter to add. For more information please see 
-# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters"> 
-# Qt Help Project / Custom Filters</a>.
-
-QHP_CUST_FILTER_ATTRS  = 
-
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this 
-# project's 
-# filter section matches. 
-# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes"> 
-# Qt Help Project / Filter Attributes</a>.
-
-QHP_SECT_FILTER_ATTRS  = 
-
-# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can 
-# be used to specify the location of Qt's qhelpgenerator. 
-# If non-empty doxygen will try to run qhelpgenerator on the generated 
-# .qhp file.
-
-QHG_LOCATION           = 
-
-# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files  
-# will be generated, which together with the HTML files, form an Eclipse help 
-# plugin. To install this plugin and make it available under the help contents 
-# menu in Eclipse, the contents of the directory containing the HTML and XML 
-# files needs to be copied into the plugins directory of eclipse. The name of 
-# the directory within the plugins directory should be the same as 
-# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before 
-# the help appears.
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# The QHG_LOCATION tag can be used to specify the location of Qt's
+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
+# generated .qhp file.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 GENERATE_ECLIPSEHELP   = NO
 
-# A unique identifier for the eclipse help plugin. When installing the plugin 
-# the directory name containing the HTML and XML files should also have 
-# this name.
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
 
 ECLIPSE_DOC_ID         = org.doxygen.Project
 
-# The DISABLE_INDEX tag can be used to turn on/off the condensed index at 
-# top of each HTML page. The value NO (the default) enables the index and 
-# the value YES disables it.
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 DISABLE_INDEX          = NO
 
-# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values 
-# (range [0,1..20]) that doxygen will group on one line in the generated HTML 
-# documentation. Note that a value of 0 will completely suppress the enum 
-# values from appearing in the overview section.
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information. If the tag
+# value is set to YES, a side panel will be generated containing a tree-like
+# index structure (just like the one that is generated for HTML Help). For this
+# to work a browser that supports JavaScript, DHTML, CSS and frames is required
+# (i.e. any modern browser). Windows users are probably better off using the
+# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW      = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+#
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 ENUM_VALUES_PER_LINE   = 4
 
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index 
-# structure should be generated to display hierarchical information. 
-# If the tag value is set to YES, a side panel will be generated 
-# containing a tree-like index structure (just like the one that 
-# is generated for HTML Help). For this to work a browser that supports 
-# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). 
-# Windows users are probably better off using the HTML help feature.
-
-GENERATE_TREEVIEW      = NO
-
-# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, 
-# and Class Hierarchy pages using a tree view instead of an ordered list.
-
-USE_INLINE_TREES       = NO
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be 
-# used to set the initial width (in pixels) of the frame in which the tree 
-# is shown.
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
+# to set the initial width (in pixels) of the frame in which the tree is shown.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 TREEVIEW_WIDTH         = 250
 
-# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open 
-# links to external symbols imported via tag files in a separate window.
+# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 EXT_LINKS_IN_WINDOW    = NO
 
-# Use this tag to change the font size of Latex formulas included 
-# as images in the HTML documentation. The default is 10. Note that 
-# when you change the font size after a successful doxygen run you need 
-# to manually remove any form_*.png images from the HTML output directory 
-# to force them to be regenerated.
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. When you change the font size after a successful
+# doxygen run you need to manually remove any form_*.png images from the HTML
+# output directory to force them to be regenerated.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 FORMULA_FONTSIZE       = 10
 
-# Use the FORMULA_TRANPARENT tag to determine whether or not the images 
-# generated for formulas are transparent PNGs. Transparent PNGs are 
-# not supported properly for IE 6.0, but are supported on all modern browsers. 
-# Note that when changing this option you need to delete any form_*.png files 
-# in the HTML output before the changes have effect.
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+#
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 FORMULA_TRANSPARENT    = YES
 
-# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax 
-# (see http://www.mathjax.org) which uses client side Javascript for the 
-# rendering instead of using prerendered bitmaps. Use this if you do not 
-# have LaTeX installed or if you want to formulas look prettier in the HTML 
-# output. When enabled you also need to install MathJax separately and 
-# configure the path to it using the MATHJAX_RELPATH option.
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 USE_MATHJAX            = NO
 
-# When MathJax is enabled you need to specify the location relative to the 
-# HTML output directory using the MATHJAX_RELPATH option. The destination 
-# directory should contain the MathJax.js script. For instance, if the mathjax 
-# directory is located at the same level as the HTML output directory, then 
-# MATHJAX_RELPATH should be ../mathjax. The default value points to the 
-# mathjax.org site, so you can quickly see the result without installing 
-# MathJax, but it is strongly recommended to install a local copy of MathJax 
-# before deployment.
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT         = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
 
 MATHJAX_RELPATH        = http://www.mathjax.org/mathjax
 
-# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension 
-# names that should be enabled during MathJax rendering.
-
-MATHJAX_EXTENSIONS     = 
-
-# When the SEARCHENGINE tag is enabled doxygen will generate a search box 
-# for the HTML output. The underlying search engine uses javascript 
-# and DHTML and should work on any modern browser. Note that when using 
-# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets 
-# (GENERATE_DOCSET) there is already a search function so this one should 
-# typically be disabled. For large projects the javascript based search engine 
-# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS     =
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE       =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
+# the HTML output. The underlying search engine uses javascript and DHTML and
+# should work on any modern browser. Note that when using HTML help
+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 SEARCHENGINE           = YES
 
-# When the SERVER_BASED_SEARCH tag is enabled the search engine will be 
-# implemented using a PHP enabled web server instead of at the web client 
-# using Javascript. Doxygen will generate the search PHP script and index 
-# file to put on the web server. The advantage of the server 
-# based approach is that it scales better to large projects and allows 
-# full text search. The disadvantages are that it is more difficult to setup 
-# and does not have live searching capabilities.
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
+# setting. When disabled, doxygen will generate a PHP script for searching and
+# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
+# and searching needs to be provided by external tools. See the section
+# "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
 
 SERVER_BASED_SEARCH    = NO
 
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will 
-# generate Latex output.
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+#
+# Doxygen ships with an example indexer (doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+#
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH        = NO
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+#
+# Doxygen ships with an example indexer (doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL       =
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE        = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID     =
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS  =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
+# The default value is: YES.
 
 GENERATE_LATEX         = NO
 
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `latex' will be used as the default path.
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_OUTPUT           = latex
 
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be 
-# invoked. If left blank `latex' will be used as the default command name. 
-# Note that when enabling USE_PDFLATEX this option is only used for 
-# generating bitmaps for formulas in the HTML output, but not in the 
-# Makefile that is written to the output directory.
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked.
+#
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_CMD_NAME         = latex
 
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to 
-# generate index for LaTeX. If left blank `makeindex' will be used as the 
-# default command name.
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 MAKEINDEX_CMD_NAME     = makeindex
 
-# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact 
-# LaTeX documents. This may be useful for small projects and may help to 
-# save some trees in general.
+# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 COMPACT_LATEX          = NO
 
-# The PAPER_TYPE tag can be used to set the paper type that is used 
-# by the printer. Possible values are: a4, letter, legal and 
-# executive. If left blank a4wide will be used.
+# The PAPER_TYPE tag can be used to set the paper type that is used by the
+# printer.
+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 PAPER_TYPE             = a4
 
-# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX 
-# packages that should be included in the LaTeX output.
-
-EXTRA_PACKAGES         = 
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for 
-# the generated latex document. The header should contain everything until 
-# the first chapter. If it is left blank doxygen will generate a 
-# standard header. Notice: only use this tag if you know what you are doing!
-
-LATEX_HEADER           = 
-
-# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for 
-# the generated latex document. The footer should contain everything after 
-# the last chapter. If it is left blank doxygen will generate a 
-# standard footer. Notice: only use this tag if you know what you are doing!
-
-LATEX_FOOTER           = 
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated 
-# is prepared for conversion to pdf (using ps2pdf). The pdf file will 
-# contain links (just like the HTML output) instead of page references 
-# This makes the output suitable for online browsing using a pdf viewer.
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. To get the times font for
+# instance you can specify
+# EXTRA_PACKAGES=times
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
+# generated LaTeX document. The header should contain everything until the first
+# chapter. If it is left blank doxygen will generate a standard header. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+#
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
+# $projectbrief, $projectlogo. Doxygen will replace $title with the empty
+# string, for the replacement values of the other commands the user is referred
+# to HTML_HEADER.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer. See
+# LATEX_HEADER for more information on how to generate a default footer and what
+# special commands can be used inside the footer.
+#
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER           =
+
+# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# LaTeX style sheets that are included after the standard style sheets created
+# by doxygen. Using this option one can overrule certain style aspects. Doxygen
+# will copy the style sheet files to the output directory.
+# Note: The order of the extra style sheet files is of importance (e.g. the last
+# style sheet in the list overrules the setting of the previous ones in the
+# list).
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_STYLESHEET =
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES      =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
+# contain links (just like the HTML output) instead of page references. This
+# makes the output suitable for online browsing using a PDF viewer.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 PDF_HYPERLINKS         = YES
 
-# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of 
-# plain latex in the generated Makefile. Set this option to YES to get a 
+# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES, to get a
 # higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 USE_PDFLATEX           = YES
 
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. 
-# command to the generated LaTeX files. This will instruct LaTeX to keep 
-# running if errors occur, instead of asking the user for help. 
-# This option is also used when generating formulas in HTML.
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
+# command to the generated LaTeX files. This will instruct LaTeX to keep running
+# if errors occur, instead of asking the user for help. This option is also used
+# when generating formulas in HTML.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_BATCHMODE        = NO
 
-# If LATEX_HIDE_INDICES is set to YES then doxygen will not 
-# include the index chapters (such as File Index, Compound Index, etc.) 
-# in the output.
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_HIDE_INDICES     = NO
 
-# If LATEX_SOURCE_CODE is set to YES then doxygen will include 
-# source code with syntax highlighting in the LaTeX output. 
-# Note that which sources are shown also depends on other settings 
-# such as SOURCE_BROWSER.
+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
+# code with syntax highlighting in the LaTeX output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_SOURCE_CODE      = NO
 
-# The LATEX_BIB_STYLE tag can be used to specify the style to use for the 
-# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See 
-# http://en.wikipedia.org/wiki/BibTeX for more info.
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_BIB_STYLE        = plain
 
 #---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output 
-# The RTF output is optimized for Word 97 and may not look very pretty with 
-# other RTF readers or editors.
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
+# RTF output is optimized for Word 97 and may not look too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
 
 GENERATE_RTF           = NO
 
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `rtf' will be used as the default path.
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
 
 RTF_OUTPUT             = rtf
 
-# If the COMPACT_RTF tag is set to YES Doxygen generates more compact 
-# RTF documents. This may be useful for small projects and may help to 
-# save some trees in general.
+# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
 
 COMPACT_RTF            = NO
 
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated 
-# will contain hyperlink fields. The RTF file will 
-# contain links (just like the HTML output) instead of page references. 
-# This makes the output suitable for online browsing using WORD or other 
-# programs which support those fields. 
-# Note: wordpad (write) and others do not support links.
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
+# contain hyperlink fields. The RTF file will contain links (just like the HTML
+# output) instead of page references. This makes the output suitable for online
+# browsing using Word or some other Word compatible readers that support those
+# fields.
+#
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
 
 RTF_HYPERLINKS         = NO
 
-# Load stylesheet definitions from file. Syntax is similar to doxygen's 
-# config file, i.e. a series of assignments. You only have to provide 
-# replacements, missing definitions are set to their default value.
-
-RTF_STYLESHEET_FILE    = 
-
-# Set optional variables used in the generation of an rtf document. 
-# Syntax is similar to doxygen's config file.
-
-RTF_EXTENSIONS_FILE    = 
-
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES (the default) Doxygen will 
-# generate man pages
+# Load stylesheet definitions from file. Syntax is similar to doxygen's config
+# file, i.e. a series of assignments. You only have to provide replacements,
+# missing definitions are set to their default value.
+#
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_EXTENSIONS_FILE    =
+
+# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code
+# with syntax highlighting in the RTF output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_SOURCE_CODE        = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
 
 GENERATE_MAN           = NO
 
-# The MAN_OUTPUT tag is used to specify where the man pages will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `man' will be used as the default path.
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
 
 MAN_OUTPUT             = man
 
-# The MAN_EXTENSION tag determines the extension that is added to 
-# the generated man pages (default is the subroutine's section .3)
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
 
 MAN_EXTENSION          = .3
 
-# If the MAN_LINKS tag is set to YES and Doxygen generates man output, 
-# then it will generate one additional man file for each entity 
-# documented in the real man page(s). These additional files 
-# only source the real man page, but without them the man command 
-# would be unable to find the correct page. The default is NO.
+# The MAN_SUBDIR tag determines the name of the directory created within
+# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
+# MAN_EXTENSION with the initial . removed.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_SUBDIR             =
+
+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
+# will generate one additional man file for each entity documented in the real
+# man page(s). These additional files only source the real man page, but without
+# them the man command would be unable to find the correct page.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
 
 MAN_LINKS              = NO
 
 #---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES Doxygen will 
-# generate an XML file that captures the structure of 
-# the code including all documentation.
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
+# captures the structure of the code including all documentation.
+# The default value is: NO.
 
 GENERATE_XML           = NO
 
-# The XML_OUTPUT tag is used to specify where the XML pages will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `xml' will be used as the default path.
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
 
 XML_OUTPUT             = xml
 
-# The XML_SCHEMA tag can be used to specify an XML schema, 
-# which can be used by a validating XML parser to check the 
-# syntax of the XML files.
-
-XML_SCHEMA             = 
-
-# The XML_DTD tag can be used to specify an XML DTD, 
-# which can be used by a validating XML parser to check the 
-# syntax of the XML files.
-
-XML_DTD                = 
-
-# If the XML_PROGRAMLISTING tag is set to YES Doxygen will 
-# dump the program listings (including syntax highlighting 
-# and cross-referencing information) to the XML output. Note that 
-# enabling this will significantly increase the size of the XML output.
+# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
+# listings (including syntax highlighting and cross-referencing information) to
+# the XML output. Note that enabling this will significantly increase the size
+# of the XML output.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
 
 XML_PROGRAMLISTING     = YES
 
 #---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will 
-# generate an AutoGen Definitions (see autogen.sf.net) file 
-# that captures the structure of the code including all 
-# documentation. Note that this feature is still experimental 
-# and incomplete at the moment.
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK       = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT         = docbook
+
+# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the
+# program listings (including syntax highlighting and cross-referencing
+# information) to the DOCBOOK output. Note that enabling this will significantly
+# increase the size of the DOCBOOK output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_PROGRAMLISTING = NO
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
+# AutoGen Definitions (see http://autogen.sf.net) file that captures the
+# structure of the code including all documentation. Note that this feature is
+# still experimental and incomplete at the moment.
+# The default value is: NO.
 
 GENERATE_AUTOGEN_DEF   = NO
 
 #---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES Doxygen will 
-# generate a Perl module file that captures the structure of 
-# the code including all documentation. Note that this 
-# feature is still experimental and incomplete at the 
-# moment.
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
+# file that captures the structure of the code including all documentation.
+#
+# Note that this feature is still experimental and incomplete at the moment.
+# The default value is: NO.
 
 GENERATE_PERLMOD       = NO
 
-# If the PERLMOD_LATEX tag is set to YES Doxygen will generate 
-# the necessary Makefile rules, Perl scripts and LaTeX code to be able 
-# to generate PDF and DVI output from the Perl module output.
+# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
+# output from the Perl module output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
 
 PERLMOD_LATEX          = NO
 
-# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be 
-# nicely formatted so it can be parsed by a human reader.  This is useful 
-# if you want to understand what is going on.  On the other hand, if this 
-# tag is set to NO the size of the Perl module output will be much smaller 
-# and Perl will parse it just the same.
+# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
+# formatted so it can be parsed by a human reader. This is useful if you want to
+# understand what is going on. On the other hand, if this tag is set to NO, the
+# size of the Perl module output will be much smaller and Perl will parse it
+# just the same.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
 
 PERLMOD_PRETTY         = YES
 
-# The names of the make variables in the generated doxyrules.make file 
-# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. 
-# This is useful so different doxyrules.make files included by the same 
-# Makefile don't overwrite each other's variables.
-
-PERLMOD_MAKEVAR_PREFIX = 
+# The names of the make variables in the generated doxyrules.make file are
+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
+# so different doxyrules.make files included by the same Makefile don't
+# overwrite each other's variables.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_MAKEVAR_PREFIX =
 
 #---------------------------------------------------------------------------
@@ -1470,327 +1989,435 @@
 #---------------------------------------------------------------------------
 
-# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will 
-# evaluate all C-preprocessor directives found in the sources and include 
+# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
+# in the source code. If set to NO, only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+MACRO_EXPANSION        = YES
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
+# the macro expansion is limited to the macros specified with the PREDEFINED and
+# EXPAND_AS_DEFINED tags.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES, the include files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by the
+# preprocessor.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
+
+INCLUDE_PATH           = ../source/Lib/
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will be
+# used.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that are
+# defined before the preprocessor is started (similar to the -D option of e.g.
+# gcc). The argument of the tag is a list of macros of the form: name or
+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
+# is assumed. To prevent a macro definition from being undefined via #undef or
+# recursively expanded use the := operator instead of the = operator.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
+# tag can be used to specify a list of macro names that should be expanded. The
+# macro definition that is found in the sources will be used. Use the PREDEFINED
+# tag if you want to use a different macro definition that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all references to function-like macros that are alone on a line, have
+# an all uppercase name, and do not end with a semicolon. Such function macros
+# are typically used for boiler-plate code, and will confuse the parser if not
+# removed.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. The format of
+# a tag file without this location is as follows:
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where loc1 and loc2 can be relative or absolute paths or URLs. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: Each tag file must have a unique name (where the name does NOT include
+# the path). If a tag file is not located in the directory in which doxygen is
+# run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
+# tag file that is based on the input files it reads. See section "Linking to
+# external documentation" for more information about the usage of tag files.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
+# the class index. If set to NO, only the inherited external classes will be
+# listed.
+# The default value is: NO.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will be
+# listed.
+# The default value is: YES.
+
+EXTERNAL_GROUPS        = YES
+
+# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
+# be listed.
+# The default value is: YES.
+
+EXTERNAL_PAGES         = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
+# powerful graphs.
+# The default value is: YES.
+
+CLASS_DIAGRAMS         = NO
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see:
+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# You can include diagrams made with dia in doxygen documentation. Doxygen will
+# then run dia to produce the diagram and insert it in the documentation. The
+# DIA_PATH tag allows you to specify the directory where the dia binary resides.
+# If left empty dia is assumed to be found in the default search path.
+
+DIA_PATH               =
+
+# If set to YES the inheritance and collaboration graphs will hide inheritance
+# and usage relations if the target is undocumented or is not a class.
+# The default value is: YES.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz (see:
+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
+# Bell Labs. The other options in this section have no effect if this option is
+# set to NO
+# The default value is: NO.
+
+HAVE_DOT               = YES
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS        = 0
+
+# When you want a differently looking font in the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You need to make
+# sure dot is able to find the font, which can be done by putting it in a
+# standard location or by setting the DOTFONTPATH environment variable or by
+# setting DOT_FONTPATH to the directory containing the font.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
+# each documented class showing the direct and indirect inheritance relations.
+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
+# graph for each documented class showing the direct and indirect implementation
+# dependencies (inheritance, containment, and class references variables) of the
+# class with other documented classes.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
+# YES then doxygen will generate a graph for each documented file showing the
+# direct and indirect include dependencies of the file with other documented
 # files.
-
-ENABLE_PREPROCESSING   = YES
-
-# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro 
-# names in the source code. If set to NO (the default) only conditional 
-# compilation will be performed. Macro expansion can be done in a controlled 
-# way by setting EXPAND_ONLY_PREDEF to YES.
-
-MACRO_EXPANSION        = YES
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES 
-# then the macro expansion is limited to the macros specified with the 
-# PREDEFINED and EXPAND_AS_DEFINED tags.
-
-EXPAND_ONLY_PREDEF     = NO
-
-# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files 
-# pointed to by INCLUDE_PATH will be searched when a #include is found.
-
-SEARCH_INCLUDES        = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that 
-# contain include files that are not input files but should be processed by 
-# the preprocessor.
-
-INCLUDE_PATH           = ../source/Lib/
-
-#                         ../source/Lib/TLibCommon \
-#                         ../source/Lib/TLibEncoder \
-#                         ../source/Lib/TLibDecoder \
-#                         ../source/Lib/libmd5 \
-#                         ../source/Lib/TLibVideoIO
-#
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard 
-# patterns (like *.h and *.hpp) to filter out the header-files in the 
-# directories. If left blank, the patterns specified with FILE_PATTERNS will 
-# be used.
-
-INCLUDE_FILE_PATTERNS  = 
-
-# The PREDEFINED tag can be used to specify one or more macro names that 
-# are defined before the preprocessor is started (similar to the -D option of 
-# gcc). The argument of the tag is a list of macros of the form: name 
-# or name=definition (no spaces). If the definition and the = are 
-# omitted =1 is assumed. To prevent a macro definition from being 
-# undefined via #undef or recursively expanded use the := operator 
-# instead of the = operator.
-
-PREDEFINED             = 
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then 
-# this tag can be used to specify a list of macro names that should be expanded. 
-# The macro definition that is found in the sources will be used. 
-# Use the PREDEFINED tag if you want to use a different macro definition that 
-# overrules the definition found in the source code.
-
-EXPAND_AS_DEFINED      = 
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then 
-# doxygen's preprocessor will remove all references to function-like macros 
-# that are alone on a line, have an all uppercase name, and do not end with a 
-# semicolon, because these will confuse the parser if not removed.
-
-SKIP_FUNCTION_MACROS   = YES
-
-#---------------------------------------------------------------------------
-# Configuration::additions related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES option can be used to specify one or more tagfiles. 
-# Optionally an initial location of the external documentation 
-# can be added for each tagfile. The format of a tag file without 
-# this location is as follows: 
-#   TAGFILES = file1 file2 ... 
-# Adding location for the tag files is done as follows: 
-#   TAGFILES = file1=loc1 "file2 = loc2" ... 
-# where "loc1" and "loc2" can be relative or absolute paths or 
-# URLs. If a location is present for each tag, the installdox tool 
-# does not have to be run to correct the links. 
-# Note that each tag file must have a unique name 
-# (where the name does NOT include the path) 
-# If a tag file is not located in the directory in which doxygen 
-# is run, you must also specify the path to the tagfile here.
-
-TAGFILES               = 
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create 
-# a tag file that is based on the input files it reads.
-
-GENERATE_TAGFILE       = 
-
-# If the ALLEXTERNALS tag is set to YES all external classes will be listed 
-# in the class index. If set to NO only the inherited external classes 
-# will be listed.
-
-ALLEXTERNALS           = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed 
-# in the modules index. If set to NO, only the current project's groups will 
-# be listed.
-
-EXTERNAL_GROUPS        = YES
-
-# The PERL_PATH should be the absolute path and name of the perl script 
-# interpreter (i.e. the result of `which perl').
-
-PERL_PATH              = /usr/bin/perl
-
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will 
-# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base 
-# or super classes. Setting the tag to NO turns the diagrams off. Note that 
-# this option also works with HAVE_DOT disabled, but it is recommended to 
-# install and use dot, since it yields more powerful graphs.
-
-CLASS_DIAGRAMS         = NO
-
-# You can define message sequence charts within doxygen comments using the \msc 
-# command. Doxygen will then run the mscgen tool (see 
-# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the 
-# documentation. The MSCGEN_PATH tag allows you to specify the directory where 
-# the mscgen tool resides. If left empty the tool is assumed to be found in the 
-# default search path.
-
-MSCGEN_PATH            = 
-
-# If set to YES, the inheritance and collaboration graphs will hide 
-# inheritance and usage relations if the target is undocumented 
-# or is not a class.
-
-HIDE_UNDOC_RELATIONS   = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is 
-# available from the path. This tool is part of Graphviz, a graph visualization 
-# toolkit from AT&T and Lucent Bell Labs. The other options in this section 
-# have no effect if this option is set to NO (the default)
-
-HAVE_DOT               = YES
-
-# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is 
-# allowed to run in parallel. When set to 0 (the default) doxygen will 
-# base this on the number of processors available in the system. You can set it 
-# explicitly to a value larger than 0 to get control over the balance 
-# between CPU load and processing speed.
-
-DOT_NUM_THREADS        = 0
-
-# By default doxygen will use the Helvetica font for all dot files that 
-# doxygen generates. When you want a differently looking font you can specify 
-# the font name using DOT_FONTNAME. You need to make sure dot is able to find 
-# the font, which can be done by putting it in a standard location or by setting 
-# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the 
-# directory containing the font.
-
-DOT_FONTNAME           = Helvetica
-
-# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. 
-# The default size is 10pt.
-
-DOT_FONTSIZE           = 10
-
-# By default doxygen will tell dot to use the Helvetica font. 
-# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to 
-# set the path where dot can find it.
-
-DOT_FONTPATH           = 
-
-# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen 
-# will generate a graph for each documented class showing the direct and 
-# indirect inheritance relations. Setting this tag to YES will force the 
-# the CLASS_DIAGRAMS tag to NO.
-
-CLASS_GRAPH            = YES
-
-# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen 
-# will generate a graph for each documented class showing the direct and 
-# indirect implementation dependencies (inheritance, containment, and 
-# class references variables) of the class with other documented classes.
-
-COLLABORATION_GRAPH    = YES
-
-# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen 
-# will generate a graph for groups, showing the direct groups dependencies
-
-GROUP_GRAPHS           = YES
-
-# If the UML_LOOK tag is set to YES doxygen will generate inheritance and 
-# collaboration diagrams in a style similar to the OMG's Unified Modeling 
-# Language.
-
-UML_LOOK               = NO
-
-# If set to YES, the inheritance and collaboration graphs will show the 
-# relations between templates and their instances.
-
-TEMPLATE_RELATIONS     = NO
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT 
-# tags are set to YES then doxygen will generate a graph for each documented 
-# file showing the direct and indirect include dependencies of the file with 
-# other documented files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 INCLUDE_GRAPH          = YES
 
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and 
-# HAVE_DOT tags are set to YES then doxygen will generate a graph for each 
-# documented header file showing the documented files that directly or 
-# indirectly include this file.
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
+# set to YES then doxygen will generate a graph for each documented file showing
+# the direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 INCLUDED_BY_GRAPH      = YES
 
-# If the CALL_GRAPH and HAVE_DOT options are set to YES then 
-# doxygen will generate a call dependency graph for every global function 
-# or class method. Note that enabling this option will significantly increase 
-# the time of a run. So in most cases it will be better to enable call graphs 
-# for selected functions only using the \callgraph command.
+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable call graphs for selected
+# functions only using the \callgraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 CALL_GRAPH             = NO
 
-# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then 
-# doxygen will generate a caller dependency graph for every global function 
-# or class method. Note that enabling this option will significantly increase 
-# the time of a run. So in most cases it will be better to enable caller 
-# graphs for selected functions only using the \callergraph command.
+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable caller graphs for selected
+# functions only using the \callergraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 CALLER_GRAPH           = NO
 
-# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen 
-# will generate a graphical hierarchy of all classes instead of a textual one.
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 GRAPHICAL_HIERARCHY    = YES
 
-# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES 
-# then doxygen will show the dependencies a directory has on other directories 
-# in a graphical way. The dependency relations are determined by the #include 
-# relations between the files in the directories.
+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
+# dependencies a directory has on other directories in a graphical way. The
+# dependency relations are determined by the #include relations between the
+# files in the directories.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DIRECTORY_GRAPH        = YES
 
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images 
-# generated by dot. Possible values are svg, png, jpg, or gif. 
-# If left blank png will be used. If you choose svg you need to set 
-# HTML_FILE_EXTENSION to xhtml in order to make the SVG files 
-# visible in IE 9+ (other browsers do not have this requirement).
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot.
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, jpg, gif and svg.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_IMAGE_FORMAT       = png
 
-# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to 
-# enable generation of interactive SVG images that allow zooming and panning. 
-# Note that this requires a modern browser other than Internet Explorer. 
-# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you 
-# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files 
-# visible. Older versions of IE do not have SVG support.
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+#
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 INTERACTIVE_SVG        = NO
 
-# The tag DOT_PATH can be used to specify the path where the dot tool can be 
+# The DOT_PATH tag can be used to specify the path where the dot tool can be
 # found. If left blank, it is assumed the dot tool can be found in the path.
-
-DOT_PATH               = 
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that 
-# contain dot files that are included in the documentation (see the 
-# \dotfile command).
-
-DOTFILE_DIRS           = 
-
-# The MSCFILE_DIRS tag can be used to specify one or more directories that 
-# contain msc files that are included in the documentation (see the 
-# \mscfile command).
-
-MSCFILE_DIRS           = 
-
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of 
-# nodes that will be shown in the graph. If the number of nodes in a graph 
-# becomes larger than this value, doxygen will truncate the graph, which is 
-# visualized by representing a node as a red box. Note that doxygen if the 
-# number of direct children of the root node in a graph is already larger than 
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note 
-# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
-
-DOT_GRAPH_MAX_NODES    = 50
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the 
-# graphs generated by dot. A depth value of 3 means that only nodes reachable 
-# from the root by following a path via at most 3 edges will be shown. Nodes 
-# that lay further from the root node will be omitted. Note that setting this 
-# option to 1 or 2 may greatly reduce the computation time needed for large 
-# code bases. Also note that the size of a graph can be further restricted by 
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the \dotfile
+# command).
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS           =
+
+# The DIAFILE_DIRS tag can be used to specify one or more directories that
+# contain dia files that are included in the documentation (see the \diafile
+# command).
+
+DIAFILE_DIRS           =
+
+# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
+# path where java can find the plantuml.jar file. If left blank, it is assumed
+# PlantUML is not used or called during a preprocessing step. Doxygen will
+# generate a warning when it encounters a \startuml command in this case and
+# will not generate output for the diagram.
+
+PLANTUML_JAR_PATH      =
+
+# When using plantuml, the specified paths are searched for files specified by
+# the !include statement in a plantuml block.
+
+PLANTUML_INCLUDE_PATH  =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
+# that will be shown in the graph. If the number of nodes in a graph becomes
+# larger than this value, doxygen will truncate the graph, which is visualized
+# by representing a node as a red box. Note that doxygen if the number of direct
+# children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_GRAPH_MAX_NODES    = 60
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
+# generated by dot. A depth value of 3 means that only nodes reachable from the
+# root by following a path via at most 3 edges will be shown. Nodes that lay
+# further from the root node will be omitted. Note that setting this option to 1
+# or 2 may greatly reduce the computation time needed for large code bases. Also
+# note that the size of a graph can be further restricted by
 # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 MAX_DOT_GRAPH_DEPTH    = 0
 
-# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent 
-# background. This is disabled by default, because dot on Windows does not 
-# seem to support this out of the box. Warning: Depending on the platform used, 
-# enabling this option may lead to badly anti-aliased labels on the edges of 
-# a graph (i.e. they become hard to read).
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not seem
+# to support this out of the box.
+#
+# Warning: Depending on the platform used, enabling this option may lead to
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
+# read).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_TRANSPARENT        = NO
 
-# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output 
-# files in one run (i.e. multiple -o and -T options on the command line). This 
-# makes dot run faster, but since only newer versions of dot (>1.8.10) 
-# support this, this feature is disabled by default.
+# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10) support
+# this, this feature is disabled by default.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_MULTI_TARGETS      = NO
 
-# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will 
-# generate a legend page explaining the meaning of the various boxes and 
-# arrows in the dot generated graphs.
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 GENERATE_LEGEND        = YES
 
-# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will 
-# remove the intermediate dot files that are used to generate 
-# the various graphs.
+# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_CLEANUP            = YES
Index: branches/HTM-14.1-update-dev0/doc/mainpage.h
===================================================================
--- branches/HTM-14.1-update-dev0/doc/mainpage.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/doc/mainpage.h	(revision 1200)
@@ -16,5 +16,5 @@
  *
  *  For <b>bug reporting and known issues</b> see:
- *  http://hevc.kw.bbc.co.uk/trac/
+ *  https://hevc.hhi.fraunhofer.de/trac/hevc
  *
  * \section License
@@ -25,5 +25,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
Index: branches/HTM-14.1-update-dev0/doc/software-manual.tex
===================================================================
--- branches/HTM-14.1-update-dev0/doc/software-manual.tex	(revision 1199)
+++ branches/HTM-14.1-update-dev0/doc/software-manual.tex	(revision 1200)
@@ -67,4 +67,70 @@
 }
 
+\newenvironment{OptionTableNoShorthand}[2]{%
+	\footnotesize
+	\def\arraystretch{1.8}
+	\clearOptions
+	\begin{longtable}{l<{\makecell[tl]{\optOption}}%
+	                  c<{\makecell[tc]{\optDefault}}%
+	                  >{\def\arraystretch{1.0}}p{0.5\textwidth}<{\clearOptions}}
+	\caption{#1} \label{#2} \\
+	\hspace*{12em}&\hspace*{8em}&\kill
+	\hline
+	 \thead{Option} &
+	 \thead{Default} &
+	 \thead{Description} \\
+	\hline
+	\endfirsthead
+	\caption[]{#1 (Continued)} \\
+	\hspace*{12em}&\hspace*{8em}&\kill
+	\hline
+	 \thead{Option} &
+	 \thead{Default} &
+	 \thead{Description} \\
+	\hline
+	\endhead
+	 \multicolumn{3}{r}{Continued...}\\
+	 \hline
+	\endfoot
+	 \hline
+	\endlastfoot
+}{%
+	\hline
+	\end{longtable}
+}
+
+\newenvironment{SEIListTable}[1]{%
+	\footnotesize
+	\def\arraystretch{1.8}
+	\clearOptions
+	\begin{longtable}{c<{\makecell[tl]{\optOption}}%
+	                  l<{\makecell[tc]{\optDefault}}%
+	                  >{\def\arraystretch{1.0}}p{0.3\textwidth}<{\clearOptions}}
+	\caption{#1} \\
+	\hspace*{12em}&\hspace*{8em}&\kill
+	\hline
+	 \thead{SEI Number} &
+	 \thead{SEI Name} &
+	 \thead{Table number of encoder controls, if available} \\
+	\hline
+	\endfirsthead
+	\caption[]{#1 (Continued)} \\
+	\hspace*{12em}&\hspace*{8em}&\kill
+	\hline
+	 \thead{SEI Number} &
+	 \thead{SEI Name} &
+	 \thead{Table number of encoder controls, if available} \\
+	\hline
+	\endhead
+	 \multicolumn{3}{r}{Continued...}\\
+	 \hline
+	\endfoot
+	 \hline
+	\endlastfoot
+}{%
+	\hline
+	\end{longtable}
+}
+
 \newenvironment{MacroTable}[1]{%
 	\footnotesize
@@ -104,4 +170,7 @@
 	\email{dflynn@blackberry.com}
 	\and
+  Karl Sharman
+	\email{karl.sharman@eu.sony.com}
+	\and
 	Karsten S\"uhring
 	\email{karsten.suehring@hhi.fraunhofer.de}
@@ -118,5 +187,5 @@
 \begin{abstract}
 This document is a user manual describing usage of reference software
-for the HEVC project. It applies to version 14.0
+for the HEVC project. It applies to version 16.4
 of the software.
 \end{abstract}
@@ -125,7 +194,9 @@
 \listoftables
 
+
+
 \section{General Information}
 Reference software is being made available to provide a reference
-implementation of the draft HEVC standard being developed by the Joint
+implementation of the HEVC standard being developed by the Joint
 Collaborative Team on Video Coding (JCT-VC) regrouping experts from
 ITU-T SG 16 and ISO/IEC SC29 WG11. One of the main goals of the
@@ -172,4 +243,5 @@
 MS Visual Studio 8   & build/HM_vc8.sln \\
 MS Visual Studio 9   & build/HM_vc9.sln \\
+MS Visual Studio 10  & build/HM_vc10.sln \\
 Xcode                & HM.xcodeproj \\
 Linux                & build/linux/makefile \\
@@ -186,5 +258,5 @@
 \section{Using the encoder}
 \begin{verbatim}
-TAppEncoder 	[-h] [-c config.cfg] [--parameter=value]
+TAppEncoder 	[--help] [-c config.cfg] [--parameter=value]
 \end{verbatim}
 
@@ -197,5 +269,5 @@
  \thead{Description} \\
 \hline
-\texttt{-h} & Prints parameter usage. \\
+\texttt{--help} & Prints parameter usage. \\
 \texttt{-c} & Defines configuration file to use.  Multiple configuration files
      may be used with repeated --c options. \\
@@ -203,5 +275,6 @@
     & Assigns value to a given parameter as further described below.
       Some parameters are also supported by shorthand
-      "--\em{opt}~\emph{value}".\\
+      "--\em{opt}~\emph{value}". These are shown in brackets after the parameter
+      name in the tables of this document\\
 \hline
 \end{tabular}
@@ -209,4 +282,8 @@
 
 Sample configuration files are provided in the cfg/ folder.
+Parameters are defined by the last value encountered on the command line.
+Therefore if a setting is set via a configuration file, and then a subsequent
+command line parameter changes that same setting, the command line parameter
+value will be used.
 
 \subsection{GOP structure table}
@@ -220,6 +297,6 @@
 includes pictures that are used for reference for the current
 picture as well as pictures that will be used for reference in
-the future. The encoder will not automatically calculate what
-pictures that has to be kept for future references, they have to
+the future. The encoder will not automatically calculate which
+pictures have to be kept for future references, they must
 be specified. Note that some specified reference frames for
 pictures encoded in the very first GOP after an IDR frame might
@@ -450,11 +527,13 @@
 %% File, I/O and source parameters
 %%
-\begin{OptionTable}{File, I/O and source parameters}
-\Option{InputFile} &
-\ShortOption{-i} &
+Shorthand alternatives for the parameter that can be used on the command line are shown in brackets after the parameter name.
+
+\begin{OptionTableNoShorthand}{File, I/O and source parameters.}{tab:fileIO}
+\Option{InputFile (-i)} &
+%\ShortOption{-i} &
 \Default{\NotSet} &
 Specifies the input video file.
 
-Video data must be in a raw 4:2:0 planar format (Y$'$CbCr).
+Video data must be in a raw 4:2:0, or 4:2:2 planar format, 4:4:4 planar format (Y$'$CbCr, RGB or GBR), or in a raw 4:0:0 format. 
 
 Note: When the bit depth of samples is larger than 8, each sample is encoded in
@@ -462,20 +541,20 @@
 \\
 
-\Option{BitstreamFile} &
-\ShortOption{-b} &
+\Option{BitstreamFile (-b)} &
+%\ShortOption{-b} &
 \Default{\NotSet} &
 Specifies the output coded bit stream file.
 \\
 
-\Option{ReconFile} &
-\ShortOption{-o} &
+\Option{ReconFile (-o)} &
+%\ShortOption{-o} &
 \Default{\NotSet} &
 Specifies the output locally reconstructed video file.
 \\
 
-\Option{SourceWidth}%
-\Option{SourceHeight} &
-\ShortOption{-wdt}%
-\ShortOption{-hgt} &
+\Option{SourceWidth (-wdt)}%
+\Option{SourceHeight (-hgt)} &
+%\ShortOption{-wdt}%
+%\ShortOption{-hgt} &
 \Default{0}%
 \Default{0} &
@@ -483,14 +562,24 @@
 \\
 
-\Option{InputBitDepth} &
-\ShortOption{\None} &
+\Option{InputBitDepth}
+ &
+%\ShortOption{\None} &
 \Default{8} &
 Specifies the bit depth of the input video.
 \\
 
+\Option{MSBExtendedBitDepth} &
+%\ShortOption{\None} &
+\Default{0} &
+Extends the input video by adding MSBs of value 0. When 0, no extension is applied and the InputBitDepth is used.
+
+The MSBExtendedBitDepth becomes the effective file InputBitDepth for subsequent processing.
+\\
+
 \Option{InternalBitDepth} &
-\ShortOption{\None} &
-\Default{0 \\ (InputBitDepth)} &
-Specifies the bit depth used for coding.
+%\ShortOption{\None} &
+\Default{0} &
+Specifies the bit depth used for coding. When 0, the setting defaults to the
+value of the MSBExtendedBitDepth.
 
 If the input video is a different bit depth to InternalBitDepth, it is
@@ -499,70 +588,137 @@
 \left\lfloor
  \frac{\mathrm{Pel} * 2^{\mathrm{InternalBitDepth}}}{
-     2^{\mathrm{InputBitDepth}}}
+     2^{\mathrm{MSBExtendedBitDepth}}}
 \right\rfloor
 \end{displaymath}
 
 Note: The effect of this option is as if the input video is externally
-converted to the InternalBitDepth and then coded with this value as
-InputBitDepth.  The codec has no notion of two different bit depths.
+converted to the MSBExtendedBitDepth and then to the InternalBitDepth
+and then coded with this value as InputBitDepth. The codec has no
+notion of different bit depths.
 \\
 
 \Option{OutputBitDepth} &
-\ShortOption{\None} &
-\Default{0 \\ (InternalBitDepth)} &
+%\ShortOption{\None} &
+\Default{0} &
 Specifies the bit depth of the output locally reconstructed video file.
-
+When 0, the setting defaults to the value of InternalBitDepth.
 Note: This option has no effect on the decoding process.
 \\
 
 \Option{InputBitDepthC}%
+\Option{MSBExtendedBitDepthC}%
 \Option{InternalBitDepthC}%
 \Option{OutputBitDepthC} &
-\ShortOption{\None} &
-\Default{(InputBitDepth)}%
-\Default{(InternalBitDepth)}%
-\Default{(InternalBitDepthC)} &
+%\ShortOption{\None} &
+\Default{0}%
+\Default{0}%
+\Default{0}%
+\Default{0} &
 Specifies the various bit-depths for chroma components.  These only need
 to be specified if non-equal luma and chroma bit-depth processing is
-required.
-\\
-
-\Option{ConformanceMode} &
-\ShortOption{\None} &
-\Default{0} &
-Specifies the conformance mode (cropping/padding parameters) to be applied to the input
-video. The following modes are available:
-\par
-\begin{tabular}{cp{0.45\textwidth}}
+required. When 0, the setting defaults to the corresponding non-Chroma value.
+\\
+
+\Option{InputColourSpaceConvert} &
+%\ShortOption{\None} &
+\Default{\NotSet} &
+The colour space conversion to apply to input video. Permitted values are:
+\par
+\begin{tabular}{lp{0.3\textwidth}}
+  UNCHANGED & No colour space conversion is applied \\
+  YCbCrToYCrCb & Swap the second and third components \\
+  YCbCrtoYYY & Set the second and third components to the values in the first \\
+  RGBtoGBR & Reorder the three components \\
+\end{tabular}
+\par
+If no value is specified, no colour space conversion is applied. The list may eventually also include RGB to YCbCr or YCgCo conversions.
+\\
+
+\Option{SNRInternalColourSpace} &
+%\ShortOption{\None} &
+\Default{false} &
+When this is set true, then no colour space conversion is applied prior to PSNR calculation, otherwise the inverse of InputColourSpaceConvert is applied.
+\\
+
+\Option{OutputInternalColourSpace} &
+%\ShortOption{\None} &
+\Default{false} &
+When this is set true, then no colour space conversion is applied to the reconstructed video, otherwise the inverse of InputColourSpaceConvert is applied.
+\\
+
+\Option{InputChromaFormat} &
+%\ShortOption{\None} &
+\Default{420} &
+Specifies the chroma format used in the input file. Permitted values (depending on the profile) are 400, 420, 422 or 444.
+\\
+
+\Option{ChromaFormatIDC (-cf)} &
+%\ShortOption{-cf} &
+\Default{0} &
+Specifies the chroma format to use for processing. Permitted values (depending on the profile) are 400, 420, 422 or 444; the value of 0 indicates that the value of InputChromaFormat should be used instead.
+\\
+
+\Option{MSEBasedSequencePSNR} &
+%\ShortOption{\None} &
+\Default{false} &
+When 0, the PSNR output is a linear average of the frame PSNRs; when 1, additional PSNRs are output which are formed from the average MSE of all the frames. The latter is useful when coding near-losslessly, where occasional frames become lossless.
+\\
+
+\Option{PrintFrameMSE} &
+%\ShortOption{\None} &
+\Default{false} &
+When 1, the Mean Square Error (MSE) values of each frame will also be output alongside the default PSNR values.
+\\
+
+\Option{PrintSequenceMSE} &
+%\ShortOption{\None} &
+\Default{false} &
+When 1, the Mean Square Error (MSE) values of the entire sequence will also be output alongside the default PSNR values.
+\\
+
+\Option{CabacZeroWordPaddingEnabled} &
+%\ShortOption{\None} &
+\Default{false} &
+When 1, CABAC zero word padding will be enabled. This is currently not the default value for the setting.
+\\
+
+\Option{ConformanceWindowMode} &
+%\ShortOption{\None} &
+\Default{0} &
+Specifies how the parameters related to the conformance window are interpreted (cropping/padding).
+The following modes are available:
+\par
+\begin{tabular}{cp{0.43\textwidth}}
 0 & No cropping / padding \\
 1 & Automatic padding to the next minimum CU size \\
 2 & Padding according to parameters HorizontalPadding and VerticalPadding \\
-3 & Cropping according to parameters ConfLeft, ConfRight, ConfTop and ConfBottom \\
-\end{tabular}
-\\
-
-\Option{HorizontalPadding}%
-\Option{VerticalPadding} &
-\ShortOption{-pdx}%
-\ShortOption{-pdy} &
+3 & Cropping according to parameters ConfWinLeft, ConfWinRight, ConfWinTop and ConfWinBottom \\
+\end{tabular}
+\\
+
+\Option{HorizontalPadding (-pdx)}%
+\Option{VerticalPadding (-pdy)} &
+%\ShortOption{-pdx}%
+%\ShortOption{-pdy} &
 \Default{0} &
 Specifies the horizontal and vertical padding to be applied to the input
-video in luma samples.  Must be a multiple of the chroma resolution
-(e.g. a multiple of two for 4:2:0).
-\\
-
-\Option{ConfLeft}%
-\Option{ConfRight}%
-\Option{ConfTop}%
-\Option{ConfBottom} &
-\ShortOption{\None} &
+video in luma samples when ConformanceWindowMode is 2.  Must be a multiple of
+the chroma resolution (e.g. a multiple of two for 4:2:0).
+\\
+
+\Option{ConfWinLeft}%
+\Option{ConfWinRight}%
+\Option{ConfWinTop}%
+\Option{ConfWinBottom} &
+%\ShortOption{\None} &
 \Default{0} &
 Specifies the horizontal and vertical cropping to be applied to the
-input video in luma samples.  Must be a multiple of the chroma
-resolution (e.g. a multiple of two for 4:2:0).
-\\
-
-\Option{FrameRate} &
-\ShortOption{-fr} &
+input video in luma samples when ConformanceWindowMode is 3. 
+Must be a multiple of the chroma resolution (e.g. a multiple of
+two for 4:2:0).
+\\
+
+\Option{FrameRate (-fr)} &
+%\ShortOption{-fr} &
 \Default{0} &
 Specifies the frame rate of the input video.
@@ -571,54 +727,97 @@
 \\
 
-\Option{FrameSkip} &
-\ShortOption{-fs} &
+\Option{FrameSkip (-fs)} &
+%\ShortOption{-fs} &
 \Default{0} &
 Specifies a number of frames to skip at beginning of input video file.
 \\
 
-\Option{FramesToBeEncoded} &
-\ShortOption{-f} &
-\Default{0 \\ (all)} &
-Specifies the number of frames to be encoded.
-\\
-\end{OptionTable}
+\Option{FramesToBeEncoded (-f)} &
+%\ShortOption{-f} &
+\Default{0} &
+Specifies the number of frames to be encoded. When 0, all frames are coded.
+\\
+
+\Option{FieldCoding} &
+%\ShortOption{\None} &
+\Default{false} &
+When 1, indicates that field-based coding is to be applied.
+\\
+
+\Option{TopFieldFirst (-Tff)} &
+%\ShortOption{\None} &
+\Default{0} &
+Indicates the order of the fields packed into the input frame. When 1, the top field is temporally first.
+\\
+
+\end{OptionTableNoShorthand}
 
 %%
 %% profile, level and conformance options
 %%
-\begin{OptionTable}{Profile and level parameters}
+\begin{OptionTableNoShorthand}{Profile and level parameters}{tab:profile}
 \Option{Profile} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{none} &
 Specifies the profile to which the encoded bitstream complies.
-Valid values are: none, main, main10, main-still-picture.
+
+Valid HEVC Ver. 1 values are: none, main, main10, main-still-picture
+
+Valid HEVC Ver. 2 (RExt) values are: main-RExt, high-throughput-RExt,
+monochrome, monochrome12, monochrome16, main12, main_422_10,
+main_422_12, main_444, main_444_10, main_444_12, main_444_16,
+main_intra, main_10_intra, main_12_intra, main_422_10_intra, main_422_12_intra,
+main_444_intra, main_444_10_intra, main_444_12_intra, main_444_16_intra.
+
+When main-RExt is specified, the constraint flags are either manually specified, or calculated via the other supplied settings.
 
 Compatibility flags are automatically determined according to the profile.
-If --Profile=main, then main10 will always be signalled as compatible.
-If --Profile=main10, then main will be signalled as compatible if the bit-depth is 8-bit.
-
-NB: There is currently no validation that the encoder configuration complies with the profile and level constraints.
+NB: There is currently only limited validation that the encoder configuration complies with the profile, level and tier constraints.
 \\
 
 \Option{Level} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{none} &
 Specifies the level to which the encoded bitstream complies.
-Valid values are: none, 1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2.
-
-NB: There is currently no validation that the encoder configuration complies with the profile and level constraints.
+Valid values are: none, 1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2, 8.5
+
+NB: There is currently only limited validation that the encoder configuration complies with the profile, level and tier constraints.
 \\
 
 \Option{Tier} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{main} &
 Specifies the level tier to which the encoded bitsream complies.
 Valid values are: main, high.
 
-NB: There is currently no validation that the encoder configuration complies with the profile and level constraints.
+NB: There is currently only limited validation that the encoder configuration complies with the profile, level and tier constraints.
+\\
+
+\Option{MaxBitDepthConstraint} &
+%\ShortOption{\None} &
+\Default{0} &
+For --profile=main-RExt, specifies the value to use to derive the general_max_bit_depth constraint flags for RExt profiles; when 0, use $\max(InternalBitDepth, InternalBitDepthC)$
+\\
+
+\Option{MaxChromaFormatConstraint} &
+%\ShortOption{\None} &
+\Default{0} &
+For --profile=main-RExt, specifies the chroma-format to use for the general profile constraints for RExt profiles; when 0, use the value of ChromaFormatIDC.
+\\
+
+\Option{IntraConstraintFlag} &
+%\ShortOption{\None} &
+\Default{false} &
+For --profile=main-RExt, specifies the value of general_intra_constraint_flag to use for RExt profiles.
+\\
+
+\Option{LowerBitRateConstraintFlag} &
+%\ShortOption{\None} &
+\Default{true} &
+Specifies the value of general_lower_bit_constraint_flag to use for RExt profiles.
 \\
 
 \Option{ProgressiveSource} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Specifies the value of general_progressive_source_flag
@@ -626,5 +825,5 @@
 
 \Option{InterlacedSource} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Specifies the value of general_interlaced_source_flag 
@@ -632,5 +831,5 @@
 
 \Option{NonPackedSource} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Specifies the value of general_non_packed_constraint_flag
@@ -638,10 +837,10 @@
 
 \Option{FrameOnly} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Specifies the value of general_frame_only_constraint_flag
 \\
 
-\end{OptionTable}
+\end{OptionTableNoShorthand}
 
 
@@ -649,7 +848,8 @@
 %% Unit definition parameters
 %%
-\begin{OptionTable}{Unit definition parameters}
+
+\begin{OptionTableNoShorthand}{Unit definition parameters}{tab:unit}
 \Option{MaxCUWidth} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{64} &
 Defines the maximum CU width.
@@ -657,17 +857,17 @@
 
 \Option{MaxCUHeight} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{64} &
 Defines the maximum CU height.
 \\
 
-\Option{MaxCUSize} &
-\ShortOption{\None} &
+\Option{MaxCUSize (-s)} &
+%\ShortOption{\None} &
 \Default{64} &
 Defines the maximum CU size.
 \\
 
-\Option{MaxPartitionDepth} &
-\ShortOption{-h} &
+\Option{MaxPartitionDepth (-h)} &
+%\ShortOption{-h} &
 \Default{4} &
 Defines the depth of the CU tree.
@@ -675,5 +875,5 @@
 
 \Option{QuadtreeTULog2MaxSize} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{6 \\ ($= \mathrm{log}_2(64)$)} &
 Defines the Maximum TU size in logarithm base 2.
@@ -681,5 +881,5 @@
 
 \Option{QuadtreeTULog2MinSize} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{2 \\ ($= \mathrm{log}_2(4)$)} &
 Defines the Minimum TU size in logarithm base 2.
@@ -687,5 +887,5 @@
 
 \Option{QuadtreeTUMaxDepthIntra} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{1} &
 Defines the depth of the TU tree for intra CUs.
@@ -693,9 +893,10 @@
 
 \Option{QuadtreeTUMaxDepthInter} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{2} &
 Defines the depth of the TU tree for inter CUs.
 \\
-\end{OptionTable}
+
+\end{OptionTableNoShorthand}
 
 
@@ -703,7 +904,8 @@
 %% Coding structure parameters
 %%
-\begin{OptionTable}{Coding structure parameters}
-\Option{IntraPeriod} &
-\ShortOption{-ip} &
+
+\begin{OptionTableNoShorthand}{Coding structure parameters}{tab:coding-structure}
+\Option{IntraPeriod (-ip)} &
+%\ShortOption{-ip} &
 \Default{$-1$} &
 Specifies the intra frame period.
@@ -711,6 +913,6 @@
 \\
 
-\Option{DecodingRefreshType} &
-\ShortOption{-dr} &
+\Option{DecodingRefreshType (-dr)} &
+%\ShortOption{-dr} &
 \Default{0} &
 Specifies the type of decoding refresh to apply at the intra frame period
@@ -718,12 +920,13 @@
 \par
 \begin{tabular}{cp{0.45\textwidth}}
-0 & Applies an I picture (not a clean random access point). \\
-1 & Applies a non-IDR clean random access point (open GOP). \\
-2 & Applies an IDR random access point (closed GOP). \\
-\end{tabular}
-\\
-
-\Option{GOPSize} &
-\ShortOption{-g} &
+0 & Applies an I picture (not a intra random access point). \\
+1 & Applies a CRA intra random access point (open GOP). \\
+2 & Applies an IDR intra random access point (closed GOP). \\
+3 & Use recovery point SEI messages to indicate random access. \\
+\end{tabular}
+\\
+
+\Option{GOPSize (-g)} &
+%\ShortOption{-g} &
 \Default{1} &
 Specifies the size of the cyclic GOP structure.
@@ -731,5 +934,5 @@
 
 \Option{Frame\emph{N}} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{\NotSet} &
 Multiple options that define the cyclic GOP structure that will be used
@@ -739,30 +942,14 @@
 See section~\ref{sec:gop-structure} for further details.
 \\
-
-\Option{ListCombination} &
-\ShortOption{-lc} &
-\Default{true} &
-Enables or disables the use of the combined reference list for uni-prediction
-in B-slices.
-\par
-\begin{tabular}{cp{0.45\textwidth}}
-  0 & Reference list~0 and reference list~1 are identical and reference
-      list~0 is used as the combined reference list. \\
-  1 & The combined reference list is derived from reference list~0 and
-      reference list~1. \\
-\end{tabular}
-NB: LComb can only be 0 in low delay coding (more precisely, when list 0
-and list 1 are the same)
-\\
-\end{OptionTable}
-
+\end{OptionTableNoShorthand}
 
 %%
 %% Motion estimation parameters
 %%
-\begin{OptionTable}{Motion estimation parameters}
+
+\begin{OptionTableNoShorthand}{Motion estimation parameters}{tab:motion-estimation}
 \Option{FastSearch} &
-\ShortOption{\None} &
-\Default{true} &
+%\ShortOption{\None} &
+\Default{1} &
 Enables or disables the use of a fast motion search.
 \par
@@ -770,9 +957,10 @@
  0 & Full search method \\
  1 & Fast search method \\
-\end{tabular}
-\\
-
-\Option{SearchRange} &
-\ShortOption{-sr} &
+ 2 & Previous motion vector fast search method \\
+\end{tabular}
+\\
+
+\Option{SearchRange (-sr)} &
+%\ShortOption{-sr} &
 \Default{96} &
 Specifies the search range used for motion estimation.
@@ -784,5 +972,5 @@
 
 \Option{BipredSearchRange} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{4} &
 Specifies the search range used for bi-prediction refinement in motion
@@ -791,5 +979,5 @@
 
 \Option{HadamardME} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{true} &
 Enables or disables the use of the Hadamard transform in fractional-pel motion
@@ -803,5 +991,5 @@
 
 \Option{ASR} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables or disables the use of adaptive search ranges, where the motion
@@ -819,5 +1007,13 @@
 \end{displaymath}
 \\
-\end{OptionTable}
+
+\Option{MaxNumMergeCand} &
+%\ShortOption{\None} &
+\Default{5} &
+Specifies the maximum number of merge candidates to use.
+\\
+
+
+\end{OptionTableNoShorthand}
 
 
@@ -825,7 +1021,8 @@
 %% Mode decision parameters
 %%
-\begin{OptionTable}{Mode decision parameters}
-\Option{LambdaModifier$N$} &
-\ShortOption{-LM$N$} &
+
+\begin{OptionTableNoShorthand}{Mode decision parameters}{tab:mode-decision}
+\Option{LambdaModifier$N$ (-LM$N$)} &
+%\ShortOption{-LM$N$} &
 \Default{1.0} &
 Specifies a value that is multiplied with the Lagrange multiplier
@@ -833,9 +1030,27 @@
 when encoding temporal layer~$N$.
 \par
-$N$ may be in the range 0--7.
+$N$ may be in the range 0 (inclusive) to 7 (exclusive).
+\\
+
+\Option{ECU} &
+%\ShortOption{\None} &
+\Default{false} &
+Enables or disables the use of early CU determination.  When enabled, skipped CUs will not be split further.
+\\
+
+\Option{CFM} &
+%\ShortOption{\None} &
+\Default{false} &
+Enables or disables the use of Cbf-based fast encoder mode.  When enabled, once a 2Nx2N CU has been evaluated, if the RootCbf is 0, further PU splits will not be evaluated.
+\\
+
+\Option{ESD} &
+%\ShortOption{\None} &
+\Default{false} &
+Enables or disables the use of early skip detection.  When enabled, the skip mode will be tested before any other.
 \\
 
 \Option{FEN} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables or disables the use of fast encoder mode.  When enabled,
@@ -850,5 +1065,5 @@
 
 \Option{FDM} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{true} &
 Enables or disables the use of fast encoder decisions for 2Nx2N merge
@@ -859,5 +1074,5 @@
 
 \Option{RDpenalty} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0} &
 RD-penalty for 32x32 TU for intra in non-intra slices.
@@ -871,20 +1086,20 @@
 \\
 
-\end{OptionTable}
+\end{OptionTableNoShorthand}
 
 %%
 %% Quantization parameters
 %%
-\begin{OptionTable}{Quantization parameters}
-\Option{QP} &
-\ShortOption{-q} &
+\begin{OptionTableNoShorthand}{Quantization parameters}{tab:quantization}
+\Option{QP (-q)} &
+%\ShortOption{-q} &
 \Default{30.0} &
-Specifies the base value of the quantization parameter.
-\\
-
-\Option{CbQpOffset}%
-\Option{CrQpOffset} &
-\ShortOption{-cbqpofs}%
-\ShortOption{-crqpofs} &
+Specifies the base value of the quantization parameter. If it is non-integer, the QP is switched once during encoding.
+\\
+
+\Option{CbQpOffset (-cbqpofs)}%
+\Option{CrQpOffset (-crqpofs)} &
+%\ShortOption{-cbqpofs}%
+%\ShortOption{-crqpofs} &
 \Default{0}%
 \Default{0} &
@@ -895,6 +1110,6 @@
 \\
 
-\Option{MaxCuDQPDepth} &
-\ShortOption{\None} &
+\Option{MaxCuDQPDepth (-dqd)} &
+%\ShortOption{\None} &
 \Default{0} &
 Defines maximum depth of a minimum CuDQP for sub-LCU-level delta QP.
@@ -903,17 +1118,26 @@
 
 \Option{RDOQ} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{true} &
-Enables or disables rate-distortion-optimized quantization.
+Enables or disables rate-distortion-optimized quantization for transformed TUs.
 \\
 
 \Option{RDOQTS} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{true} &
 Enables or disables rate-distortion-optimized quantization for transform-skipped TUs.
 \\
 
-\Option{DeltaQpRD} &
-\ShortOption{-dqr} &
+\Option{SelectiveRDOQ} &
+%\ShortOption{\None} &
+\Default{false} &
+Enables or disables selective rate-distortion-optimized quantization.
+A simple quantization is use to pre-analyze, whether to bypass the RDOQ process or not. 
+If all the coefficients are quantized to 0, the RDOQ process is bypassed. 
+Otherwise, the RDOQ process is performed as usual.
+\\
+
+\Option{DeltaQpRD (-dqr)} &
+%\ShortOption{-dqr} &
 \Default{0} &
 Specifies the maximum QP offset at slice level for multi-pass slice
@@ -923,6 +1147,6 @@
 \\
 
-\Option{MaxDeltaQP} &
-\ShortOption{-d} &
+\Option{MaxDeltaQP (-d)} &
+%\ShortOption{-d} &
 \Default{0} &
 Specifies the maximum QP offset at the largest coding unit level for
@@ -933,6 +1157,6 @@
 \\
 
-\Option{dQPFile} &
-\ShortOption{-m} &
+\Option{dQPFile (-m)} &
+%\ShortOption{-m} &
 \Default{\NotSet} &
 Specifies a file containing a list of QP deltas. The $n$-th line
@@ -941,16 +1165,56 @@
 \\
 
-\Option{AdaptiveQpSelection} &
-\ShortOption{-aqps} &
+\Option{AdaptiveQp (-aq)} &
+%\ShortOption{-aq} &
+\Default{false} &
+Enable or disable QP adaptation based upon a psycho-visual model.
+\\
+
+\Option{MaxQPAdaptationRange (-aqr)} &
+%\ShortOption{-aqps} &
+\Default{6} &
+Specifies the maximum QP adaptation range.
+\\
+
+\Option{AdaptiveQpSelection (-aqps)} &
+%\ShortOption{-aqps} &
 \Default{false} &
 Specifies whether QP values for non-I frames will be calculated on the
 fly based on statistics of previously coded frames.
 \\
-\Option{RecalculateQPAccordingToLambda} &
-\ShortOption{\None} &
+
+\Option{RecalculateQP...} \Option{AccordingToLambda} &
+%\ShortOption{\None} &
 \Default{false} &
 Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case.
 \\
-\end{OptionTable}
+
+\Option{ScalingList} &
+%\ShortOption{\None} &
+\Default{0} &
+Controls the specification of scaling lists:
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & Scaling lists are disabled \\
+ 1 & Use default scaling lists \\
+ 2 & Scaling lists are specified in the file indicated by ScalingListFile \\
+\end{tabular}
+\\
+
+\Option{ScalingListFile} &
+%\ShortOption{\None} &
+\Default{\NotSet} &
+When ScalingList is set to 2, this parameter indicates the name of the file, which contains the defined scaling lists.
+If ScalingList is set to 2 and this parameter is an empty string, information on the format of the scaling list file
+is output and the encoder stops.
+\\
+
+\Option{MaxCUChromaQpAdjustmentDepth} &
+%\ShortOption{\None} &
+\Default{-1} &
+Specifies the maximum depth for CU chroma QP adjustment; if negative, CU chroma QP adjustment is disabled.
+\\
+
+\end{OptionTableNoShorthand}
 
 
@@ -958,5 +1222,5 @@
 %% Slice coding parameters
 %%
-\begin{OptionTable}{Slice coding parameters}
+\begin{OptionTableNoShorthand}{Slice coding parameters}{tab:slice-coding}
 %\Option{SliceGranularity} &
 %\ShortOption{\None} &
@@ -976,5 +1240,5 @@
 
 \Option{SliceMode} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0} &
 Controls the slice partitioning method in conjunction with
@@ -990,5 +1254,5 @@
 
 \Option{SliceArgument} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{\NotSet} &
 Specifies the maximum number of CTUs, bytes or tiles in a slice depending on the
@@ -997,5 +1261,5 @@
 
 \Option{SliceSegmentMode} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0} &
 Enables (dependent) slice segment coding in conjunction with 
@@ -1011,5 +1275,5 @@
 
 \Option{SliceSegmentArgument} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{\NotSet} &
 Defines the maximum number of CTUs, bytes or tiles a slice segment
@@ -1018,5 +1282,5 @@
 
 \Option{WaveFrontSynchro} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables the use of specific CABAC probabilities synchronization at the
@@ -1025,7 +1289,19 @@
 \\
 
+\Option{TileUniformSpacing} &
+%\ShortOption{\None} &
+\Default{false} &
+Controls the mode used to determine per row and column tile sizes.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & Each tile column width and tile row height is explicitly set
+     by TileColumnWidthArray and TileRowHeightArray respectively \\
+ 1 & Tile columns and tile rows are uniformly spaced. \\
+\end{tabular}
+\\
+
 \Option{NumTileColumnsMinus1}%
 \Option{NumTileRowsMinus1} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0} &
 Specifies the tile based picture partitioning geometry as
@@ -1034,19 +1310,7 @@
 \\
 
-\Option{UniformSpacingIdc} &
-\ShortOption{\None} &
-\Default{0} &
-Controls the mode used to determine per row and column tile sizes.
-\par
-\begin{tabular}{cp{0.45\textwidth}}
- 0 & Each tile column width and tile row height is explicitly set
-     by ColumnWidthArray and RowHeightArray respectively \\
- 1 & Tile columns and tile rows are uniformly spaced. \\
-\end{tabular}
-\\
-
-\Option{ColumnWidthArray}%
-\Option{RowHeightArray} &
-\ShortOption{\None} &
+\Option{TileColumnWidthArray}%
+\Option{TileRowHeightArray} &
+%\ShortOption{\None} &
 \Default{\NotSet} &
 Specifies a space or comma separated list of widths and heights,
@@ -1054,5 +1318,5 @@
 list corresponds to the leftmost tile column or topmost tile row.
 \\
-\end{OptionTable}
+\end{OptionTableNoShorthand}
 
 
@@ -1061,7 +1325,7 @@
 %% Deblocking filter parameters
 %%
-\begin{OptionTable}{Deblocking filter parameters}
+\begin{OptionTableNoShorthand}{Deblocking filter parameters}{tab:deblocking-filter}
 \Option{LoopFilterDisable} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables or disables the in-loop deblocking filter.
@@ -1069,5 +1333,5 @@
 
 \Option{LFCrossSliceBoundaryFlag} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{true} &
 Enables or disables the use of in-loop filtering across slice
@@ -1076,5 +1340,5 @@
 
 \Option{DeblockingFilterControlPresent}&
-\ShortOption{\None}&
+%\ShortOption{\None}&
 \Default{false}&
 Enables or disables the presence of the deblocking filter control
@@ -1084,5 +1348,5 @@
 
 \Option{LoopFilterOffsetInPPS}&
-\ShortOption{\None}&
+%\ShortOption{\None}&
 \Default{false}&
 If enabled, the in-loop deblocking filter control parameters are sent in PPS. 
@@ -1097,5 +1361,5 @@
 
 \Option{LoopFilterTcOffset_div2}&
-\ShortOption{\None}&
+%\ShortOption{\None}&
 \Default{0}&
 Specifies the base value for the in-loop deblocking filter parameter tc_offset_div2. The final value of tc_offset_div2 
@@ -1104,5 +1368,5 @@
 
 \Option{LoopFilterBetaOffset_div2}&
-\ShortOption{\None}&
+%\ShortOption{\None}&
 \Default{0}&
 Specifies the base value for the in-loop deblocking filter parameter beta_offset_div2. The final value of beta_offset_div2 
@@ -1110,5 +1374,17 @@
 \\
 
-\end{OptionTable}
+\Option{DeblockingFilterMetric}&
+%\ShortOption{\None}&
+\Default{false}&
+Enables or disables the use of a deblocking filter metric to evaluate the suitability of deblocking..
+\\
+
+\Option{LFCrossSliceBoundaryFlag}&
+%\ShortOption{\None}&
+\Default{true}&
+Enables or disables the use of a deblocking across tile boundaries.
+\\
+
+\end{OptionTableNoShorthand}
 
 
@@ -1117,20 +1393,15 @@
 %% Coding tools parameters
 %%
-\begin{OptionTable}{Coding tools parameters}
-%\Option{ALF} &
-%\ShortOption{\None} &
-%\Default{true} &
-%Enables or disables the adaptive loop filter.
-%\\
-
-%\Option{ALFLowLatencyEncode} &
-%\ShortOption{\None} &
-%\Default{false} &
-%Specifies the operating mode (low latency or high efficiency) of the
-%adaptive loop filter.
-%\\
+
+\begin{OptionTableNoShorthand}{Coding tools parameters}{tab:coding-tools}
+
+\Option{AMP} &
+%\ShortOption{\None} &
+\Default{true} &
+Enables or disables the use of asymmetric motion partitions.
+\\
 
 \Option{SAO} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{true} &
 Enables or disables the sample adaptive offset (SAO) filter.
@@ -1138,5 +1409,5 @@
 
 \Option{SAOLcuBoundary} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables or disables SAO parameter estimation using non-deblocked pixels
@@ -1144,18 +1415,6 @@
 \\
 
-%\Option{LMChroma} &
-%\ShortOption{\None} &
-%\Default{true} &
-%Enables or disables the intra chroma-from-luma prediction mode.
-%\\
-
-%\Option{NSQT} &
-%\ShortOption{\None} &
-%\Default{true} &
-%Enables or disables the non-square quadtree transform.
-%\\
-
 \Option{ConstrainedIntraPred} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables or disables constrained intra prediction.  Constrained intra
@@ -1165,5 +1424,5 @@
 
 \Option{TransquantBypassEnableFlag} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables or disables the ability to bypass the transform,
@@ -1176,5 +1435,5 @@
 
 \Option{CUTransquantBypassFlagForce} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0} &
 Controls the per CU transformation, quantization and filtering
@@ -1191,5 +1450,5 @@
 
 \Option{PCMEnabledFlag} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables or disables the use of PCM. The encoder will use cost measures on a CU-by-CU basis to determine if PCM mode is to be applied.
@@ -1197,5 +1456,5 @@
 
 \Option{PCMLog2MaxSize} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{5 \\ ($= \mathrm{log}_2(32)$)} &
 Specifies log2 of the maximum PCM block size. When PCM is enabled, the
@@ -1205,5 +1464,5 @@
 
 \Option{PCMLog2MinSize} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{3} &
 Specifies log2 of the minimum PCM block size. When PCM is enabled, the
@@ -1215,6 +1474,6 @@
 
 \Option{PCMInputBitDepthFlag} &
-\ShortOption{\None} &
-\Default{1} &
+%\ShortOption{\None} &
+\Default{true} &
 If enabled specifies that PCM sample bit-depth is set equal to
 InputBitDepth. Otherwise, it specifies that PCM sample bit-depth is set
@@ -1223,5 +1482,5 @@
 
 \Option{PCMFilterDisableFlag} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 If enabled specifies that loop-filtering on reconstructed samples of PCM
@@ -1231,18 +1490,24 @@
 \\
 
-\Option{WeightedPredP} &
-\ShortOption{-wpP} &
+\Option{WeightedPredP (-wpP)} &
+%\ShortOption{-wpP} &
 \Default{false} &
 Enables the use of weighted prediction in P slices.
 \\
 
-\Option{WeightedPredB} &
-\ShortOption{-wpB} &
+\Option{WeightedPredB (-wpB)} &
+%\ShortOption{-wpB} &
 \Default{false} &
 Enables the use of weighted prediction in B slices.
 \\
 
-\Option{SignHideFlag} &
-\ShortOption{-SBH} &
+\Option{Log2ParallelMergeLevel} &
+%\ShortOption{\None} &
+\Default{2} &
+Defines the PPS-derived Log2ParMrgLevel variable.
+\\
+
+\Option{SignHideFlag (-SBH)} &
+%\ShortOption{-SBH} &
 \Default{true} &
 If enabled specifies that for each 4x4 coefficient group for which the
@@ -1254,6 +1519,6 @@
 \\
 
-\Option{StrongIntraSmoothing} &
-\ShortOption{-sis} &
+\Option{StrongIntraSmoothing (-sis)} &
+%\ShortOption{-sis} &
 \Default{true} &
 If enabled specifies that for 32x32 intra prediction block, the intra smoothing
@@ -1265,5 +1530,5 @@
 
 \Option{TMVPMode} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{1} &
 Controls the temporal motion vector prediction mode.
@@ -1277,12 +1542,11 @@
 
 \Option{TransformSkip} &
-\ShortOption{\None} &
-\Default{false} &
-Enables or disables transform-skipping mode decision for 4x4 TUs
-\footnote{Enables transform_skip_enabled and per 4x4 TU tests}.
+%\ShortOption{\None} &
+\Default{false} &
+Enables or disables transform-skipping mode decision.
 \\
 
 \Option{TransformSkipFast} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Enables or disables reduced testing of the transform-skipping mode
@@ -1293,13 +1557,14 @@
 This option has no effect if TransformSkip is disabled.
 \\
-\end{OptionTable}
+\end{OptionTableNoShorthand}
 
 %%
 %% Rate control parameters
 %%
-\begin{OptionTable}{Rate control parameters}
+
+\begin{OptionTableNoShorthand}{Rate control parameters}{tab:rate-control}
 
 \Option{RateControl} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Rate control: enables rate control or not.
@@ -1307,5 +1572,5 @@
 
 \Option{TargetBitrate} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0} &
 Rate control: target bitrate, in bps.
@@ -1313,5 +1578,5 @@
 
 \Option{KeepHierarchicalBit} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0} &
 Rate control: 0: equal bit allocation among pictures;
@@ -1321,5 +1586,5 @@
 
 \Option{LCULevelRateControl} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{true} &
 Rate control: true: LCU level RC; false: picture level RC.
@@ -1327,5 +1592,5 @@
 
 \Option{RCLCUSeparateModel} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{true} &
 Rate control: use LCU level separate R-lambda model or not.
@@ -1334,5 +1599,5 @@
 
 \Option{InitialQP} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0} &
 Rate control: initial QP value for the first picture.
@@ -1341,46 +1606,39 @@
 
 \Option{RCForceIntraQP} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{false} &
 Rate control: force intra QP to be equal to initial QP or not.
 \\
-\end{OptionTable}
+\end{OptionTableNoShorthand}
 
 %%
 %% VUI parameters
 %%
-\begin{OptionTable}{VUI parameters}
-\Option{VuiParametersPresent} &
-\ShortOption{-vui} &
+\begin{OptionTableNoShorthand}{VUI parameters}{tab:VUI}
+\Option{VuiParametersPresent (-vui)} &
 \Default{false} &
 Enable generation of vui_parameters().
 \\
 \Option{AspectRatioInfoPresent} &
-\ShortOption{} &
 \Default{false} &
 Signals whether aspect_ratio_idc is present.
 \\
 \Option{AspectRatioIdc} &
-\ShortOption{} &
 \Default{0} &
 aspect_ratio_idc
 \\
 \Option{SarWidth} &
-\ShortOption{} &
 \Default{0} &
 Specifies the horizontal size of the sample aspect ratio.
 \\
 \Option{SarHeight} &
-\ShortOption{} &
 \Default{0} &
 Specifies the vertical size of the sample aspect ratio.
 \\
 \Option{OverscanInfoPresent} &
-\ShortOption{} &
 \Default{false} &
 Signals whether overscan_info_present_flag is present.
 \\
 \Option{OverscanAppropriate} &
-\ShortOption{} &
 \Default{false} &
 Indicates whether cropped decoded pictures are suitable for display using overscan.
@@ -1392,15 +1650,12 @@
 \\
 \Option{VideoSignalTypePresent} &
-\ShortOption{} &
 \Default{false} &
 Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present.
 \\
 \Option{VideoFormat} &
-\ShortOption{} &
 \Default{5} &
 Indicates representation of pictures.
 \\
 \Option{VideoFullRange} &
-\ShortOption{} &
 \Default{false} &
 Indicates the black level and range of luma and chroma signals.
@@ -1412,40 +1667,32 @@
 \\
 \Option{ColourDescriptionPresent} &
-\ShortOption{} &
 \Default{false} &
 Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present.
 \\
 \Option{ColourPrimaries} &
-\ShortOption{} &
 \Default{2} &
 Indicates chromaticity coordinates of the source primaries.
 \\
 \Option{TransferCharateristics} &
-\ShortOption{} &
 \Default{2} &
 Indicates the opto-electronic transfer characteristics of the source.
 \\
 \Option{MatrixCoefficients} &
-\ShortOption{} &
 \Default{2} &
 Describes the matrix coefficients used in deriving luma and chroma from RGB primaries.
 \\
 \Option{ChromaLocInfoPresent} &
-\ShortOption{} &
 \Default{false} &
 Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present.
 \\
 \Option{ChromaSampleLocTypeTopField} &
-\ShortOption{} &
 \Default{0} &
 Specifies the location of chroma samples for top field.
 \\
 \Option{ChromaSampleLocTypeBottomField} &
-\ShortOption{} &
 \Default{0} &
 Specifies the location of chroma samples for bottom field.
 \\
 \Option{NeutralChromaIndication} &
-\ShortOption{} &
 \Default{false} &
 Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1).
@@ -1453,11 +1700,10 @@
 
 \Option{DefaultDisplayWindowFlag} &
-\ShortOption{\None} &
-\Default{0} &
+\Default{flag} &
 Indicates the presence of the Default Window parameters.
 \par
 \begin{tabular}{cp{0.45\textwidth}}
-0 & Disabled \\
-1 & Enabled \\
+false & Disabled \\
+true & Enabled \\
 \end{tabular}
 \\
@@ -1467,5 +1713,4 @@
 \Option{DefDispWinTopOffset}%
 \Option{DefDispWinBottomOffset} &
-\ShortOption{\None} &
 \Default{0} &
 Specifies the horizontal and vertical offset to be applied to the
@@ -1474,52 +1719,490 @@
 \\
 
+\Option{FrameFieldInfoPresentFlag} &
+\Default{false} &
+Specificies the value of the VUI syntax element `frame_field_info_present_flag', which indicates that pic_struct and field coding related values are present in picture timing SEI messages.
+\\
+
+\Option{PocProportionalToTimingFlag} &
+\Default{false} &
+Specificies the value of the VUI syntax element `vui_poc_proportional_to_timing_flag', which indicates that the POC value is proportional to the output time with respect to the first picture in the CVS.
+\\
+
+\Option{NumTicksPocDiffOneMinus} &
+\Default{0} &
+Specificies the value of the VUI syntax element `vui_num_ticks_poc_diff_one_minus1', which specifies the number of clock ticks corresponding to a difference of picture order count values equal to 1, and is used only when PocProportionalToTimingFlag is true.
+\\
+
 \Option{BitstreamRestriction} &
-\ShortOption{} &
 \Default{false} &
 Signals whether bitstream restriction parameters are present.
 \\
 \Option{TilesFixedStructure} &
-\ShortOption{} &
 \Default{false} &
 Indicates that each active picture parameter set has the same values of the syntax elements related to tiles.
 \\
 \Option{MotionVectorsOverPicBoundaries} &
-\ShortOption{} &
 \Default{false} &
 Indicates that no samples outside the picture boundaries are used for inter prediction.
 \\
 \Option{MaxBytesPerPicDenom} &
-\ShortOption{} &
 \Default{2} &
 Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture.
 \\
 \Option{MaxBitsPerMinCuDenom} &
-\ShortOption{} &
 \Default{1} &
 Indicates an upper bound for the number of bits of coding_unit() data.
 \\
 \Option{Log2MaxMvLengthHorizontal} &
-\ShortOption{} &
 \Default{15} &
 Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units.
 \\
 \Option{Log2MaxMvLengthVertical} &
-\ShortOption{} &
 \Default{15} &
 Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units.
 \\
-\end{OptionTable}
-
+\end{OptionTableNoShorthand}
+
+
+\begin{OptionTableNoShorthand}{Range Extensions (Version 2) tool parameters}{tab:rext-tools}
+
+\Option{CostMode} &
+\Default{lossy} &
+Specifies the cost mode to use.
+\par
+\begin{tabular}{lp{0.3\textwidth}}
+  lossy                   & $cost=distortion+\lambda \times bits$ \\
+  sequence_level_lossless & $cost=distortion / \lambda + bits$. \\
+  lossless                & As with sequence_level_lossless, but QP is also set to 0 (this will be deprecated in the future) \\
+  mixed_lossless_lossy    & As with sequence_level_lossless, but QP'=4 is used for pre-estimates of transquant-bypass blocks \\
+\end{tabular}
+\\
+
+\Option{ExtendedPrecision} &
+\Default{false} &
+Specifies the use of extended_precision_processing flag. Note that unless the HIGH_BIT_DEPTH_SUPPORT macro in TypeDef.h is enabled, all internal bit depths must be 8 when the ExtendedPrecision setting is enabled.
+This setting is only valid for the 16-bit RExt profiles.
+\\
+
+\Option{HighPrecisionPredictionWeighting} &
+\Default{false} &
+Specifies the value of high_precision_prediction_weighting_flag. This setting is only valid for the 16-bit or 4:4:4 RExt profiles.
+\\
+
+\Option{CrossComponentPrediction} &
+\Default{false} &
+When true, specifies the use of the cross component prediction tool (4:4:4 processing only). Version 1 and some Version 2 (RExt) profiles require this to be false.
+\\
+
+\Option{ReconBasedCrossCPredictionEstimate} &
+\Default{false} &
+If true, then when determining the alpha value for cross-component prediction, use the reconstructed residual rather than the pre-transform encoder-side residual
+\\
+
+\Option{SaoLumaOffsetBitShift}
+\Option{SaoChromaOffsetBitShift}&
+\Default{0}
+\Default{0} &
+Specifies the shift to apply to the SAO parameters. If negative, an estimate will be calculated based upon the initial QP. Version 1 and some Version 2 (RExt) profiles require this to be 0.
+\\
+
+\Option{TransformSkipLog2MaxSize} &
+\Default{2} &
+Specifies the maximum TU size for which transform-skip can be used; the minimum value is 2. Version 1 and some Version 2 (RExt) profiles require this to be 2.
+\\
+
+\Option{ImplicitResidualDPCM} &
+\Default{false} &
+When true, specifies the use of the implicitly signalled residual RDPCM tool (for intra). Version 1 and some Version 2 (RExt) profiles require this to be false.
+\\
+
+\Option{ExplicitResidualDPCM} &
+\Default{false} &
+When true, specifies the use of the explicitly signalled residual RDPCM tool (for intra-block-copy and inter). Version 1 and some Version 2 (RExt) profiles require this to be false.
+\\
+
+\Option{ResidualRotation} &
+\Default{false} &
+When true, specifies the use of the residual rotation tool. Version 1 and some Version 2 (RExt) profiles require this to be false.
+\\
+
+\Option{SingleSignificanceMapContext} &
+\Default{false} &
+When true, specifies the use of a single significance map context for transform-skipped and transquant-bypassed TUs. Version 1 and some Version 2 (RExt) profiles require this to be false.
+\\
+
+\Option{GolombRiceParameterAdaptation} &
+\Default{false} &
+When true, enable the adaptation of the Golomb-Rice parameter over the course of each slice. Version 1 and some Version 2 (RExt) profiles require this to be false.
+\\
+
+\Option{AlignCABACBeforeBypass} &
+\Default{false} &
+When true, align the CABAC engine to a defined fraction of a bit prior to coding bypass data (including sign bits) when coeff_abs_level_remaining syntax elements are present in the group.
+This must always be true for the high-throughput-RExt profile, and false otherwise.
+\\
+
+\Option{IntraReferenceSmoothing} &
+\Default{true} &
+When true, enable intra reference smoothing, otherwise disable it. Version 1 and some Version 2 (RExt) profiles require this to be true.
+\\
+
+\end{OptionTableNoShorthand}
+
+\subsection{Encoder SEI parameters}
+The table below lists the SEI messages defined for Version 1 and Range-Extensions, and if available, the respective table that lists the controls within the HM Encoder to include the messages within the bit stream.
+
+\begin{SEIListTable}{List of Version 1 and RExt SEI messages}
+    0 & Buffering period                         & Table \ref{tab:sei-buffering-period} \\
+    1 & Picture timing                           & Table \ref{tab:sei-picture-timing} \\
+    2 & Pan-scan rectangle                       & (Not handled)\\
+    3 & Filler payload                           & (Not handled)\\
+    4 & User data registered by Rec. ITU-T T.35  & (Not handled)\\
+    5 & User data unregistered                   & Decoded only\\
+    6 & Recovery point                           & Table \ref{tab:sei-recovery-point} \\
+    9 & Scene information                        & (Not handled)\\
+   15 & Picture snapshot                         & (Not handled)\\
+   16 & Progressive refinement segment start     & (Not handled)\\
+   17 & Progressive refinement segment end       & (Not handled)\\
+   19 & Film grain characteristics               & (Not handled)\\
+   22 & Post-filter hint                         & (Not handled)\\
+   23 & Tone mapping information                 & Table \ref{tab:sei-tone-mapping-info} \\
+   45 & Frame packing arrangement                & Table \ref{tab:sei-frame-packing-arrangement} \\
+   47 & Display orientation                      & Table \ref{tab:sei-display-orientation} \\
+  128 & Structure of pictures information        & Table \ref{tab:sei-sop-info} \\
+  129 & Active parameter sets                    & Table \ref{tab:sei-active-parameter-sets} \\
+  130 & Decoding unit information                & Table \ref{tab:sei-decoding-unit-info} \\
+  131 & Temporal sub-layer zero index            & Table \ref{tab:sei-temporal-level-0} \\
+  132 & Decoded picture hash                     & Table \ref{tab:sei-decoded-picture-hash} \\
+  133 & Scalable nesting                         & Table \ref{tab:sei-scalable-nesting} \\
+  134 & Region refresh information               & Table \ref{tab:sei-region-refresh-info} \\
+  135 & No display                               & Table \ref{tab:sei-no-display} \\
+  136 & Time code                                & Table \ref{tab:sei-time-code} \\
+  137 & Mastering display colour volume          & Table \ref{tab:sei-mastering-display-colour-volume} \\
+  138 & Segmented rectangular frame packing arrangement & Table \ref{tab:sei-seg-rect-fpa}\\
+  139 & Temporal motion-constrained tile sets    & Table \ref{tab:sei-tmcts} \\
+  140 & Chroma resampling filter hint            & Table \ref{tab:chroma-resampling-filter-hint} \\
+  141 & Knee function information                & Table \ref{tab:sei-knee-function} \\
+  142 & Colour remapping information             & (Not handled)\\
+  143 & Deinterlaced field identification        & (Not handled)\\
+\end{SEIListTable}
 %%
 %% SEI messages
 %%
-\begin{OptionTable}{SEI messages}
+
+  
+
+\begin{OptionTableNoShorthand}{Buffering period SEI message encoder parameters}{tab:sei-buffering-period}
+\Option{SEIBufferingPeriod} &
+\Default{0} &
+Enables or disables the insertion of the Buffering period
+SEI messages. This option has no effect if VuiParametersPresent is disabled.
+SEIBufferingPeriod requires SEIActiveParameterSets to be enabled.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Picture timing SEI message encoder parameters}{tab:sei-picture-timing}
+\Option{SEIPictureTiming} &
+\Default{0} &
+Enables or disables the insertion of the Picture timing
+SEI messages. This option has no effect if VuiParametersPresent is disabled.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Recovery point SEI message encoder parameters}{tab:sei-recovery-point}
+\Option{SEIRecoveryPoint} &
+\Default{0} &
+Enables or disables the insertion of the Recovery point
+SEI messages.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Tone mapping information SEI message encoder parameters}{tab:sei-tone-mapping-info}
+\Option{SEIToneMappingInfo} &
+\Default{0} &
+Enables or disables the insertion of the Tone Mapping SEI message.
+\\
+\Option{SEIToneMapId} &
+\Default{0} &
+Specifies Id of Tone Mapping SEI message for a given session.
+\\
+\Option{SEIToneMapCancelFlag} &
+\Default{false} &
+Indicates that Tone Mapping SEI message cancels the persistance or follows.
+\\
+\Option{SEIToneMapPersistenceFlag} &
+\Default{true} &
+Specifies the persistence of the Tone Mapping SEI message.
+\\
+\Option{SEIToneMapCodedDataBitDepth} &
+\Default{8} &
+Specifies Coded Data BitDepth of Tone Mapping SEI messages.
+\\
+\Option{SEIToneMapTargetBitDepth} &
+\Default{8} &
+Specifies Output BitDepth of Tome mapping function.
+\\
+\Option{SEIToneMapModelId} &
+\Default{0} &
+Specifies Model utilized for mapping coded data into 
+target_bit_depth range.
+\par
+\begin{tabular}{cp{0.35\textwidth}}
+  0 & linear mapping with clipping \\
+  1 & sigmoidal mapping \\
+  2 & user-defined table mapping \\
+  3 & piece-wise linear mapping \\
+  4 & luminance dynamic range mapping \\
+\end{tabular}
+\\
+\Option{SEIToneMapMinValue} &
+\Default{0} &
+Specifies the minimum value in mode 0.
+\\
+\Option{SEIToneMapMaxValue} &
+\Default{1023} &
+Specifies the maxmum value in mode 0.
+\\
+\Option{SEIToneMapSigmoidMidpoint} &
+\Default{512} &
+Specifies the centre point in mode 1.
+\\
+\Option{SEIToneMapSigmoidWidth} &
+\Default{960} &
+Specifies the distance between 5% and 95% values of 
+the target_bit_depth in mode 1.
+\\
+\Option{SEIToneMapStartOfCodedInterval} &
+\Default{\None} &
+Array of user-defined mapping table. 
+Default table can be set to the following:
+\par
+\begin{tabular}{cp{0.35\textwidth}}
+0 12 24 36 48 60 72 84 96 108 120 132 144 156 168 180 
+\\
+192 192 196 204 208 216 220 228 232 240 248 252 260 264 
+\\
+272 276 284 292 292 296 300 304 308 312 320 324 328 332 
+\\
+336 344 348 352 356 360 368 372 376 380 384 388 396 400 
+\\
+404 408 412 420 424 428 432 436 444 444 444 448 452 456 
+\\
+460 464 468 472 476 476 480 484 488 492 496 500 504 508 
+\\
+508 512 516 520 524 528 532 536 540 540 544 548 552 556 
+\\
+560 564 568 572 572 576 580 584 588 592 596 600 604 604 
+\\
+608 612 616 620 624 628 632 636 636 640 644 648 652 656 
+\\
+660 664 668 672 672 672 676 680 680 684 688 692 692 696 
+\\
+700 704 704 708 712 716 716 720 724 724 728 732 736 736 
+\\
+740 744 748 748 752 756 760 760 764 768 768 772 776 780 
+\\
+780 784 788 792 792 796 800 804 804 808 812 812 816 820 
+\\
+824 824 828 832 836 836 840 844 848 848 852 856 860 860 
+\\
+860 864 864 868 872 872 876 880 880 884 884 888 892 892 
+\\
+896 900 900 904 908 908 912 912 916 920 920 924 928 928 
+\\
+932 936 936 940 940 944 948 948 952 956 956 960 964 964 
+\\
+968 968 972 976 976 980 984 984 988 992 992 996 996 1000 
+\\
+1004 1004 1008 1012 1012 1016 1020 1024
+\\
+\end{tabular}
+\\
+\Option{SEIToneMapNumPivots} &
+\Default{0} &
+Specifies the number of pivot points in mode 3.
+\\
+\Option{SEIToneMapCodedPivotValue} &
+\Default{\None} &
+Array of coded pivot point in mode 3.
+A suggested table is:
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+64 128 256 512 768
+\end{tabular}
+\\
+\Option{SEIToneMapTargetPivotValue} &
+\Default{\None} &
+Array of target pivot point in mode 3.
+A suggested table is:
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+48 73 111 168 215
+\end{tabular}
+\\
+\Option{SEIToneMap...} \Option{CameraIsoSpeedIdc} &
+\Default{0} &
+Indicates the camera ISO speed for daylight illumination.
+\\
+\Option{SEIToneMap...} \Option{CameraIsoSpeedValue} &
+\Default{400} &
+Specifies the camera ISO speed for daylight illumination of Extended_ISO.
+\\
+\Option{SEIToneMap...} \Option{ExposureIndexIdc} &
+\Default{0} &
+Indicates the exposure index setting of the camera.
+\\
+\Option{SEIToneMap...} \Option{ExposureIndexValue} &
+\Default{400} &
+Specifies the exposure index setting of the cameran of Extended_ISO.
+\\
+\Option{SEIToneMapExposure...} \Option{CompensationValueSignFlag} &
+\Default{0} &
+Specifies the sign of ExposureCompensationValue.
+\\
+\Option{SEIToneMapExposure...} \Option{CompensationValueNumerator} &
+\Default{0} &
+Specifies the numerator of ExposureCompensationValue.
+\\
+\Option{SEIToneMapExposure...} \Option{CompensationValueDenomIdc} &
+\Default{2} &
+Specifies the denominator of ExposureCompensationValue.
+\\
+\Option{SEIToneMapRef...} \Option{ScreenLuminanceWhite} &
+\Default{350} &
+Specifies reference screen brightness setting in units of candela per square metre.
+\\
+\Option{SEIToneMapExtended...} \Option{RangeWhiteLevel} &
+\Default{800} &
+Indicates the luminance dynamic range.
+\\
+\Option{SEIToneMapNominal...} \Option{BlackLevelLumaCodeValue} &
+\Default{16} &
+Specifies luma sample value of the nominal black level assigned decoded pictures.
+\\
+\Option{SEIToneMapNominal...} \Option{WhiteLevelLumaCodeValue} &
+\Default{235} &
+Specifies luma sample value of the nominal white level assigned decoded pictures.
+\\
+\Option{SEIToneMapExtended...} \Option{WhiteLevelLumaCodeValue} &
+\Default{300} &
+Specifies luma sample value of the extended dynamic range assigned decoded pictures.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Frame packing arrangement SEI message encoder parameters}{tab:sei-frame-packing-arrangement}
+\Option{SEIFramePacking} &
+\Default{0} &
+Enables or disables the insertion of the Frame packing arrangement SEI messages.
+\\
+\Option{SEIFramePackingType} &
+\Default{0} &
+Indicates the arrangement type in the Frame packing arrangement SEI message.
+This option has no effect if SEIFramePacking is disabled.
+\par
+\begin{tabular}{cp{0.35\textwidth}}
+  3 & Side by Side \\
+  4 & Top Bottom \\
+  5 & Frame Alternate \\
+\end{tabular}
+\\
+\Option{SEIFramePackingInterpretation} &
+\Default{0} &
+Indicates the constituent frames relationship in the Frame packing arrangement SEI message. 
+This option has no effect if SEIFramePacking is disabled.
+\par
+\begin{tabular}{cp{0.35\textwidth}}
+  0 & Unspecified \\
+  1 & Frame 0 is associated with the left view of a stereo pair \\
+  2 & Frame 0 is associated with the right view of a stereo pair \\
+\end{tabular}
+\\
+\Option{SEIFramePackingQuincunx} &
+\Default{0} &
+Enables or disables the quincunx_sampling signalling in the
+Frame packing arrangement SEI messages. This option has no
+effect if SEIFramePacking is disabled.
+\\
+\Option{SEIFramePackingId} &
+\Default{0} &
+Indicates the session number in the Frame packing arrangement
+SEI messages. This option has no effect if SEIFramePacking is
+disabled.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Display orientation SEI message encoder parameters}{tab:sei-display-orientation}
+\Option{SEIDisplayOrientation} &
+\Default{0} &
+Enables or disables the insertion of the Display orientation
+SEI messages.
+\par
+\begin{tabular}{cp{0.20\textwidth}}
+  0 & Disabled \\
+  N: $0 < N < (2^{16} - 1)$ & Enable display orientation SEI message with 
+  \mbox{anticlockwise_rotation = N} 
+  and \mbox{display_orientation_repetition_period = 1} \\
+\end{tabular}
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Structure of pictures information SEI message encoder parameters}{tab:sei-sop-info}
+\Option{SEISOPDescription} &
+\Default{0} &
+Enables or disables the insertion of the Structure of pictures information SEI messages.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Active parameter sets SEI message encoder parameters}{tab:sei-active-parameter-sets}
+\Option{SEIActiveParameterSets} &
+\Default{0} &
+Enables or disables the insertion of the Active parameter sets
+SEI messages.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Decoding unit information SEI message encoder parameters}{tab:sei-decoding-unit-info}
+\Option{SEIDecodingUnitInfo} &
+\Default{0} &
+Enables or disables the insertion of the Decoding unit information
+SEI messages. This option has no effect if VuiParametersPresent is disabled.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Temporal sub-layer zero index SEI message encoder parameters}{tab:sei-temporal-level-0}
+\Option{SEITemporalLevel0Index} &
+\Default{0} &
+Enables or disables the insertion of the Temporal level zero index
+SEI messages.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Decoded picture hash SEI message encoder parameters}{tab:sei-decoded-picture-hash}
 \Option{SEIDecodedPictureHash} &
-\ShortOption{\None} &
 \Default{0} &
 Enables or disables the calculation and insertion of the Decoded picture hash
 SEI messages.
 \par
-\begin{tabular}{cp{0.45\textwidth}}
+\begin{tabular}{cp{0.35\textwidth}}
   0 & Disabled \\
   1 & Transmits MD5 in SEI message and writes the value to the encoder
@@ -1531,288 +2214,254 @@
 \end{tabular}
 \\
-\Option{SEIpictureDigest} &
-\ShortOption{\None} &
-\Default{0} &
-Deprecated alias for SEIDecodedPictureHash.
-Do not use anymore.
-\\
-\Option{SEIRecoveryPoint} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Recovery point
-SEI messages.
-\\
-\Option{SEIActiveParameterSets} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Active parameter sets
-SEI messages.
-\\
-\Option{SEIBufferingPeriod} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Buffering period
-SEI messages. This option has no effect if VuiParametersPresent is disabled.
-SEIBufferingPeriod requires SEIActiveParameterSets to be enabled.
-\\
-\Option{SEIPictureTiming} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Picture timing
-SEI messages. This option has no effect if VuiParametersPresent is disabled.
-\\
-\Option{SEIDecodingUnitInfo} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Decoding unit information
-SEI messages. This option has no effect if VuiParametersPresent is disabled.
-\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Scalable nesting SEI message encoder parameters}{tab:sei-scalable-nesting}
+\Option{SEIScalableNesting} &
+\Default{0} &
+Enables or disables the use of the scalable nesting SEI messages.
+\\
+\end{OptionTableNoShorthand}
+
+
+        
+\begin{OptionTableNoShorthand}{Region refresh information SEI message encoder parameters}{tab:sei-region-refresh-info}
 \Option{SEIGradualDecodingRefreshInfo} &
-\ShortOption{\None} &
 \Default{0} &
 Enables or disables the insertion of the Gradual decoding refresh information
 SEI messages.
 \\
-\Option{SEITemporalLevel0Index} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Temporal level zero index
-SEI messages.
-\\
-\Option{SEIDisplayOrientation} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Display orientation
-SEI messages.
-\par
-\begin{tabular}{cp{0.30\textwidth}}
-  0 & Disabled \\
-  N: $0 < N < (2^{16} - 1)$ & Enable display orientation SEI message with 
-  \mbox{anticlockwise_rotation = N} 
-  and \mbox{display_orientation_repetition_period = 1} \\
-\end{tabular}
-\\
-\Option{SEIFramePacking} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Frame packing arrangement SEI messages.
-\\
-\Option{SEIFramePackingType} &
-\ShortOption{\None} &
-\Default{0} &
-Indicates the arrangement type in the Frame packing arrangement SEI message.
-This option has no effect if SEIFramePacking is disabled.
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{No display SEI message encoder parameters}{tab:sei-no-display}
+\Option{SEINoDisplay} &
+\Default{0} &
+When non-zero, generate no-display SEI message for temporal layer N or higher.
+\\
+\end{OptionTableNoShorthand}
+
+
+        
+\begin{OptionTableNoShorthand}{Time code SEI message encoder parameters}{tab:sei-time-code}
+\Option{SEITimeCodeEnabled} &
+\Default{false} &
+When true (non-zero), generate Time code SEI messages.
+\\
+\Option{SEITimeCodeNumClockTs} &
+\Default{0} &
+Number of clock time sets, in the range of 0 to 3 (inclusive).
+\\
+\Option{SEITimeCodeTimeStampFlag} &
+\Default{\None} &
+Time stamp flag associated to each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeFieldBasedFlag} &
+\Default{\None} &
+Field based flag associated to each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeCountingType} &
+\Default{\None} &
+Counting type associated to each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeFullTsFlag} &
+\Default{\None} &
+Full time stamp flag associated to each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeDiscontinuityFlag} &
+\Default{\None} &
+Discontinuity flag associated to each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeCntDroppedFlag} &
+\Default{\None} &
+Counter dropped flag associated to each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeNumFrames} &
+\Default{\None} &
+Number of frames associated to each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeSecondsFlag} &
+\Default{\None} &
+Flag to signal seconds value presence in each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeMinutesFlag} &
+\Default{\None} &
+Flag to signal minutes value presence in each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeHoursFlag} &
+\Default{\None} &
+Flag to signal hours value presence in each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeSecondsValue} &
+\Default{\None} &
+Seconds value for each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeMinutesValue} &
+\Default{\None} &
+Minutes value for each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeHoursValue} &
+\Default{\None} &
+Hours value for each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeOffsetLength} &
+\Default{\None} &
+Time offset length associated to each time set (comma or space separated list of entries).
+\\
+\Option{SEITimeCodeTimeOffset} &
+\Default{\None} &
+Time offset associated to each time set (comma or space separated list of entries).
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Mastering display colour volume SEI message encoder parameters}{tab:sei-mastering-display-colour-volume}
+\Option{SEIMasteringDisplayColourVolume} &
+\Default{false} &
+When true (non-zero), generate Mastering display colour volume SEI message.
+\\
+\Option{SEIMasteringDisplayMaxLuminance} &
+\Default{10000} &
+Specifies the mastering display maximum luminance value in units of 1/10000 candela per square metre.
+\\
+\Option{SEIMasteringDisplayMinLuminance} &
+\Default{0} &
+Specifies the mastering display minimum luminance value in units of 1/10000 candela per square metre.
+\\
+\Option{SEIMasteringDisplayPrimaries} &
+\Default{0,50000, 0,0, 50000,0} &
+Mastering display primaries for all three colour planes in CIE xy coordinates in increments of 1/50000 (results in the ranges 0 to 50000 inclusive).
+\\
+\Option{SEIMasteringDisplayWhitePoint} &
+\Default{16667, 16667} &
+Mastering display white point CIE xy coordinates in normalized increments of 1/50000 (e.g. 0.333 = 16667).
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Segmented rectangular frame packing arrangement SEI message encoder parameters}{tab:sei-seg-rect-fpa}
+\Option{SEISegmentedRectFramePacking} &
+\Default{0} &
+Controls generation of segmented rectangular frame packing SEI messages.
+\\
+\Option{SEISegmentedRectFramePackingCancel} &
+\Default{false} &
+If true, cancels the persistence of any previous SRFPA SEI message.
+\\
+\Option{SEISegmentedRectFramePackingType} &
+\Default{0} &
+Specifies the arrangement of the frames in the reconstructed picture.
+\\
+\Option{SEISegmentedRectFramePackingPersistence} &
+\Default{false} &
+If false the SEI applies to the current frame only.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Temporal motion-constrained tile sets SEI message encoder parameters}{tab:sei-tmcts}
+\Option{SEITempMotionConstrainedTileSets} &
+\Default{false} &
+When true (non-zero), generates example temporal motion constrained tile sets SEI messages.
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Chroma resampling filter hint SEI message encoder parameters}{tab:chroma-resampling-filter-hint}
+\Option{SEIChromaSamplingFilterHint} &
+\Default{false} &
+When true (non-zero), generates example chroma sampling filter hint SEI messages.
+\\
+\Option{SEIChromaSamplingHorizontalFilterType} &
+\Default{2} &
+Defines the index of the chroma sampling horizontal filter:
+\par
+\begin{tabular}{cp{0.35\textwidth}}
+  0 & Unspecified \\
+  1 & Filters signalled within the SEI message \\
+  2 & Filters as described by SMPTE RP 2050-1:2012\\
+\end{tabular}
+\\
+\Option{SEIChromaSamplingVerticalFilterType} &
+\Default{2} &
+Defines the index of the chroma sampling vertical filter:
+\par
+\begin{tabular}{cp{0.35\textwidth}}
+  0 & Unspecified \\
+  1 & Filters signalled within the SEI message \\
+  2 & Filters as described in the 5/3 filter description of ITU-T Rec. T.800 | ISO/IEC 15444-1\\
+\end{tabular}
+\\
+\end{OptionTableNoShorthand}
+
+
+
+\begin{OptionTableNoShorthand}{Knee function SEI message encoder parameters}{tab:sei-knee-function}
+\Option{SEIKneeFunctionInfo} &
+\Default{false} &
+Enables (true) or disables (false) the insertion of the Knee function SEI messages.
+\\
+\Option{SEIKneeFunctionId} &
+\Default{0} &
+Specifies Id of Knee function SEI message for a given session.
+\\
+\Option{SEIKneeFunctionCancelFlag} &
+\Default{false} &
+Indicates that Knee function SEI message cancels the persistance (true) or follows (false).
+\\
+\Option{SEIKneeFunctionPersistenceFlag} &
+\Default{true} &
+Specifies the persistence of the Knee function SEI message.
+\\
+\Option{SEIKneeFunctionInputDrange} &
+\Default{1000} &
+Specifies the peak luminance level for the input picture of Knee function SEI messages.
+\\
+\Option{SEIKneeFunctionInputDispLuminance} &
+\Default{100} &
+Specifies the expected display brightness for the input picture of Knee function SEI messages.
+\\
+\Option{SEIKneeFunctionOutputDrange} &
+\Default{4000} &
+Specifies the peak luminance level for the output picture of Knee function SEI messages.
+\\
+\Option{SEIKneeFunctionOutputDispLuminance} &
+\Default{800} &
+Specifies the expected display brightness for the output picture of Knee function SEI messages.
+\\
+\Option{SEIKneeFunctionNumKneePointsMinus1} &
+\Default{2} &
+Specifies the number of knee points - 1.
+\\
+\Option{SEIKneeFunctionInputKneePointValue} &
+\Default{} &
+Array of input knee point. Default table can be set to the following:
 \par
 \begin{tabular}{cp{0.45\textwidth}}
-  3 & Side by Side \\
-  4 & Top Bottom \\
-  5 & Frame Alternate \\
-\end{tabular}
-\\
-\Option{SEIFramePackingInterpretation} &
-\ShortOption{\None} &
-\Default{0} &
-Indicates the constituent frames relationship in the Frame packing arrangement SEI message. 
-This option has no effect if SEIFramePacking is disabled.
+600 800 900
+\end{tabular}
+\\
+\Option{SEIKneeFunctionOutputKneePointValue} &
+\Default{} &
+Array of output knee point. Default table can be set to the following:
 \par
 \begin{tabular}{cp{0.45\textwidth}}
-  0 & Unspecified \\
-  1 & Frame 0 is associated with the left view of a stereo pair \\
-  2 & Frame 0 is associated with the right view of a stereo pair \\
-\end{tabular}
-\\
-\Option{SEIFramePackingQuincunx} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the quincunx_sampling signalling in the
-Frame packing arrangement SEI messages. This option has no
-effect if SEIFramePacking is disabled.
-\\
-\Option{SEIFramePackingId} &
-\ShortOption{\None} &
-\Default{0} &
-Indicates the session number in the Frame packing arrangement
-SEI messages. This option has no effect if SEIFramePacking is
-disabled.
-\\
-\Option{SEIToneMappingInfo} &
-\ShortOption{\None} &
-\Default{0} &
-Enables or disables the insertion of the Tone Mapping SEI message.
-\\
-\Option{SEIToneMapId} &
-\ShortOption{\None} &
-\Default{0} &
-Specifies Id of Tone Mapping SEI message for a given session.
-\\
-\Option{SEIToneMapCancelFlag} &
-\ShortOption{\None} &
-\Default{0} &
-Indicates that Tone Mapping SEI message cancels the persistance or follows.
-\\
-\Option{SEIToneMapPersistenceFlag} &
-\ShortOption{\None} &
-\Default{1} &
-Specifies the persistence of the Tone Mapping SEI message.
-\\
-\Option{SEIToneMapCodedDataBitDepth} &
-\ShortOption{\None} &
-\Default{10} &
-Specifies Coded Data BitDepth of Tone Mapping SEI messages.
-\\
-\Option{SEIToneMapTargetBitDepth} &
-\ShortOption{\None} &
-\Default{8} &
-Specifies Output BitDepth of Tome mapping function.
-\\
-\Option{SEIToneMapModelId} &
-\ShortOption{\None} &
-\Default{0} &
-Specifies Model utilized for mapping coded data into 
-target_bit_depth range.
-\par
-\begin{tabular}{cp{0.45\textwidth}}
-  0 & linear mapping with clipping \\
-  1 & sigmoidal mapping \\
-  2 & user-defined table mapping \\
-  3 & piece-wise linear mapping \\
-  4 & luminance dynamic range mapping \\
-\end{tabular}
-\\
-\Option{SEIToneMapMinValue} &
-\ShortOption{\None} &
-\Default{0} &
-Specifies the minimum value in mode 0.
-\\
-\Option{SEIToneMapMaxValue} &
-\ShortOption{\None} &
-\Default{1023} &
-Specifies the maxmum value in mode 0.
-\\
-\Option{SEIToneMapSigmoidMidpoint} &
-\ShortOption{\None} &
-\Default{512} &
-Specifies the centre point in mode 1.
-\\
-\Option{SEIToneMapSigmoidWidth} &
-\ShortOption{\None} &
-\Default{960} &
-Specifies the distance between 5% and 95% values of 
-the target_bit_depth in mode 1.
-\\
-\Option{SEIToneMapStartOfCodedInterval} &
-\ShortOption{\None} &
-\Default{\None} &
-Array of user-defined mapping table. 
-Default table can be set to the following:
-\par
-\begin{tabular}{cp{0.45\textwidth}}
-0 12 24 36 48 60 72 84 96 108 120 132 144 156 168 180 
-192 192 196 204 208 216 220 228 232 240 248 252 260 264 
-272 276 284 292 292 296 300 304 308 312 320 324 328 332 
-336 344 348 352 356 360 368 372 376 380 384 388 396 400 
-404 408 412 420 424 428 432 436 444 444 444 448 452 456 
-460 464 468 472 476 476 480 484 488 492 496 500 504 508 
-508 512 516 520 524 528 532 536 540 540 544 548 552 556 
-560 564 568 572 572 576 580 584 588 592 596 600 604 604 
-608 612 616 620 624 628 632 636 636 640 644 648 652 656 
-660 664 668 672 672 672 676 680 680 684 688 692 692 696 
-700 704 704 708 712 716 716 720 724 724 728 732 736 736 
-740 744 748 748 752 756 760 760 764 768 768 772 776 780 
-780 784 788 792 792 796 800 804 804 808 812 812 816 820 
-824 824 828 832 836 836 840 844 848 848 852 856 860 860 
-860 864 864 868 872 872 876 880 880 884 884 888 892 892 
-896 900 900 904 908 908 912 912 916 920 920 924 928 928 
-932 936 936 940 940 944 948 948 952 956 956 960 964 964 
-968 968 972 976 976 980 984 984 988 992 992 996 996 1000 
-1004 1004 1008 1012 1012 1016 1020 1024
-\end{tabular}
-\\
-\Option{SEIToneMapNumPivots} &
-\ShortOption{\None} &
-\Default{5} &
-Specifies the number of pivot points in mode 3.
-\\
-\Option{SEIToneMapCodedPivotValue} &
-\ShortOption{\None} &
-\Default{\None} &
-Array of coded pivot point in mode 3.
-Default table can be set to the following:
-\par
-\begin{tabular}{cp{0.45\textwidth}}
-64 128 256 512 768
-\end{tabular}
-\\
-\Option{SEIToneMapTargetPivotValue} &
-\ShortOption{\None} &
-\Default{\None} &
-Array of target pivot point in mode 3.
-Default table can be set to the following:
-\par
-\begin{tabular}{cp{0.45\textwidth}}
-48 73 111 168 215
-\end{tabular}
-\\
-\Option{SEIToneMapCameraIsoSpeedIdc} &
-\ShortOption{\None} &
-\Default{0} &
-Indicates the camera ISO speed for daylight illumination.
-\\
-\Option{SEIToneMapCameraIsoSpeedValue} &
-\ShortOption{\None} &
-\Default{400} &
-Specifies the camera ISO speed for daylight illumination of Extended_ISO.
-\\
-\Option{SEIToneMapExposureIndexIdc} &
-\ShortOption{\None} &
-\Default{0} &
-Indicates the exposure index setting of the camera.
-\\
-\Option{SEIToneMapExposureIndexValue} &
-\ShortOption{\None} &
-\Default{400} &
-Specifies the exposure index setting of the cameran of Extended_ISO.
-\\
-\Option{SEIToneMapExposureCompensationValueSignFlag} &
-\ShortOption{\None} &
-\Default{0} &
-Specifies the sign of ExposureCompensationValue.
-\\
-\Option{SEIToneMapExposureCompensationValueNumerator} &
-\ShortOption{\None} &
-\Default{0} &
-Specifies the numerator of ExposureCompensationValue.
-\\
-\Option{SEIToneMapExposureCompensationValueDenomIdc} &
-\ShortOption{\None} &
-\Default{2} &
-Specifies the denominator of ExposureCompensationValue.
-\\
-\Option{SEIToneMapRefScreenLuminanceWhite} &
-\ShortOption{\None} &
-\Default{350} &
-Specifies reference screen brightness setting in units of candela per square metre.
-\\
-\Option{SEIToneMapExtendedRangeWhiteLevel} &
-\ShortOption{\None} &
-\Default{800} &
-Indicates the luminance dynamic range.
-\\
-\Option{SEIToneMapNominalBlackLevelLumaCodeValue} &
-\ShortOption{\None} &
-\Default{16} &
-Specifies luma sample value of the nominal black level assigned decoded pictures.
-\\
-\Option{SEIToneMapNominalWhiteLevelLumaCodeValue} &
-\ShortOption{\None} &
-\Default{235} &
-Specifies luma sample value of the nominal white level assigned decoded pictures.
-\\
-\Option{SEIToneMapExtendedWhiteLevelLumaCodeValue} &
-\ShortOption{\None} &
-\Default{300} &
-Specifies luma sample value of the extended dynamic range assigned decoded pictures.
-\\
-\end{OptionTable}
+100 250 450
+\end{tabular}
+\\
+\end{OptionTableNoShorthand}
+
+
+
+%\Option{SEITimeCode} &
+%\Default{false} &
+%When true, generate time code SEI messages.
+%\\
 
 %%
@@ -1912,4 +2561,5 @@
 \url{source/Lib/TLibCommon/TypeDef.h}.
 
+
 %%
 %%
@@ -1917,29 +2567,49 @@
 \clearpage
 \section{Using the decoder}
+\subsection{General}
 \begin{verbatim}
 TAppDecoder -b str.bin -o dec.yuv [options]
 \end{verbatim}
 
-\begin{OptionTable}{Decoder options}
-\Option{} &
-\ShortOption{-h} &
+\begin{OptionTableNoShorthand}{Decoder options}{tab:decoder-options}
+\Option{(--help)} &
+%\ShortOption{\None} &
 \Default{\None} &
 Prints usage information.
 \\
 
-\Option{} &
-\ShortOption{-o} &
+\Option{BitStreamFile (-b)} &
+%\ShortOption{-b} &
 \Default{\NotSet} &
-Defines reconstructed YUV file name.
-\\
-
-\Option{} &
-\ShortOption{-s} &
+Defines the input bit stream file name.
+\\
+
+\Option{ReconFile (-o)} &
+%\ShortOption{-o} &
+\Default{\NotSet} &
+Defines reconstructed YUV file name. If empty, no file is generated.
+\\
+
+\Option{SkipFrames (-s)} &
+%\ShortOption{-s} &
 \Default{0} &
 Defines the number of pictures in decoding order to skip.
 \\
 
-\Option{OutputBitDepth} &
-\ShortOption{-d} &
+\Option{MaxTemporalLayer (-t)} &
+%\ShortOption{-t} &
+\Default{-1} &
+Defines the maximum temporal layer to be decoded. If -1, then all layers are decoded.
+\\
+
+\Option{TarDecLayerIdSetFile (-l)} &
+%\ShortOption{-t} &
+\Default{\NotSet} &
+Specifies the targetDecLayerIdSet file name. The file would contain white-space separated LayerId values of the layers that are to be decoded.
+Omitting the parameter, or using a value of -1 in the file decodes all layers.
+\\
+
+\Option{OutputBitDepth (-d)} &
+%\ShortOption{-d} &
 \Default{0 \\ (Native)} &
 Specifies the luma bit-depth of the reconstructed YUV file (the value 0 indicates
@@ -1948,5 +2618,5 @@
 
 \Option{OutputBitDepthC} &
-\ShortOption{\None} &
+%\ShortOption{\None} &
 \Default{0 \\ (Native)} &
 Defines the chroma bit-depth of the reconstructed YUV file (the value 0 indicates
@@ -1954,6 +2624,6 @@
 \\
 
-\Option{SEIPictureDigest} &
-\ShortOption{\None} &
+\Option{SEIDecodedPictureHash} &
+%\ShortOption{\None} &
 \Default{1} &
 Enable or disable verification of any Picture hash SEI messages. When
@@ -1963,5 +2633,5 @@
 \begin{itemize}
 \item
-  If Picture hash SEI messages are included in the bitstream, the same type
+  If Picture hash SEI messages are included in the bit stream, the same type
   of hash is calculated for each decoded picture and written to the
   log together with an indication whether the calculted value matches
@@ -1985,6 +2655,12 @@
 \\
 
-\Option{RespectDefDispWindow} &
-\ShortOption{-w} &
+\Option{OutputDecodedSEIMessagesFilename} &
+%\ShortOption{\None} &
+\Default{\NotSet} &
+When a non-empty file name is specified, information regarding any decoded SEI messages will be output to the indicated file. If the file name is '-', then stdout is used instead.
+\\
+
+\Option{RespectDefDispWindow (-w)} &
+%\ShortOption{-w} &
 \Default{0} &
 Video region to be output by the decoder.
@@ -1996,5 +2672,27 @@
 \\
 
-\end{OptionTable}
+\Option{OutputColourSpaceConvert} &
+\Default{\NotSet} &
+Specifies the colour space conversion to apply to 444 video. Permitted values are:
+\par
+\begin{tabular}{lp{0.45\textwidth}}
+  UNCHANGED   & No colour space conversion is applied \\
+  YCrCbToYCbCr & Swap the second and third components \\
+  GBRtoRGB     & Reorder the three components \\
+\end{tabular}
+If no value is specified, no colour space conversion is applied. The list may eventually also include RGB to YCbCr or YCgCo conversions.\\
+\\
+
+\Option{SEINoDisplay} &
+\Default{false} &
+When true, do not output frames for which there is an SEI NoDisplay message.
+\\
+
+\end{OptionTableNoShorthand}
+
+
+\subsection{Using the decoder analyser}
+If the decoder is compiled with the macro RExt__DECODER_DEBUG_BIT_STATISTICS defined as 1 (either externally, or by editing TypeDef.h), the decoder will gather fractional bit counts associated with the different syntax elements, producing a table of the number of bits per syntax element, and where appropriate, according to block size and colour component/channel.
+The Linux makefile will compile both the analyser and standard version when the `all' or `everything' target is used (where the latter will also build  high-bit-depth executables).
 
 
Index: branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -41,10 +41,10 @@
 #include "TAppDecCfg.h"
 #include "TAppCommon/program_options_lite.h"
-
-#if H_MV
-#include <cassert>
-#endif
+#include "TLibCommon/TComChromaFormat.h"
 #ifdef WIN32
 #define strdup _strdup
+#endif
+#if NH_MV
+#include <cassert>
 #endif
 
@@ -68,36 +68,50 @@
   string cfg_ReconFile;
   string cfg_TargetDecLayerIdSetFile;
-#if H_3D
+#if NH_3D
   string cfg_ScaleOffsetFile;
 #endif
+  string outputColourSpaceConvert;
+  Int warnUnknowParameter = 0;
 
   po::Options opts;
   opts.addOptions()
-  ("help", do_help, false, "this help text")
-  ("BitstreamFile,b", cfg_BitstreamFile, string(""), "bitstream input file name")
-  ("ReconFile,o",     cfg_ReconFile,     string(""), "reconstructed YUV output file name\n"
-                                                     "YUV writing is skipped if omitted")
-#if H_3D
-  ("ScaleOffsetFile,p", cfg_ScaleOffsetFile, string(""), "file with coded scales and offsets")
-#endif
-  ("SkipFrames,s", m_iSkipFrame, 0, "number of frames to skip before random access")
-  ("OutputBitDepth,d", m_outputBitDepthY, 0, "bit depth of YUV output luma component (default: use 0 for native depth)")
-  ("OutputBitDepthC,d", m_outputBitDepthC, 0, "bit depth of YUV output chroma component (default: use 0 for native depth)")
-#if H_MV
-  ("TargetOptLayerSetIdx,x", m_targetOptLayerSetIdx, -1, "Target output layer set index. (default: -1, determine automatically to be equal to highest layer set index") // Should actually equal to 0 as default. However, this would cause only the base layer to be decoded.  
-#endif
-  ("MaxTemporalLayer,t", m_iMaxTemporalLayer, -1, "Maximum Temporal Layer to be decoded. -1 to decode all layers")
-  ("SEIDecodedPictureHash", m_decodedPictureHashSEIEnabled, 1, "Control handling of decoded picture hash SEI messages\n"
-                                              "\t1: check hash in SEI messages if available in the bitstream\n"
-                                              "\t0: ignore SEI message")
-  ("SEIpictureDigest", m_decodedPictureHashSEIEnabled, 1, "deprecated alias for SEIDecodedPictureHash")
-  ("TarDecLayerIdSetFile,l", cfg_TargetDecLayerIdSetFile, string(""), "targetDecLayerIdSet file name. The file should include white space separated LayerId values to be decoded. Omitting the option or a value of -1 in the file decodes all layers.")
-  ("RespectDefDispWindow,w", m_respectDefDispWindow, 0, "Only output content inside the default display window\n")
-#if H_MV
-  ("OutputVpsInfo,v", m_outputVpsInfo, false, "Output information about the layer dependencies and layer sets")
-#endif
+
+
+  ("help",                      do_help,                               false,      "this help text")
+  ("BitstreamFile,b",           cfg_BitstreamFile,                     string(""), "bitstream input file name")
+  ("ReconFile,o",               cfg_ReconFile,                         string(""), "reconstructed YUV output file name\n"
+                                                                                   "YUV writing is skipped if omitted")
+#if NH_3D
+  ("ScaleOffsetFile,p",         cfg_ScaleOffsetFile,                   string(""), "file with coded scales and offsets")
+  ("Depth420OutputFlag",        m_depth420OutputFlag,                  true      , "Output depth layers in 4:2:0 ") 
+#endif
+  ("WarnUnknowParameter,w",     warnUnknowParameter,                                  0, "warn for unknown configuration parameters instead of failing")
+  ("SkipFrames,s",              m_iSkipFrame,                          0,          "number of frames to skip before random access")
+  ("OutputBitDepth,d",          m_outputBitDepth[CHANNEL_TYPE_LUMA],   0,          "bit depth of YUV output luma component (default: use 0 for native depth)")
+  ("OutputBitDepthC,d",         m_outputBitDepth[CHANNEL_TYPE_CHROMA], 0,          "bit depth of YUV output chroma component (default: use 0 for native depth)")
+  ("OutputColourSpaceConvert",  outputColourSpaceConvert,              string(""), "Colour space conversion to apply to input 444 video. Permitted values are (empty string=UNCHANGED) " + getListOfColourSpaceConverts(false))
+#if NH_MV
+  ("TargetOptLayerSetIdx,x",    m_targetOptLayerSetIdx,                -1,         "Target output layer set index. (default: -1, determine automatically to be equal to highest layer set index") // Should actually equal to 0 as default. However, this would cause only the base layer to be decoded.  
+#endif
+  ("MaxTemporalLayer,t",        m_iMaxTemporalLayer,                   -1,         "Maximum Temporal Layer to be decoded. -1 to decode all layers")
+  ("SEIDecodedPictureHash",     m_decodedPictureHashSEIEnabled,        1,          "Control handling of decoded picture hash SEI messages\n"
+                                                                                   "\t1: check hash in SEI messages if available in the bitstream\n"
+                                                                                   "\t0: ignore SEI message")
+  ("SEINoDisplay",              m_decodedNoDisplaySEIEnabled,          true,       "Control handling of decoded no display SEI messages")
+  ("TarDecLayerIdSetFile,l",    cfg_TargetDecLayerIdSetFile,           string(""), "targetDecLayerIdSet file name. The file should include white space separated LayerId values to be decoded. Omitting the option or a value of -1 in the file decodes all layers.")
+  ("RespectDefDispWindow,w",    m_respectDefDispWindow,                0,          "Only output content inside the default display window\n")
+#if NH_MV
+  ("OutputVpsInfo,v",           m_outputVpsInfo,                       false,       "Output information about the layer dependencies and layer sets")
+#endif
+#if O0043_BEST_EFFORT_DECODING
+  ("ForceDecodeBitDepth",       m_forceDecodeBitDepth,                 0U,         "Force the decoder to operate at a particular bit-depth (best effort decoding)")
+#endif
+  ("OutputDecodedSEIMessagesFilename",  m_outputDecodedSEIMessagesFilename,    string(""), "When non empty, output decoded SEI messages to the indicated file. If file is '-', then output to stdout\n")
+  ("ClipOutputVideoToRec709Range",      m_bClipOutputVideoToRec709Range,  false, "If true then clip output video to the Rec. 709 Range on saving")
   ;
+
   po::setDefaults(opts);
-  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
+  po::ErrorReporter err;
+  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv, err);
 
   for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
@@ -109,4 +123,20 @@
   {
     po::doHelp(cout, opts);
+    return false;
+  }
+
+  if (err.is_errored)
+  {
+    if (!warnUnknowParameter)
+    {
+      /* errors have already been reported to stderr */
+      return false;
+    }
+  }
+
+  m_outputColourSpaceConvert = stringToInputColourSpaceConvert(outputColourSpaceConvert, false);
+  if (m_outputColourSpaceConvert>=NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS)
+  {
+    fprintf(stderr, "Bad output colour space conversion string\n");
     return false;
   }
@@ -116,10 +146,11 @@
   m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
 
-#if H_3D
+#if NH_3D
   m_pchScaleOffsetFile = cfg_ScaleOffsetFile.empty() ? NULL : strdup(cfg_ScaleOffsetFile.c_str());
 #endif
+
   if (!m_pchBitstreamFile)
   {
-    fprintf(stderr, "No input file specifed, aborting\n");
+    fprintf(stderr, "No input file specified, aborting\n");
     return false;
   }
@@ -127,5 +158,5 @@
   if ( !cfg_TargetDecLayerIdSetFile.empty() )
   {
-#if H_MV
+#if NH_MV
     m_targetDecLayerIdSetFileEmpty = false;     
 #endif
@@ -152,5 +183,5 @@
         if ( layerIdParsed < 0 || layerIdParsed >= MAX_NUM_LAYER_IDS )
         {
-          fprintf(stderr, "Warning! Parsed LayerId %d is not withing allowed range [0,%d]. Ignoring this value.\n", layerIdParsed, MAX_NUM_LAYER_IDS-1 );
+          fprintf(stderr, "Warning! Parsed LayerId %d is not within allowed range [0,%d]. Ignoring this value.\n", layerIdParsed, MAX_NUM_LAYER_IDS-1 );
         }
         else
@@ -172,12 +203,12 @@
     }
   }
-#if H_MV
-  m_targetDecLayerIdSet.push_back( 0 );         // Only base layer at startup
-#endif
-
+
+#if NH_MV
+  //m_targetDecLayerIdSet.push_back( 0 );         // Only base layer at startup
+#endif
   return true;
 }
 
-#if H_MV
+#if NH_MV
 Void TAppDecCfg::xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName)
 {
Index: branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecCfg.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecCfg.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,4 +45,5 @@
 #include "TLibCommon/CommonDef.h"
 #include <vector>
+
 //! \ingroup TAppDecoder
 //! \{
@@ -56,31 +57,38 @@
 {
 protected:
-  Char*         m_pchBitstreamFile;                   ///< input bitstream file name
-#if H_MV
-  Int           m_targetOptLayerSetIdx;               ///< target output layer set index
-  Int           m_maxLayerId;                         ///< maximum nuh_layer_id decoded
-  std::vector<Char*> m_pchReconFiles;                 ///< array of output reconstruction file name create from output reconstruction file name
+  Char*         m_pchBitstreamFile;                     ///< input bitstream file name
+#if NH_MV
+  Int           m_targetOptLayerSetIdx;                 ///< target output layer set index
+  Int           m_maxLayerId;                           ///< maximum nuh_layer_id decoded
+  std::vector<Char*> m_pchReconFiles;                   ///< array of output reconstruction file name create from output reconstruction file name
 #endif
-  Char*         m_pchReconFile;                       ///< output reconstruction file name
-#if H_3D
-  Char*         m_pchScaleOffsetFile;                 ///< output coded scale and offset parameters
+  Char*         m_pchReconFile;                         ///< output reconstruction file name
+#if NH_3D
+  Char*         m_pchScaleOffsetFile;                   ///< output coded scale and offset parameters
+  Bool          m_depth420OutputFlag;                   ///< output depth layers in 4:2:0
 #endif
-  Int           m_iSkipFrame;                         ///< counter for frames prior to the random access point to skip
-  Int           m_outputBitDepthY;                    ///< bit depth used for writing output (luma)
-  Int           m_outputBitDepthC;                    ///< bit depth used for writing output (chroma)t
+  Int           m_iSkipFrame;                           ///< counter for frames prior to the random access point to skip
+  Int           m_outputBitDepth[MAX_NUM_CHANNEL_TYPE]; ///< bit depth used for writing output
+  InputColourSpaceConversion m_outputColourSpaceConvert;
 
   Int           m_iMaxTemporalLayer;                  ///< maximum temporal layer to be decoded
   Int           m_decodedPictureHashSEIEnabled;       ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+  Bool          m_decodedNoDisplaySEIEnabled;         ///< Enable(true)/disable(false) writing only pictures that get displayed based on the no display SEI message
+  std::vector<Int> m_targetDecLayerIdSet;             ///< set of LayerIds to be included in the sub-bitstream extraction process.
+#if NH_MV
+  Bool          m_targetDecLayerIdSetFileEmpty;       ///< indication if target layers are given by file
+#endif
 
-  std::vector<Int> m_targetDecLayerIdSet;             ///< set of LayerIds to be included in the sub-bitstream extraction process.
-#if H_MV
-  Bool          m_targetDecLayerIdSetFileEmpty;      ///< indication if target layers are given by file
+  Int           m_respectDefDispWindow;               ///< Only output content inside the default display window
+#if O0043_BEST_EFFORT_DECODING
+  UInt          m_forceDecodeBitDepth;                ///< if non-zero, force the bit depth at the decoder (best effort decoding)
 #endif
-  Int           m_respectDefDispWindow;               ///< Only output content inside the default display window 
-
-#if H_MV
+  std::string   m_outputDecodedSEIMessagesFilename;   ///< filename to output decoded SEI messages to. If '-', then use stdout. If empty, do not output details.
+  Bool          m_bClipOutputVideoToRec709Range;      ///< If true, clip the output video to the Rec 709 range on saving.
+#if NH_MV
   Bool          m_outputVpsInfo;                     ///< Output VPS information 
   Void xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName); ///< create filenames
 #endif
+
 public:
   TAppDecCfg()
@@ -88,15 +96,24 @@
   , m_pchReconFile(NULL)
   , m_iSkipFrame(0)
-  , m_outputBitDepthY(0)
-  , m_outputBitDepthC(0)
+  , m_outputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
   , m_iMaxTemporalLayer(-1)
   , m_decodedPictureHashSEIEnabled(0)
-#if H_MV
+  , m_decodedNoDisplaySEIEnabled(false)
+#if NH_MV
   , m_targetDecLayerIdSetFileEmpty(true)
 #endif
   , m_respectDefDispWindow(0)
-  {}
+#if O0043_BEST_EFFORT_DECODING
+  , m_forceDecodeBitDepth(0)
+#endif
+  {
+    for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+    {
+      m_outputBitDepth[channelTypeIndex] = 0;
+    }
+  }
+
   virtual ~TAppDecCfg() {}
-  
+
   Bool  parseCfg        ( Int argc, Char* argv[] );   ///< initialize option class from configuration
 };
Index: branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,4 +45,7 @@
 #include "TLibDecoder/AnnexBread.h"
 #include "TLibDecoder/NALread.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
 
 //! \ingroup TAppDecoder
@@ -54,5 +57,5 @@
 
 TAppDecTop::TAppDecTop()
-#if !H_MV
+#if !NH_MV
 : m_iPOCLastDisplay(-MAX_INT)
 #else
@@ -60,5 +63,5 @@
 #endif
 {
-#if H_MV
+#if NH_MV
   for (Int i = 0; i < MAX_NUM_LAYER_IDS; i++) 
   {
@@ -67,9 +70,9 @@
   }
 #endif
-#if H_3D
+#if NH_3D
     m_pScaleOffsetFile  = 0;
 #endif
 
-#if H_MV
+#if NH_MV
     m_markedForOutput = false; 
 #endif
@@ -83,4 +86,9 @@
 Void TAppDecTop::destroy()
 {
+#if NH_MV
+  // destroy internal classes
+  xDestroyDecLib();
+#endif
+
   if (m_pchBitstreamFile)
   {
@@ -88,5 +96,5 @@
     m_pchBitstreamFile = NULL;
   }
-#if H_MV
+#if NH_MV
   for (Int decIdx = 0; decIdx < m_numDecoders; decIdx++)
   {
@@ -103,5 +111,5 @@
     m_pchReconFile = NULL;
   }
-#if H_3D
+#if NH_3D
   if (m_pchScaleOffsetFile)
   {
@@ -127,5 +135,5 @@
 {
   Int                 poc;
-#if H_MV
+#if NH_MV
   poc = -1; 
 #endif
@@ -138,6 +146,5 @@
     exit(EXIT_FAILURE);
   }
-
-#if H_3D
+#if NH_3D
   if( m_pchScaleOffsetFile ) 
   { 
@@ -146,10 +153,21 @@
   }
 #endif
+
   InputByteStream bytestream(bitstreamFile);
+
+  if (!m_outputDecodedSEIMessagesFilename.empty() && m_outputDecodedSEIMessagesFilename!="-")
+  {
+    m_seiMessageFileStream.open(m_outputDecodedSEIMessagesFilename.c_str(), std::ios::out);
+    if (!m_seiMessageFileStream.is_open() || !m_seiMessageFileStream.good())
+    {
+      fprintf(stderr, "\nUnable to open file `%s' for writing decoded SEI messages\n", m_outputDecodedSEIMessagesFilename.c_str());
+      exit(EXIT_FAILURE);
+    }
+  }
 
   // create & initialize internal classes
   xCreateDecLib();
   xInitDecLib  ();
-#if !H_MV
+#if !NH_MV
   m_iPOCLastDisplay += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
 
@@ -169,5 +187,5 @@
   Bool firstSlice        = true; 
 #endif
-  Bool loopFiltered      = false;
+  Bool loopFiltered = false;
 
   while (!!bitstreamFile)
@@ -177,6 +195,11 @@
      * requires the TDecTop::decode() method to be called again with the same
      * nal unit. */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::TComCodingStatisticsData backupStats(TComCodingStatistics::GetStatistics());
+    streampos location = bitstreamFile.tellg() - streampos(bytestream.GetNumBufferedBytes());
+#else
     streampos location = bitstreamFile.tellg();
-#if H_MV
+#endif
+#if NH_MV
 #if ENC_DEC_TRACE
     Int64 symCount = g_nSymbolCounter;
@@ -184,11 +207,11 @@
 #endif
     AnnexBStats stats = AnnexBStats();
-    vector<uint8_t> nalUnit;
+
     InputNALUnit nalu;
-    byteStreamNALUnit(bytestream, nalUnit, stats);
+    byteStreamNALUnit(bytestream, nalu.getBitstream().getFifo(), stats);
 
     // call actual decoding function
     Bool bNewPicture = false;
-#if H_MV
+#if NH_MV
     Bool newSliceDiffPoc   = false;
     Bool newSliceDiffLayer = false;
@@ -196,5 +219,5 @@
     Bool allLayersDecoded  = false;     
 #endif
-    if (nalUnit.empty())
+    if (nalu.getBitstream().getFifo().empty())
     {
       /* this can happen if the following occur:
@@ -207,12 +230,11 @@
     else
     {
-      read(nalu, nalUnit);
-#if H_MV      
+      read(nalu);
+#if NH_MV      
       if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) 
           || !isNaluWithinTargetDecLayerIdSet(&nalu)
-          || nalu.m_layerId > MAX_NUM_LAYER_IDS-1
-          || (nalu.m_nalUnitType == NAL_UNIT_VPS && nalu.m_layerId > 0)           
-          || (nalu.m_nalUnitType == NAL_UNIT_EOB && nalu.m_layerId > 0)    
-          || (nalu.m_nalUnitType == NAL_UNIT_EOS && nalu.m_layerId > 0)    
+          || nalu.m_nuhLayerId > MAX_NUM_LAYER_IDS-1
+          || (nalu.m_nalUnitType == NAL_UNIT_VPS && nalu.m_nuhLayerId > 0)           
+          || (nalu.m_nalUnitType == NAL_UNIT_EOB && nalu.m_nuhLayerId > 0)              
          ) 
       {
@@ -225,6 +247,6 @@
       else
       { 
-        Int decIdx     = xGetDecoderIdx( nalu.m_layerId , true );      
-        newSliceDiffLayer = nalu.isSlice() && ( nalu.m_layerId != layerIdCurrPic ) && !firstSlice;
+        Int decIdx     = xGetDecoderIdx( nalu.m_nuhLayerId , true );      
+        newSliceDiffLayer = nalu.isSlice() && ( nalu.m_nuhLayerId != layerIdCurrPic ) && !firstSlice;
         newSliceDiffPoc   = m_tDecTop[decIdx]->decode(nalu, m_iSkipFrame, m_pocLastDisplay[decIdx], newSliceDiffLayer, sliceSkippedFlag );
         // decode function only returns true when all of the following conditions are true
@@ -233,31 +255,33 @@
         // - nalu.isSlice() == true      
 
-        if ( nalu.m_nalUnitType == NAL_UNIT_VPS )
-        {
-          m_vps = m_tDecTop[decIdx]->getPrefetchedVPS(); 
+        bNewPicture       = ( newSliceDiffLayer || newSliceDiffPoc ) && !sliceSkippedFlag; 
+        if ( nalu.isSlice() && firstSlice && !sliceSkippedFlag )        
+        {
+          layerIdCurrPic = nalu.m_nuhLayerId; 
+          pocCurrPic     = m_tDecTop[decIdx]->getCurrPoc(); 
+          decIdxCurrPic  = decIdx; 
+          firstSlice     = false; 
+
+          /// Use VPS activated by the first slice to determine OLS
+          m_vps = m_tDecTop[decIdx]->getActiveVPS( );
           if ( m_targetDecLayerIdSetFileEmpty )
-          {
-            TComVPS* vps = m_vps; 
+          {            
             if ( m_targetOptLayerSetIdx == -1 )
             {
-              // Not normative! Corresponds to specification by "External Means". (Should be set equal to 0, when no external means available. ) 
-              m_targetOptLayerSetIdx = vps->getVpsNumLayerSetsMinus1(); 
+              m_targetOptLayerSetIdx = m_tDecTop[decIdx]->getTargetOlsIdx(); 
             }
-
-            for (Int dI = 0; dI < m_numDecoders; dI++ )
+            else
             {
-              m_tDecTop[decIdx]->setTargetOptLayerSetIdx( m_targetOptLayerSetIdx ); 
-#if H_3D
-              m_tDecTop[decIdx]->setProfileIdc( ); 
-#endif
+              assert( m_tDecTop[decIdx]->getTargetOlsIdx() == m_targetOptLayerSetIdx );
             }
 
-            if ( m_targetOptLayerSetIdx < 0 || m_targetOptLayerSetIdx >= vps->getNumOutputLayerSets() )
+            if ( m_targetOptLayerSetIdx < 0 || m_targetOptLayerSetIdx >= m_vps->getNumOutputLayerSets() )
             {
-              fprintf(stderr, "\ntarget output layer set index must be in the range of 0 to %d, inclusive \n", vps->getNumOutputLayerSets() - 1 );            
+              fprintf(stderr, "\ntarget output layer set index must be in the range of 0 to %d, inclusive \n", m_vps->getNumOutputLayerSets() - 1 );            
               exit(EXIT_FAILURE);
             }
-            m_targetDecLayerIdSet = vps->getTargetDecLayerIdList( m_targetOptLayerSetIdx ); 
+            m_targetDecLayerIdSet = m_vps->getTargetDecLayerIdList( m_targetOptLayerSetIdx ); 
           }
+
           if (m_outputVpsInfo )
           {
@@ -267,29 +291,15 @@
             m_vps->printPTL(); 
           }
-        }
-#if H_3D
-        if (nalu.m_nalUnitType == NAL_UNIT_VPS )
-        {                  
-          m_cCamParsCollector.init( m_pScaleOffsetFile, m_tDecTop[decIdx]->getPrefetchedVPS() );
-        }       
-#endif
-        bNewPicture       = ( newSliceDiffLayer || newSliceDiffPoc ) && !sliceSkippedFlag; 
-        if ( nalu.isSlice() && firstSlice && !sliceSkippedFlag )        
-        {
-          layerIdCurrPic = nalu.m_layerId; 
-          pocCurrPic     = m_tDecTop[decIdx]->getCurrPoc(); 
-          decIdxCurrPic  = decIdx; 
-          firstSlice     = false; 
-        }
-
-        if ( bNewPicture || !bitstreamFile )
+        }        
+
+        if ( bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS )
         { 
           layerIdLastPic    = layerIdCurrPic; 
-          layerIdCurrPic    = nalu.m_layerId; 
+          layerIdCurrPic    = nalu.m_nuhLayerId; 
           pocLastPic        = pocCurrPic; 
           pocCurrPic        = m_tDecTop[decIdx]->getCurrPoc(); 
           decIdxLastPic     = decIdxCurrPic; 
           decIdxCurrPic     = decIdx; 
-          allLayersDecoded = ( pocCurrPic != pocLastPic );
+          allLayersDecoded = ( pocCurrPic != pocLastPic ) && ( nalu.m_nalUnitType != NAL_UNIT_EOS );
         }
 #else
@@ -309,6 +319,12 @@
            * [1] except for the first NAL unit in the file
            *     (but bNewPicture doesn't happen then) */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+          bitstreamFile.seekg(location);
+          bytestream.reset();
+          TComCodingStatistics::SetStatistics(backupStats);
+#else
           bitstreamFile.seekg(location-streamoff(3));
           bytestream.reset();
+#endif
 #if H_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
@@ -327,9 +343,16 @@
       }
     }
-    if (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS )
+
+    if ( (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS) &&
+#if NH_MV      
+      !m_tDecTop[decIdxLastPic]->getFirstSliceInSequence () )
+#else
+      !m_cTDecTop.getFirstSliceInSequence () )
+#endif
+
     {
       if (!loopFiltered || bitstreamFile)
       {
-#if H_MV
+#if NH_MV
         assert( decIdxLastPic != -1 ); 
         m_tDecTop[decIdxLastPic]->endPicDecoding(poc, pcListPic, m_targetDecLayerIdSet );
@@ -340,14 +363,28 @@
       }
       loopFiltered = (nalu.m_nalUnitType == NAL_UNIT_EOS);
-    }
-#if !FIX_WRITING_OUTPUT
-#if SETTING_NO_OUT_PIC_PRIOR
-    if (bNewPicture && m_cTDecTop.getIsNoOutputPriorPics())
-    {
-      m_cTDecTop.checkNoOutputPriorPics( pcListPic );
-    }
-#endif
-#endif
-#if H_3D
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+#if NH_MV      
+        m_tDecTop[decIdxLastPic]->setFirstSliceInSequence(true);
+#else
+        m_cTDecTop.setFirstSliceInSequence(true);
+#endif
+      }
+    }
+    else if ( (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS ) &&
+#if NH_MV      
+              m_tDecTop[decIdxLastPic]->getFirstSliceInSequence () ) 
+#else
+              m_cTDecTop.getFirstSliceInSequence () ) 
+#endif
+    {
+#if NH_MV      
+      m_tDecTop[decIdxLastPic]->setFirstSliceInPicture (true);
+#else
+      m_cTDecTop.setFirstSliceInPicture (true);
+#endif
+    }
+
+#if NH_3D
     if ( allLayersDecoded || !bitstreamFile )
     {
@@ -363,18 +400,22 @@
     if( pcListPic )
     {
-#if H_MV
+#if NH_MV
       if ( m_pchReconFiles[decIdxLastPic] && !m_reconOpen[decIdxLastPic] )
 #else
-      if ( m_pchReconFile && !openedReconFile  )
-#endif
-      {
-        if (!m_outputBitDepthY) { m_outputBitDepthY = g_bitDepthY; }
-        if (!m_outputBitDepthC) { m_outputBitDepthC = g_bitDepthC; }
-
-#if H_MV
-        m_tVideoIOYuvReconFile[decIdxLastPic]->open( m_pchReconFiles[decIdxLastPic], true, m_outputBitDepthY, m_outputBitDepthC, g_bitDepthY, g_bitDepthC ); // write mode
+      if ( m_pchReconFile && !openedReconFile )
+#endif
+      {
+        const BitDepths &bitDepths=pcListPic->front()->getPicSym()->getSPS().getBitDepths(); // use bit depths of first reconstructed picture.
+        for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+        {
+          if (m_outputBitDepth[channelType] == 0)
+          {
+            m_outputBitDepth[channelType] = bitDepths.recon[channelType];
+          }
+        }
+#if NH_MV
+        m_tVideoIOYuvReconFile[decIdxLastPic]->open( m_pchReconFiles[decIdxLastPic], true, m_outputBitDepth, m_outputBitDepth, bitDepths.recon ); // write mode
         m_reconOpen[decIdxLastPic] = true;
       }
-#if FIX_WRITING_OUTPUT
       // write reconstruction to file
       if( bNewPicture )
@@ -388,5 +429,4 @@
         xWriteOutput( pcListPic, decIdxLastPic, nalu.m_temporalId );
       }
-#if SETTING_NO_OUT_PIC_PRIOR
       if ( (bNewPicture || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA) && m_tDecTop[decIdxLastPic]->getNoOutputPriorPicsFlag() )
       {
@@ -394,12 +434,10 @@
         m_tDecTop[decIdxLastPic]->setNoOutputPriorPicsFlag (false);
       }
-#endif
-#endif
+
       if ( bNewPicture && newSliceDiffPoc && 
 #else
-        m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepthY, m_outputBitDepthC, g_bitDepthY, g_bitDepthC ); // write mode
-        openedReconFile  = true;
-      }
-#if FIX_WRITING_OUTPUT
+        m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepth, m_outputBitDepth, bitDepths.recon ); // write mode
+        openedReconFile = true;
+      }
       // write reconstruction to file
       if( bNewPicture )
@@ -407,5 +445,4 @@
         xWriteOutput( pcListPic, nalu.m_temporalId );
       }
-#if SETTING_NO_OUT_PIC_PRIOR
       if ( (bNewPicture || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA) && m_cTDecTop.getNoOutputPriorPicsFlag() )
       {
@@ -413,7 +450,6 @@
         m_cTDecTop.setNoOutputPriorPicsFlag (false);
       }
-#endif
-#endif
-      if ( bNewPicture && 
+
+      if ( bNewPicture &&
 #endif
            (   nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL
@@ -423,5 +459,5 @@
             || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP ) )
       {
-#if H_MV
+#if NH_MV
         xFlushOutput( pcListPic, decIdxLastPic );
 #else
@@ -431,30 +467,22 @@
       if (nalu.m_nalUnitType == NAL_UNIT_EOS)
       {
-#if H_MV
-#if FIX_OUTPUT_EOS
-        xWriteOutput( pcListPic, decIdxLastPic, nalu.m_temporalId );
-#else
-        xFlushOutput( pcListPic, decIdxLastPic );
-#endif
-#else
-#if FIX_OUTPUT_EOS
+#if NH_MV
+        xWriteOutput( pcListPic, decIdxCurrPic, nalu.m_temporalId );
+#else
         xWriteOutput( pcListPic, nalu.m_temporalId );
-#else
-        xFlushOutput( pcListPic );
-#endif
-
-#endif
-      }
-      // write reconstruction to file -- for additional bumping as defined in C.5.2.3 
-#if H_MV
+#endif
+#if NH_MV
+        m_tDecTop[decIdxCurrPic]->setFirstSliceInPicture (false);
+#else
+        m_cTDecTop.setFirstSliceInPicture (false);
+#endif
+      }
+      // write reconstruction to file -- for additional bumping as defined in C.5.2.3
+#if NH_MV
       // Above comment seems to be wrong
 #endif
-#if FIX_WRITING_OUTPUT
       if(!bNewPicture && nalu.m_nalUnitType >= NAL_UNIT_CODED_SLICE_TRAIL_N && nalu.m_nalUnitType <= NAL_UNIT_RESERVED_VCL31)
-#else
-      if(bNewPicture)
-#endif
-      {
-#if H_MV        
+      {
+#if NH_MV        
         // Bumping after reference picture set has been applied (here after first vcl nalu. 
 #if ENC_DEC_TRACE
@@ -471,6 +499,6 @@
     }
   }
-#if H_MV
-#if H_3D
+#if NH_MV
+#if NH_3D
   if( m_cCamParsCollector.isInitialized() )
   {
@@ -486,8 +514,7 @@
   // delete buffers
   m_cTDecTop.deletePicBuffer();
-#endif
-     
   // destroy internal classes
   xDestroyDecLib();
+#endif
 }
 
@@ -498,5 +525,5 @@
 Void TAppDecTop::xCreateDecLib()
 {
-#if H_MV
+#if NH_MV
   // initialize global variables
   initROM();  
@@ -512,5 +539,5 @@
 Void TAppDecTop::xDestroyDecLib()
 {
-#if H_MV
+#if NH_MV
   // destroy ROM
   destroyROM();
@@ -538,9 +565,9 @@
     m_cTVideoIOYuvReconFile. close();
   }
-  
+
   // destroy decoder class
   m_cTDecTop.destroy();
 #endif
-#if H_3D
+#if NH_3D
   m_cCamParsCollector.uninit();
   if( m_pScaleOffsetFile ) 
@@ -553,15 +580,27 @@
 Void TAppDecTop::xInitDecLib()
 {
-#if !H_MV
+
+#if NH_3D
+  m_cCamParsCollector.setCodeScaleOffsetFile( m_pScaleOffsetFile );
+#endif
+#if !NH_MV
   // initialize decoder class
   m_cTDecTop.init();
   m_cTDecTop.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+#if O0043_BEST_EFFORT_DECODING
+  m_cTDecTop.setForceDecodeBitDepth(m_forceDecodeBitDepth);
+#endif
+  if (!m_outputDecodedSEIMessagesFilename.empty())
+  {
+    std::ostream &os=m_seiMessageFileStream.is_open() ? m_seiMessageFileStream : std::cout;
+    m_cTDecTop.setDecodedSEIMessageOutputStream(&os);
+  }
 #endif
 }
 
 /** \param pcListPic list of pictures to be written to file
-    \todo            DYN_REF_FREE should be revised
+    \param tId       temporal sub-layer ID
  */
-#if H_MV
+#if NH_MV
 Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, Int decIdx, Int tId )
 #else
@@ -569,5 +608,4 @@
 #endif
 {
-
   if (pcListPic->empty())
   {
@@ -578,9 +616,6 @@
   Int numPicsNotYetDisplayed = 0;
   Int dpbFullness = 0;
-#if H_MV
-  TComSPS* activeSPS = m_tDecTop[ decIdx ]->getActiveSPS();
-#else
-  TComSPS* activeSPS = m_cTDecTop.getActiveSPS();
-#endif
+  const TComSPS* activeSPS = &(pcListPic->front()->getPicSym()->getSPS());
+
   UInt numReorderPicsHighestTid;
   UInt maxDecPicBufferingHighestTid;
@@ -597,9 +632,9 @@
     maxDecPicBufferingHighestTid = activeSPS->getMaxDecPicBuffering(m_iMaxTemporalLayer); 
   }
-  
+
   while (iterPic != pcListPic->end())
   {
     TComPic* pcPic = *(iterPic);
-#if H_MV
+#if NH_MV
     if(pcPic->getOutputMark() && pcPic->getPOC() > m_pocLastDisplay[decIdx])
 #else
@@ -607,5 +642,5 @@
 #endif
     {
-      numPicsNotYetDisplayed++;
+       numPicsNotYetDisplayed++;
       dpbFullness++;
     }
@@ -616,10 +651,12 @@
     iterPic++;
   }
-  iterPic   = pcListPic->begin();
+
+  iterPic = pcListPic->begin();
+
   if (numPicsNotYetDisplayed>2)
   {
     iterPic++;
   }
-  
+
   TComPic* pcPic = *(iterPic);
   if (numPicsNotYetDisplayed>2 && pcPic->isField()) //Field Decoding
@@ -633,8 +670,10 @@
       iterPic++;
       TComPic* pcPicBottom = *(iterPic);
-      
-#if H_MV
-      if ( pcPicTop->getOutputMark() && (numPicsNotYetDisplayed >  pcPicTop->getNumReorderPics(tId) && !(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1)
-          && pcPicBottom->getOutputMark() && (numPicsNotYetDisplayed >  pcPicBottom->getNumReorderPics(tId) && (pcPicTop->getPOC() == m_pocLastDisplay[decIdx]+1 || m_pocLastDisplay[decIdx]<0)))
+
+#if NH_MV
+      if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() &&
+        (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid) &&
+        (!(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1) &&
+        (pcPicTop->getPOC() == m_pocLastDisplay[decIdx]+1 || m_pocLastDisplay[decIdx] < 0))
 #else
       if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() &&
@@ -646,5 +685,5 @@
         // write to file
         numPicsNotYetDisplayed = numPicsNotYetDisplayed-2;
-#if H_MV
+#if NH_MV
       if ( m_pchReconFiles[decIdx] )
 #else
@@ -653,8 +692,21 @@
         {
           const Window &conf = pcPicTop->getConformanceWindow();
-          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
-
+          const Window  defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
           const Bool isTff = pcPicTop->isTopField();
-#if H_MV
+
+          Bool display = true;
+          if( m_decodedNoDisplaySEIEnabled )
+          {
+            SEIMessages noDisplay = getSeisByType(pcPic->getSEIs(), SEI::NO_DISPLAY );
+            const SEINoDisplay *nd = ( noDisplay.size() > 0 ) ? (SEINoDisplay*) *(noDisplay.begin()) : NULL;
+            if( (nd != NULL) && nd->m_noDisplay )
+            {
+              display = false;
+            }
+          }
+
+          if (display)
+          {
+#if NH_MV
         assert( conf   .getScaledFlag() );
         assert( defDisp.getScaledFlag() );
@@ -667,49 +719,39 @@
         m_tVideoIOYuvReconFile[decIdx]->write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
 #else
-          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
-#endif
-                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
-        }
-        
+        m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#endif
+                                           m_outputColourSpaceConvert,
+                                           conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                           conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                           conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+#if NH_3D
+                                           conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), m_depth420OutputFlag && pcPicTop->getIsDepth() ? CHROMA_420 : NUM_CHROMA_FORMAT, isTff );
+#else
+                                           conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff );
+#endif
+          }
+        }
+
         // update POC of display order
-#if H_MV
+#if NH_MV
         m_pocLastDisplay[decIdx] = pcPic->getPOC();
 #else
         m_iPOCLastDisplay = pcPicBottom->getPOC();
 #endif
-        
+
         // erase non-referenced picture in the reference picture list after display
         if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true )
         {
-#if !DYN_REF_FREE
           pcPicTop->setReconMark(false);
-          
+
           // mark it should be extended later
           pcPicTop->getPicYuvRec()->setBorderExtension( false );
-          
-#else
-          pcPicTop->destroy();
-          pcListPic->erase( iterPic );
-          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
-          continue;
-#endif
         }
         if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true )
         {
-#if !DYN_REF_FREE
           pcPicBottom->setReconMark(false);
-          
+
           // mark it should be extended later
           pcPicBottom->getPicYuvRec()->setBorderExtension( false );
-          
-#else
-          pcPicBottom->destroy();
-          pcListPic->erase( iterPic );
-          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
-          continue;
-#endif
         }
         pcPicTop->setOutputMark(false);
@@ -721,9 +763,10 @@
   {
     iterPic = pcListPic->begin();
+
     while (iterPic != pcListPic->end())
     {
       pcPic = *(iterPic);
 
-#if H_MV
+#if NH_MV
       if(pcPic->getOutputMark() && pcPic->getPOC() > m_pocLastDisplay[decIdx] &&
         (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid))
@@ -734,10 +777,10 @@
       {
         // write to file
-        numPicsNotYetDisplayed--;
+         numPicsNotYetDisplayed--;
         if(pcPic->getSlice(0)->isReferenced() == false)
         {
           dpbFullness--;
         }
-#if H_MV
+#if NH_MV
       if ( m_pchReconFiles[decIdx] )
 #else
@@ -745,7 +788,7 @@
 #endif
         {
-          const Window &conf = pcPic->getConformanceWindow();
-          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
-#if H_MV
+          const Window &conf    = pcPic->getConformanceWindow();
+          const Window defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+#if NH_MV
         assert( conf   .getScaledFlag() );
         assert( defDisp.getScaledFlag() );
@@ -760,47 +803,46 @@
           m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
 #endif
-                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
-        }
-        
+                                         m_outputColourSpaceConvert,
+                                         conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                         conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                         conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                         conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), 
+#if NH_3D
+                                          m_depth420OutputFlag && pcPic->getIsDepth() ? CHROMA_420 : NUM_CHROMA_FORMAT,
+#else
+                                          NUM_CHROMA_FORMAT,
+#endif
+           m_bClipOutputVideoToRec709Range   );
+        }
+
         // update POC of display order
-#if H_MV
+#if NH_MV
         m_pocLastDisplay[decIdx] = pcPic->getPOC();
 #else
         m_iPOCLastDisplay = pcPic->getPOC();
 #endif
-        
+
         // erase non-referenced picture in the reference picture list after display
         if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
         {
-#if !DYN_REF_FREE
           pcPic->setReconMark(false);
-          
+
           // mark it should be extended later
           pcPic->getPicYuvRec()->setBorderExtension( false );
-          
-#else
-          pcPic->destroy();
-          pcListPic->erase( iterPic );
-          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
-          continue;
-#endif
         }
         pcPic->setOutputMark(false);
-#if H_MV
+#if NH_MV
         pcPic->setPicOutputFlag(false);
 #endif
       }
-      
+
       iterPic++;
     }
   }
 }
+
 /** \param pcListPic list of pictures to be written to file
-    \todo            DYN_REF_FREE should be revised
  */
-#if H_MV
+#if NH_MV
 Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic, Int decIdx )
 #else
@@ -813,8 +855,8 @@
   }
   TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
-  
+
   iterPic   = pcListPic->begin();
   TComPic* pcPic = *(iterPic);
-  
+
   if (pcPic->isField()) //Field Decoding
   {
@@ -827,9 +869,9 @@
       iterPic++;
       pcPicBottom = *(iterPic);
-      
+
       if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() && !(pcPicTop->getPOC()%2) && (pcPicBottom->getPOC() == pcPicTop->getPOC()+1) )
       {
         // write to file
-#if H_MV
+#if NH_MV
       if ( m_pchReconFiles[decIdx] )
 #else
@@ -838,7 +880,7 @@
         {
           const Window &conf = pcPicTop->getConformanceWindow();
-          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Window  defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
           const Bool isTff = pcPicTop->isTopField();
-#if H_MV
+#if NH_MV
         assert( conf   .getScaledFlag() );
         assert( defDisp.getScaledFlag() );
@@ -853,51 +895,39 @@
           m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
 #endif
-                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
-        }
-        
+                                         m_outputColourSpaceConvert,
+                                         conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                         conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                         conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+#if NH_3D
+                                         conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), m_depth420OutputFlag && pcPicTop->getIsDepth() ? CHROMA_420 : NUM_CHROMA_FORMAT, isTff );
+#else
+                                         conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff );
+#endif
+        }
+
         // update POC of display order
-#if H_MV
+#if NH_MV
       m_pocLastDisplay[decIdx] = pcPic->getPOC();
 #else
-      m_iPOCLastDisplay = pcPicBottom->getPOC();
+        m_iPOCLastDisplay = pcPicBottom->getPOC();
 #endif        
         // erase non-referenced picture in the reference picture list after display
         if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true )
         {
-#if !DYN_REF_FREE
           pcPicTop->setReconMark(false);
-          
+
           // mark it should be extended later
           pcPicTop->getPicYuvRec()->setBorderExtension( false );
-          
-#else
-          pcPicTop->destroy();
-          pcListPic->erase( iterPic );
-          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
-          continue;
-#endif
         }
         if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true )
         {
-#if !DYN_REF_FREE
           pcPicBottom->setReconMark(false);
-          
+
           // mark it should be extended later
           pcPicBottom->getPicYuvRec()->setBorderExtension( false );
-          
-#else
-          pcPicBottom->destroy();
-          pcListPic->erase( iterPic );
-          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
-          continue;
-#endif
         }
         pcPicTop->setOutputMark(false);
         pcPicBottom->setOutputMark(false);
-        
-#if !DYN_REF_FREE
+
         if(pcPicTop)
         {
@@ -906,5 +936,4 @@
           pcPicTop = NULL;
         }
-#endif
       }
     }
@@ -921,9 +950,9 @@
     {
       pcPic = *(iterPic);
-      
+
       if ( pcPic->getOutputMark() )
       {
         // write to file
-#if H_MV
+#if NH_MV
       if ( m_pchReconFiles[decIdx] )
 #else
@@ -931,7 +960,7 @@
 #endif
         {
-          const Window &conf = pcPic->getConformanceWindow();
-          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
-#if H_MV
+          const Window &conf    = pcPic->getConformanceWindow();
+          const Window  defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+#if NH_MV
         assert( conf   .getScaledFlag() );
         assert( defDisp.getScaledFlag() );
@@ -946,41 +975,39 @@
           m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
 #endif
-                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
-                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
-                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
-                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
-        }
-        
+                                         m_outputColourSpaceConvert,
+                                         conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                         conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                         conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                         conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), 
+#if NH_3D
+                                         m_depth420OutputFlag && pcPic->getIsDepth() ? CHROMA_420 : NUM_CHROMA_FORMAT
+#else
+                                         NUM_CHROMA_FORMAT
+#endif
+                                         , m_bClipOutputVideoToRec709Range);
+        }
+
         // update POC of display order
-#if H_MV
+#if NH_MV
       m_pocLastDisplay[decIdx] = pcPic->getPOC();
 #else
         m_iPOCLastDisplay = pcPic->getPOC();
 #endif
-        
+
         // erase non-referenced picture in the reference picture list after display
         if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
         {
-#if !DYN_REF_FREE
           pcPic->setReconMark(false);
-          
+
           // mark it should be extended later
           pcPic->getPicYuvRec()->setBorderExtension( false );
-          
-#else
-          pcPic->destroy();
-          pcListPic->erase( iterPic );
-          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
-          continue;
-#endif
         }
         pcPic->setOutputMark(false);
-#if H_MV
+#if NH_MV
         pcPic->setPicOutputFlag(false);
 #endif
       }
-#if !H_MV
-#if !DYN_REF_FREE
-      if(pcPic)
+#if !NH_MV
+      if(pcPic != NULL)
       {
         pcPic->destroy();
@@ -988,10 +1015,9 @@
         pcPic = NULL;
       }
-#endif    
 #endif
       iterPic++;
     }
   }
-#if H_MV
+#if NH_MV
   m_pocLastDisplay[decIdx] = -MAX_INT;
 #else
@@ -1011,8 +1037,8 @@
   for (std::vector<Int>::iterator it = m_targetDecLayerIdSet.begin(); it != m_targetDecLayerIdSet.end(); it++)
   {
-#if H_MV
-    if ( nalu->m_layerId == (*it) )
-#else
-    if ( nalu->m_reservedZero6Bits == (*it) )
+#if NH_MV
+    if ( nalu->m_nuhLayerId == (*it) )
+#else
+    if ( nalu->m_nuhLayerId == (*it) )
 #endif
     {
@@ -1023,5 +1049,5 @@
 }
 
-#if H_MV
+#if NH_MV
 Int TAppDecTop::xGetDecoderIdx( Int layerId, Bool createFlag /*= false */ )
 {
@@ -1052,10 +1078,14 @@
     m_tDecTop[ decIdx ]->setIvPicLists( &m_ivPicLists ); 
     m_tDecTop[ decIdx ]->setLayerInitilizedFlags( m_layerInitilizedFlags );
-    m_tDecTop[ decIdx ]->setTargetOptLayerSetIdx( m_targetOptLayerSetIdx );    
-#if H_3D
-    m_tDecTop[ decIdx ]->setProfileIdc           ( );    
-#endif
-
-#if H_3D
+    m_tDecTop[ decIdx ]->setTargetOlsIdx( m_targetOptLayerSetIdx );    
+#if O0043_BEST_EFFORT_DECODING
+    m_cTDecTop[ decIdx ]->setForceDecodeBitDepth(m_forceDecodeBitDepth);
+#endif
+    if (!m_outputDecodedSEIMessagesFilename.empty())
+    {
+      std::ostream &os=m_seiMessageFileStream.is_open() ? m_seiMessageFileStream : std::cout;
+      m_tDecTop[ decIdx ]->setDecodedSEIMessageOutputStream(&os);
+    }
+#if NH_3D
    m_tDecTop[ decIdx ]->setCamParsCollector( &m_cCamParsCollector );
 #endif
Index: branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecTop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppDecoder/TAppDecTop.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -61,5 +61,5 @@
 private:
   // class interface
-#if H_MV
+#if NH_MV
   TDecTop*                        m_tDecTop             [ MAX_NUM_LAYERS ];    ///< decoder classes
   TVideoIOYuv*                    m_tVideoIOYuvReconFile[ MAX_NUM_LAYERS ];    ///< reconstruction YUV class
@@ -68,11 +68,11 @@
   TComPicLists                    m_ivPicLists;                                ///< picture buffers of decoder instances
   Bool                            m_layerInitilizedFlags[ MAX_NUM_LAYER_IDS ]; ///< for layerwise startup 
-  TComVPS*                        m_vps;                                ///< active VPS
+  const TComVPS*                  m_vps;                                ///< active VPS
 #else
   TDecTop                         m_cTDecTop;                     ///< decoder class
   TVideoIOYuv                     m_cTVideoIOYuvReconFile;        ///< reconstruction YUV class
 #endif
-    // for output control
-#if H_MV
+  // for output control
+#if NH_MV
   Int                             m_pocLastDisplay      [ MAX_NUM_LAYERS ]; ///< last POC in display order
   Bool                            m_reconOpen           [ MAX_NUM_LAYERS ]; ///< reconstruction file opened
@@ -81,6 +81,7 @@
   Int                             m_iPOCLastDisplay;              ///< last POC in display order
 #endif
+  std::ofstream                   m_seiMessageFileStream;         ///< Used for outputing SEI messages.
 
-#if H_3D
+#if NH_3D
   FILE*                           m_pScaleOffsetFile;
   CamParsCollector                m_cCamParsCollector;
@@ -89,8 +90,24 @@
   TAppDecTop();
   virtual ~TAppDecTop() {}
-  
+
   Void  create            (); ///< create internal members
   Void  destroy           (); ///< destroy internal members
   Void  decode            (); ///< main decoding function
+#if NH_MV
+  UInt  getNumberOfChecksumErrorsDetected( ) const 
+  {
+    UInt numOfChecksumErrors = 0; 
+    for (Int i = 0; i < m_numDecoders; i++ )
+    {
+      numOfChecksumErrors += getNumberOfChecksumErrorsDetected( i ); 
+    }
+    return numOfChecksumErrors; 
+  }
+
+  UInt  getNumberOfChecksumErrorsDetected( Int decIdx ) const { return m_tDecTop[decIdx]->getNumberOfChecksumErrorsDetected(); }
+
+#else
+  UInt  getNumberOfChecksumErrorsDetected() const { return m_cTDecTop.getNumberOfChecksumErrorsDetected(); }
+#endif
 
 protected:
@@ -99,5 +116,5 @@
   Void  xInitDecLib       (); ///< initialize decoder class
 
-#if H_MV
+#if NH_MV
   Void  xWriteOutput      ( TComList<TComPic*>* pcListPic, Int layerId, Int tId ); ///< write YUV to file
 
Index: branches/HTM-14.1-update-dev0/source/App/TAppDecoder/decmain.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppDecoder/decmain.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppDecoder/decmain.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -44,6 +44,4 @@
 //! \{
 
-bool g_md5_mismatch = false; ///< top level flag that indicates if there has been a decoding mismatch
-
 // ====================================================================================================================
 // Main function
@@ -52,12 +50,13 @@
 int main(int argc, char* argv[])
 {
+  Int returnCode = EXIT_SUCCESS;
   TAppDecTop  cTAppDecTop;
 
   // print information
   fprintf( stdout, "\n" );
-#if H_MV
+#if NH_MV
   fprintf( stdout, "3D-HTM Software: Decoder Version [%s] based on HM Version [%s]", NV_VERSION, HM_VERSION );  
 #else
-  fprintf( stdout, "HM software: Decoder Version [%s]", NV_VERSION );
+  fprintf( stdout, "HM software: Decoder Version [%s] (including RExt)", NV_VERSION );
 #endif
   fprintf( stdout, NVM_ONOS );
@@ -73,21 +72,23 @@
   {
     cTAppDecTop.destroy();
-    return 1;
+    returnCode = EXIT_FAILURE;
+    return returnCode;
   }
 
   // starting time
-  double dResult;
-  long lBefore = clock();
+  Double dResult;
+  clock_t lBefore = clock();
 
   // call decoding function
   cTAppDecTop.decode();
 
-  if (g_md5_mismatch)
+  if (cTAppDecTop.getNumberOfChecksumErrorsDetected() != 0)
   {
     printf("\n\n***ERROR*** A decoding mismatch occured: signalled md5sum does not match\n");
+    returnCode = EXIT_FAILURE;
   }
 
   // ending time
-  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  dResult = (Double)(clock()-lBefore) / CLOCKS_PER_SEC;
   printf("\n Total Time: %12.3f sec.\n", dResult);
 
@@ -95,5 +96,5 @@
   cTAppDecTop.destroy();
 
-  return g_md5_mismatch ? EXIT_FAILURE : EXIT_SUCCESS;
+  return returnCode;
 }
 
Index: branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,15 +36,12 @@
 */
 
+#include <stdio.h>
 #include <stdlib.h>
 #include <cassert>
 #include <cstring>
 #include <string>
+#include <limits>
 #include "TLibCommon/TComRom.h"
 #include "TAppEncCfg.h"
-
-static istream& operator>>(istream &, Level::Name &);
-static istream& operator>>(istream &, Level::Tier &);
-static istream& operator>>(istream &, Profile::Name &);
-
 #include "TAppCommon/program_options_lite.h"
 #include "TLibEncoder/TEncRateCtrl.h"
@@ -53,6 +50,54 @@
 #endif
 
+#define MACRO_TO_STRING_HELPER(val) #val
+#define MACRO_TO_STRING(val) MACRO_TO_STRING_HELPER(val)
+
 using namespace std;
 namespace po = df::program_options_lite;
+
+
+
+enum ExtendedProfileName // this is used for determining profile strings, where multiple profiles map to a single profile idc with various constraint flag combinations
+{
+  NONE = 0,
+  MAIN = 1,
+  MAIN10 = 2,
+  MAINSTILLPICTURE = 3,
+  MAINREXT = 4,
+  HIGHTHROUGHPUTREXT = 5, // Placeholder profile for development
+  // The following are RExt profiles, which would map to the MAINREXT profile idc.
+  // The enumeration indicates the bit-depth constraint in the bottom 2 digits
+  //                           the chroma format in the next digit
+    //                           the intra constraint in the next digit
+//                           If it is a RExt still picture, there is a '1' for the top digit.
+#if NH_MV
+  MULTIVIEWMAIN = 6,
+#if NH_3D
+  MAIN3D = 8, 
+#endif
+#endif
+  MONOCHROME_8      = 1008,
+  MONOCHROME_12     = 1012,
+  MONOCHROME_16     = 1016,
+  MAIN_12           = 1112,
+  MAIN_422_10       = 1210,
+  MAIN_422_12       = 1212,
+  MAIN_444          = 1308,
+  MAIN_444_10       = 1310,
+  MAIN_444_12       = 1312,
+  MAIN_444_16       = 1316, // non-standard profile definition, used for development purposes
+  MAIN_INTRA        = 2108,
+  MAIN_10_INTRA     = 2110,
+  MAIN_12_INTRA     = 2112,
+  MAIN_422_10_INTRA = 2210,
+  MAIN_422_12_INTRA = 2212,
+  MAIN_444_INTRA    = 2308,
+  MAIN_444_10_INTRA = 2310,
+  MAIN_444_12_INTRA = 2312,
+  MAIN_444_16_INTRA = 2316,
+  MAIN_444_STILL_PICTURE = 11308,
+  MAIN_444_16_STILL_PICTURE = 12316
+};
+
 
 //! \ingroup TAppEncoder
@@ -64,5 +109,5 @@
 
 TAppEncCfg::TAppEncCfg()
-#if H_MV
+#if NH_MV
 : m_pchBitstreamFile()
 #else
@@ -71,8 +116,11 @@
 , m_pchReconFile()
 #endif
+, m_inputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
+, m_snrInternalColourSpace(false)
+, m_outputInternalColourSpace(false)
 , m_pchdQPFile()
 , m_scalingListFile()
 {
-#if !H_MV
+#if !NH_MV
   m_aidQP = NULL;
 #endif
@@ -88,5 +136,5 @@
 TAppEncCfg::~TAppEncCfg()
 {
-#if H_MV
+#if NH_MV
   for( Int layer = 0; layer < m_aidQP.size(); layer++ )
   {
@@ -123,9 +171,9 @@
     m_targetPivotValue = NULL;
   }
-#if !H_MV
+#if !NH_MV
   free(m_pchInputFile);
 #endif
   free(m_pchBitstreamFile);
-#if H_MV
+#if NH_MV
   for(Int i = 0; i< m_pchReconFileList.size(); i++ )
   {
@@ -138,5 +186,5 @@
   free(m_pchdQPFile);
   free(m_scalingListFile);
-#if H_MV
+#if NH_MV
   for( Int i = 0; i < m_GOPListMvc.size(); i++ )
   {
@@ -148,14 +196,20 @@
   }
 #endif
-#if H_3D
-#if H_3D_VSO
+#if NH_3D
+#if NH_3D_VSO
   if (  m_pchVSOConfig != NULL)
+  {
     free (  m_pchVSOConfig );
+  }
 #endif
   if ( m_pchCameraParameterFile != NULL )
+  {
     free ( m_pchCameraParameterFile ); 
+  }
 
   if ( m_pchBaseViewCameraNumbers != NULL )
+  {
     free ( m_pchBaseViewCameraNumbers ); 
+  }
 #endif
 }
@@ -185,5 +239,4 @@
   }
   in>>entry.m_interRPSPrediction;
-#if AUTO_INTER_RPS
   if (entry.m_interRPSPrediction==1)
   {
@@ -199,16 +252,5 @@
     in>>entry.m_deltaRPS;
   }
-#else
-  if (entry.m_interRPSPrediction)
-  {
-    in>>entry.m_deltaRPS;
-    in>>entry.m_numRefIdc;
-    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
-    {
-      in>>entry.m_refIdc[i];
-    }
-  }
-#endif
-#if H_MV
+#if NH_MV
   in>>entry.m_numActiveRefLayerPics;
   for( Int i = 0; i < entry.m_numActiveRefLayerPics; i++ )
@@ -225,39 +267,130 @@
   }
 #endif
-#if H_3D
+#if NH_3D
   in>>entry.m_interCompPredFlag;
 #endif
+
   return in;
 }
 
-static const struct MapStrToProfile {
+Bool confirmPara(Bool bflag, const Char* message);
+
+static inline ChromaFormat numberToChromaFormat(const Int val)
+{
+  switch (val)
+  {
+    case 400: return CHROMA_400; break;
+    case 420: return CHROMA_420; break;
+    case 422: return CHROMA_422; break;
+    case 444: return CHROMA_444; break;
+    default:  return NUM_CHROMA_FORMAT;
+  }
+}
+
+static const struct MapStrToProfile
+{
   const Char* str;
   Profile::Name value;
-} strToProfile[] = {
-  {"none", Profile::NONE},
-  {"main", Profile::MAIN},
-  {"main10", Profile::MAIN10},
-  {"main-still-picture", Profile::MAINSTILLPICTURE},
-#if H_MV
-  {"multiview-main", Profile::MULTIVIEWMAIN},
-#if H_3D
-  {"3d-main"       , Profile::MAIN3D},
-#endif
-
-#endif
+}
+strToProfile[] =
+{
+  {"none",                 Profile::NONE               },
+  {"main",                 Profile::MAIN               },
+  {"main10",               Profile::MAIN10             },
+  {"main-still-picture",   Profile::MAINSTILLPICTURE   },
+  {"main-RExt",            Profile::MAINREXT           },
+  {"high-throughput-RExt", Profile::HIGHTHROUGHPUTREXT }
+#if NH_MV
+  ,{"multiview-main"     , Profile::MULTIVIEWMAIN      },
+#if NH_3D
+   {"3d-main"            , Profile::MAIN3D             }
+#endif
+#endif
+
 };
 
-static const struct MapStrToTier {
+static const struct MapStrToExtendedProfile
+{
+  const Char* str;
+  ExtendedProfileName value;
+}
+strToExtendedProfile[] =
+{
+    {"none",               NONE             },
+    {"main",               MAIN             },
+    {"main10",             MAIN10           },
+    {"main_still_picture",        MAINSTILLPICTURE },
+    {"main-still-picture",        MAINSTILLPICTURE },
+    {"main_RExt",                 MAINREXT         },
+    {"main-RExt",                 MAINREXT         },
+    {"main_rext",                 MAINREXT         },
+    {"main-rext",                 MAINREXT         },
+    {"high_throughput_RExt",      HIGHTHROUGHPUTREXT },
+    {"high-throughput-RExt",      HIGHTHROUGHPUTREXT },
+    {"high_throughput_rext",      HIGHTHROUGHPUTREXT },
+    {"high-throughput-rext",      HIGHTHROUGHPUTREXT },
+#if NH_MV
+    {"multiview-main"     , MULTIVIEWMAIN   },
+#if NH_3D
+    {"3d-main"            , MAIN3D          },
+#endif
+#endif
+    {"monochrome",         MONOCHROME_8     },
+    {"monochrome12",       MONOCHROME_12    },
+    {"monochrome16",       MONOCHROME_16    },
+    {"main12",             MAIN_12          },
+    {"main_422_10",        MAIN_422_10      },
+    {"main_422_12",        MAIN_422_12      },
+    {"main_444",           MAIN_444         },
+    {"main_444_10",        MAIN_444_10      },
+    {"main_444_12",        MAIN_444_12      },
+    {"main_444_16",        MAIN_444_16      },
+    {"main_intra",         MAIN_INTRA       },
+    {"main_10_intra",      MAIN_10_INTRA    },
+    {"main_12_intra",      MAIN_12_INTRA    },
+    {"main_422_10_intra",  MAIN_422_10_INTRA},
+    {"main_422_12_intra",  MAIN_422_12_INTRA},
+    {"main_444_intra",     MAIN_444_INTRA   },
+    {"main_444_still_picture",    MAIN_444_STILL_PICTURE },
+    {"main_444_10_intra",  MAIN_444_10_INTRA},
+    {"main_444_12_intra",  MAIN_444_12_INTRA},
+    {"main_444_16_intra",         MAIN_444_16_INTRA},
+    {"main_444_16_still_picture", MAIN_444_16_STILL_PICTURE }
+};
+
+static const ExtendedProfileName validRExtProfileNames[2/* intraConstraintFlag*/][4/* bit depth constraint 8=0, 10=1, 12=2, 16=3*/][4/*chroma format*/]=
+{
+    {
+        { MONOCHROME_8,  NONE,          NONE,              MAIN_444          }, // 8-bit  inter for 400, 420, 422 and 444
+        { NONE,          NONE,          MAIN_422_10,       MAIN_444_10       }, // 10-bit inter for 400, 420, 422 and 444
+        { MONOCHROME_12, MAIN_12,       MAIN_422_12,       MAIN_444_12       }, // 12-bit inter for 400, 420, 422 and 444
+        { MONOCHROME_16, NONE,          NONE,              MAIN_444_16       }  // 16-bit inter for 400, 420, 422 and 444 (the latter is non standard used for development)
+    },
+    {
+        { NONE,          MAIN_INTRA,    NONE,              MAIN_444_INTRA    }, // 8-bit  intra for 400, 420, 422 and 444
+        { NONE,          MAIN_10_INTRA, MAIN_422_10_INTRA, MAIN_444_10_INTRA }, // 10-bit intra for 400, 420, 422 and 444
+        { NONE,          MAIN_12_INTRA, MAIN_422_12_INTRA, MAIN_444_12_INTRA }, // 12-bit intra for 400, 420, 422 and 444
+        { NONE,          NONE,          NONE,              MAIN_444_16_INTRA }  // 16-bit intra for 400, 420, 422 and 444
+    }
+};
+
+static const struct MapStrToTier
+{
   const Char* str;
   Level::Tier value;
-} strToTier[] = {
+}
+strToTier[] =
+{
   {"main", Level::MAIN},
   {"high", Level::HIGH},
 };
 
-static const struct MapStrToLevel {
+static const struct MapStrToLevel
+{
   const Char* str;
   Level::Name value;
-} strToLevel[] = {
+}
+strToLevel[] =
+{
   {"none",Level::NONE},
   {"1",   Level::LEVEL1},
@@ -274,13 +407,55 @@
   {"6.1", Level::LEVEL6_1},
   {"6.2", Level::LEVEL6_2},
+  {"8.5", Level::LEVEL8_5},
 };
 
+static const struct MapStrToCostMode
+{
+  const Char* str;
+  CostMode    value;
+}
+strToCostMode[] =
+{
+  {"lossy",                     COST_STANDARD_LOSSY},
+  {"sequence_level_lossless",   COST_SEQUENCE_LEVEL_LOSSLESS},
+  {"lossless",                  COST_LOSSLESS_CODING},
+  {"mixed_lossless_lossy",      COST_MIXED_LOSSLESS_LOSSY_CODING}
+};
+
+static const struct MapStrToScalingListMode
+{
+  const Char* str;
+  ScalingListMode value;
+}
+strToScalingListMode[] =
+{
+  {"0",       SCALING_LIST_OFF},
+  {"1",       SCALING_LIST_DEFAULT},
+  {"2",       SCALING_LIST_FILE_READ},
+  {"off",     SCALING_LIST_OFF},
+  {"default", SCALING_LIST_DEFAULT},
+  {"file",    SCALING_LIST_FILE_READ}
+};
+
 template<typename T, typename P>
-static istream& readStrToEnum(P map[], unsigned long mapLen, istream &in, T &val)
+static std::string enumToString(P map[], UInt mapLen, const T val)
+{
+  for (UInt i = 0; i < mapLen; i++)
+  {
+    if (val == map[i].value)
+    {
+      return map[i].str;
+    }
+  }
+  return std::string();
+}
+
+template<typename T, typename P>
+static istream& readStrToEnum(P map[], UInt mapLen, istream &in, T &val)
 {
   string str;
   in >> str;
 
-  for (Int i = 0; i < mapLen; i++)
+  for (UInt i = 0; i < mapLen; i++)
   {
     if (str == map[i].str)
@@ -296,19 +471,283 @@
 }
 
-static istream& operator>>(istream &in, Profile::Name &profile)
+//inline to prevent compiler warnings for "unused static function"
+
+static inline istream& operator >> (istream &in, ExtendedProfileName &profile)
 {
-  return readStrToEnum(strToProfile, sizeof(strToProfile)/sizeof(*strToProfile), in, profile);
+  return readStrToEnum(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), in, profile);
 }
 
-static istream& operator>>(istream &in, Level::Tier &tier)
+namespace Level
 {
-  return readStrToEnum(strToTier, sizeof(strToTier)/sizeof(*strToTier), in, tier);
+  static inline istream& operator >> (istream &in, Tier &tier)
+  {
+    return readStrToEnum(strToTier, sizeof(strToTier)/sizeof(*strToTier), in, tier);
+  }
+
+  static inline istream& operator >> (istream &in, Name &level)
+  {
+    return readStrToEnum(strToLevel, sizeof(strToLevel)/sizeof(*strToLevel), in, level);
+  }
 }
 
-static istream& operator>>(istream &in, Level::Name &level)
+static inline istream& operator >> (istream &in, CostMode &mode)
 {
-  return readStrToEnum(strToLevel, sizeof(strToLevel)/sizeof(*strToLevel), in, level);
+  return readStrToEnum(strToCostMode, sizeof(strToCostMode)/sizeof(*strToCostMode), in, mode);
 }
 
+static inline istream& operator >> (istream &in, ScalingListMode &mode)
+{
+  return readStrToEnum(strToScalingListMode, sizeof(strToScalingListMode)/sizeof(*strToScalingListMode), in, mode);
+}
+
+template <class T>
+struct SMultiValueInput
+{
+  const T              minValIncl;
+  const T              maxValIncl; // Use 0 for unlimited
+  const std::size_t    minNumValuesIncl;
+  const std::size_t    maxNumValuesIncl; // Use 0 for unlimited
+        std::vector<T> values;
+  SMultiValueInput() : minValIncl(0), maxValIncl(0), minNumValuesIncl(0), maxNumValuesIncl(0), values() { }
+  SMultiValueInput(std::vector<T> &defaults) : minValIncl(0), maxValIncl(0), minNumValuesIncl(0), maxNumValuesIncl(0), values(defaults) { }
+  SMultiValueInput(const T &minValue, const T &maxValue, std::size_t minNumberValues=0, std::size_t maxNumberValues=0)
+    : minValIncl(minValue), maxValIncl(maxValue), minNumValuesIncl(minNumberValues), maxNumValuesIncl(maxNumberValues), values()  { }
+  SMultiValueInput(const T &minValue, const T &maxValue, std::size_t minNumberValues, std::size_t maxNumberValues, const T* defValues, const UInt numDefValues)
+    : minValIncl(minValue), maxValIncl(maxValue), minNumValuesIncl(minNumberValues), maxNumValuesIncl(maxNumberValues), values(defValues, defValues+numDefValues)  { }
+  SMultiValueInput<T> &operator=(const std::vector<T> &userValues) { values=userValues; return *this; }
+  SMultiValueInput<T> &operator=(const SMultiValueInput<T> &userValues) { values=userValues.values; return *this; }
+};
+
+static inline istream& operator >> (istream &in, SMultiValueInput<UInt> &values)
+{
+  values.values.clear();
+  string str;
+  while (!in.eof())
+  {
+    string tmp; in >> tmp; str+=" " + tmp;
+  }
+  if (!str.empty())
+  {
+    const Char *pStr=str.c_str();
+    // soak up any whitespace
+    for(;isspace(*pStr);pStr++);
+
+    while (*pStr != 0)
+    {
+      Char *eptr;
+      UInt val=strtoul(pStr, &eptr, 0);
+      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      if (val<values.minValIncl || val>values.maxValIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+
+      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      values.values.push_back(val);
+      // soak up any whitespace and up to 1 comma.
+      pStr=eptr;
+      for(;isspace(*pStr);pStr++);
+      if (*pStr == ',')
+      {
+        pStr++;
+      }
+      for(;isspace(*pStr);pStr++);
+    }
+  }
+  if (values.values.size() < values.minNumValuesIncl)
+  {
+    in.setstate(ios::failbit);
+  }
+  return in;
+}
+
+static inline istream& operator >> (istream &in, SMultiValueInput<Int> &values)
+{
+  values.values.clear();
+  string str;
+  while (!in.eof())
+  {
+    string tmp; in >> tmp; str+=" " + tmp;
+  }
+  if (!str.empty())
+  {
+    const Char *pStr=str.c_str();
+    // soak up any whitespace
+    for(;isspace(*pStr);pStr++);
+
+    while (*pStr != 0)
+    {
+      Char *eptr;
+      Int val=strtol(pStr, &eptr, 0);
+      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      if (val<values.minValIncl || val>values.maxValIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+
+      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      values.values.push_back(val);
+      // soak up any whitespace and up to 1 comma.
+      pStr=eptr;
+      for(;isspace(*pStr);pStr++);
+      if (*pStr == ',')
+      {
+        pStr++;
+      }
+      for(;isspace(*pStr);pStr++);
+    }
+  }
+  if (values.values.size() < values.minNumValuesIncl)
+  {
+    in.setstate(ios::failbit);
+  }
+  return in;
+}
+
+static inline istream& operator >> (istream &in, SMultiValueInput<Bool> &values)
+{
+  values.values.clear();
+  string str;
+  while (!in.eof())
+  {
+    string tmp; in >> tmp; str+=" " + tmp;
+  }
+  if (!str.empty())
+  {
+    const Char *pStr=str.c_str();
+    // soak up any whitespace
+    for(;isspace(*pStr);pStr++);
+
+    while (*pStr != 0)
+    {
+      Char *eptr;
+      Int val=strtol(pStr, &eptr, 0);
+      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      if (val<Int(values.minValIncl) || val>Int(values.maxValIncl))
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+
+      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      values.values.push_back(val!=0);
+      // soak up any whitespace and up to 1 comma.
+      pStr=eptr;
+      for(;isspace(*pStr);pStr++);
+      if (*pStr == ',')
+      {
+        pStr++;
+      }
+      for(;isspace(*pStr);pStr++);
+    }
+  }
+  if (values.values.size() < values.minNumValuesIncl)
+  {
+    in.setstate(ios::failbit);
+  }
+  return in;
+}
+
+static Void
+automaticallySelectRExtProfile(const Bool bUsingGeneralRExtTools,
+                               const Bool bUsingChromaQPAdjustment,
+                               const Bool bUsingExtendedPrecision,
+                               const Bool bIntraConstraintFlag,
+                               UInt &bitDepthConstraint,
+                               ChromaFormat &chromaFormatConstraint,
+                               const Int  maxBitDepth,
+                               const ChromaFormat chromaFormat)
+{
+  // Try to choose profile, according to table in Q1013.
+  UInt trialBitDepthConstraint=maxBitDepth;
+  if (trialBitDepthConstraint<8)
+  {
+    trialBitDepthConstraint=8;
+  }
+  else if (trialBitDepthConstraint==9 || trialBitDepthConstraint==11)
+  {
+    trialBitDepthConstraint++;
+  }
+  else if (trialBitDepthConstraint>12)
+  {
+    trialBitDepthConstraint=16;
+  }
+
+  // both format and bit depth constraints are unspecified
+  if (bUsingExtendedPrecision || trialBitDepthConstraint==16)
+  {
+    bitDepthConstraint = 16;
+    chromaFormatConstraint = (!bIntraConstraintFlag && chromaFormat==CHROMA_400) ? CHROMA_400 : CHROMA_444;
+  }
+  else if (bUsingGeneralRExtTools)
+  {
+    if (chromaFormat == CHROMA_400 && !bIntraConstraintFlag)
+    {
+      bitDepthConstraint = 16;
+      chromaFormatConstraint = CHROMA_400;
+    }
+    else
+    {
+      bitDepthConstraint = trialBitDepthConstraint;
+      chromaFormatConstraint = CHROMA_444;
+    }
+  }
+  else if (chromaFormat == CHROMA_400)
+  {
+    if (bIntraConstraintFlag)
+    {
+      chromaFormatConstraint = CHROMA_420; // there is no intra 4:0:0 profile.
+      bitDepthConstraint     = trialBitDepthConstraint;
+    }
+    else
+    {
+      chromaFormatConstraint = CHROMA_400;
+      bitDepthConstraint     = trialBitDepthConstraint == 8 ? 8 : 12;
+    }
+  }
+  else
+  {
+    bitDepthConstraint = trialBitDepthConstraint;
+    chromaFormatConstraint = chromaFormat;
+    if (bUsingChromaQPAdjustment && chromaFormat == CHROMA_420)
+    {
+      chromaFormatConstraint = CHROMA_422; // 4:2:0 cannot use the chroma qp tool.
+    }
+    if (chromaFormatConstraint == CHROMA_422 && bitDepthConstraint == 8)
+    {
+      bitDepthConstraint = 10; // there is no 8-bit 4:2:2 profile.
+    }
+    if (chromaFormatConstraint == CHROMA_420 && !bIntraConstraintFlag)
+    {
+      bitDepthConstraint = 12; // there is no 8 or 10-bit 4:2:0 inter RExt profile.
+    }
+  }
+}
 // ====================================================================================================================
 // Public member functions
@@ -322,18 +761,18 @@
 {
   Bool do_help = false;
-  
-#if !H_MV
+
+#if !NH_MV
   string cfg_InputFile;
 #endif
   string cfg_BitstreamFile;
-#if !H_MV
+#if !NH_MV
   string cfg_ReconFile;
 #endif
-#if H_MV
+#if NH_MV
   vector<Int>   cfg_dimensionLength; 
   string        cfg_profiles;
   string        cfg_levels; 
   string        cfg_tiers; 
-#if H_3D 
+#if NH_3D
   cfg_dimensionLength.push_back( 2  );  // depth
   cfg_dimensionLength.push_back( 32 );  // texture 
@@ -343,30 +782,71 @@
 #endif
   string cfg_dQPFile;
-  string cfgColumnWidth;
-  string cfgRowHeight;
   string cfg_ScalingListFile;
-  string cfg_startOfCodedInterval;
-  string cfg_codedPivotValue;
-  string cfg_targetPivotValue;
+
+  Int tmpChromaFormat;
+  Int tmpInputChromaFormat;
+  Int tmpConstraintChromaFormat;
+  string inputColourSpaceConvert;
+#if NH_MV
+  std::vector<ExtendedProfileName> extendedProfiles;
+#else
+  ExtendedProfileName extendedProfile;
+#endif
+  Int saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];
+
+  // Multi-value input fields:                                // minval, maxval (incl), min_entries, max_entries (incl) [, default values, number of default values]
+  SMultiValueInput<UInt> cfg_ColumnWidth                     (0, std::numeric_limits<UInt>::max(), 0, std::numeric_limits<UInt>::max());
+  SMultiValueInput<UInt> cfg_RowHeight                       (0, std::numeric_limits<UInt>::max(), 0, std::numeric_limits<UInt>::max());
+  SMultiValueInput<Int>  cfg_startOfCodedInterval            (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
+  SMultiValueInput<Int>  cfg_codedPivotValue                 (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
+  SMultiValueInput<Int>  cfg_targetPivotValue                (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
+
+  const UInt defaultInputKneeCodes[3]  = { 600, 800, 900 };
+  const UInt defaultOutputKneeCodes[3] = { 100, 250, 450 };
+  SMultiValueInput<UInt> cfg_kneeSEIInputKneePointValue      (1,  999, 0, 999, defaultInputKneeCodes,  sizeof(defaultInputKneeCodes )/sizeof(UInt));
+  SMultiValueInput<UInt> cfg_kneeSEIOutputKneePointValue     (0, 1000, 0, 999, defaultOutputKneeCodes, sizeof(defaultOutputKneeCodes)/sizeof(UInt));
+  const Int defaultPrimaryCodes[6]     = { 0,50000, 0,0, 50000,0 };
+  const Int defaultWhitePointCode[2]   = { 16667, 16667 };
+  SMultiValueInput<Int>  cfg_DisplayPrimariesCode            (0, 50000, 3, 3, defaultPrimaryCodes,   sizeof(defaultPrimaryCodes  )/sizeof(Int));
+  SMultiValueInput<Int>  cfg_DisplayWhitePointCode           (0, 50000, 2, 2, defaultWhitePointCode, sizeof(defaultWhitePointCode)/sizeof(Int));
+
+  SMultiValueInput<Bool> cfg_timeCodeSeiTimeStampFlag        (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiNumUnitFieldBasedFlag(0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiCountingType         (0,  6, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiFullTimeStampFlag    (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiDiscontinuityFlag    (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiCntDroppedFlag       (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiNumberOfFrames       (0,511, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiSecondsValue         (0, 59, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiMinutesValue         (0, 59, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiHoursValue           (0, 23, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiSecondsFlag          (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiMinutesFlag          (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiHoursFlag            (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiTimeOffsetLength     (0, 31, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiTimeOffsetValue      (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, MAX_TIMECODE_SEI_SETS);
+  Int warnUnknowParameter = 0;
+
   po::Options opts;
   opts.addOptions()
-  ("help", do_help, false, "this help text")
-  ("c", po::parseConfigFile, "configuration file name")
-  
+  ("help",                                            do_help,                                          false, "this help text")
+  ("c",    po::parseConfigFile, "configuration file name")
+  ("WarnUnknowParameter,w",                           warnUnknowParameter,                                  0, "warn for unknown configuration parameters instead of failing")
+
   // File, I/O and source parameters
-#if H_MV
+#if NH_MV
   ("InputFile_%d,i_%d",       m_pchInputFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "original Yuv input file name %d")
 #else
-  ("InputFile,i",           cfg_InputFile,     string(""), "Original YUV input file name")
-#endif
-  ("BitstreamFile,b",       cfg_BitstreamFile, string(""), "Bitstream output file name")
-#if H_MV
+  ("InputFile,i",                                     cfg_InputFile,                               string(""), "Original YUV input file name")
+#endif
+  ("BitstreamFile,b",                                 cfg_BitstreamFile,                           string(""), "Bitstream output file name")
+#if NH_MV
   ("ReconFile_%d,o_%d",       m_pchReconFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "reconstructed Yuv output file name %d")
 #else
-  ("ReconFile,o",           cfg_ReconFile,     string(""), "Reconstructed YUV output file name")
-#endif
-#if H_MV
+  ("ReconFile,o",                                     cfg_ReconFile,                               string(""), "Reconstructed YUV output file name")
+#endif
+#if NH_MV
   ("NumberOfLayers",        m_numberOfLayers     , 1,                     "Number of layers")
-#if !H_3D
+#if !NH_3D
   ("ScalabilityMask",       m_scalabilityMask    , 2                    , "Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary")    
 #else
@@ -377,15 +857,10 @@
   ("ViewId",                m_viewId             , std::vector<Int>(1,0), "View Id per View Order Index")
   ("AuxId",                 m_auxId              , std::vector<Int>(1,0), "AuxId per layer")
-#if H_3D
+#if NH_3D
   ("DepthFlag",             m_depthFlag          , std::vector<Int>(1,0), "Depth Flag")
-#if H_3D_DIM
-  ("DLT",                   m_useDLT,           true,  "Depth lookup table")
-#endif
-#if H_3D
-#endif
 #endif
   ("TargetEncLayerIdList",  m_targetEncLayerIdList, std::vector<Int>(0,0), "LayerIds in Nuh to be encoded")  
-  ("LayerIdInNuh",          m_layerIdInNuh       , std::vector<Int>(1,0), "LayerId in Nuh")  
-  ("SplittingFlag",         m_splittingFlag      , false                , "Splitting Flag")    
+  ("LayerIdInNuh",          m_layerIdInNuh        , std::vector<Int>(1,0), "LayerId in Nuh")  
+  ("SplittingFlag",         m_splittingFlag       , false                , "Splitting Flag")    
 
   // Layer Sets + Output Layer Sets + Profile Tier Level
@@ -406,207 +881,246 @@
   ("DependencyTypes_%d",    m_dependencyTypes    , std::vector<Int>(0,0), MAX_NUM_LAYERS, "Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion")
 #endif
-  ("SourceWidth,-wdt",      m_iSourceWidth,        0, "Source picture width")
-  ("SourceHeight,-hgt",     m_iSourceHeight,       0, "Source picture height")
-  ("InputBitDepth",         m_inputBitDepthY,    8, "Bit-depth of input file")
-  ("OutputBitDepth",        m_outputBitDepthY,   0, "Bit-depth of output file (default:InternalBitDepth)")
-  ("InternalBitDepth",      m_internalBitDepthY, 0, "Bit-depth the codec operates at. (default:InputBitDepth)"
-                                                       "If different to InputBitDepth, source data will be converted")
-  ("InputBitDepthC",        m_inputBitDepthC,    0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
-  ("OutputBitDepthC",       m_outputBitDepthC,   0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
-  ("InternalBitDepthC",     m_internalBitDepthC, 0, "As per InternalBitDepth but for chroma component. (default:IntrenalBitDepth)")
-  ("ConformanceMode",       m_conformanceWindowMode,  0, "Deprecated alias of ConformanceWindowMode")
-  ("ConformanceWindowMode", m_conformanceWindowMode,  0, "Window conformance mode (0: no window, 1:automatic padding, 2:padding, 3:conformance")
-  ("HorizontalPadding,-pdx",m_aiPad[0],            0, "Horizontal source padding for conformance window mode 2")
-  ("VerticalPadding,-pdy",  m_aiPad[1],            0, "Vertical source padding for conformance window mode 2")
-  ("ConfLeft",              m_confWinLeft,            0, "Deprecated alias of ConfWinLeft")
-  ("ConfRight",             m_confWinRight,           0, "Deprecated alias of ConfWinRight")
-  ("ConfTop",               m_confWinTop,             0, "Deprecated alias of ConfWinTop")
-  ("ConfBottom",            m_confWinBottom,          0, "Deprecated alias of ConfWinBottom")
-  ("ConfWinLeft",           m_confWinLeft,            0, "Left offset for window conformance mode 3")
-  ("ConfWinRight",          m_confWinRight,           0, "Right offset for window conformance mode 3")
-  ("ConfWinTop",            m_confWinTop,             0, "Top offset for window conformance mode 3")
-  ("ConfWinBottom",         m_confWinBottom,          0, "Bottom offset for window conformance mode 3")
-  ("FrameRate,-fr",         m_iFrameRate,          0, "Frame rate")
-  ("FrameSkip,-fs",         m_FrameSkip,          0u, "Number of frames to skip at start of input YUV")
-  ("FramesToBeEncoded,f",   m_framesToBeEncoded,   0, "Number of frames to be encoded (default=all)")
+  ("SourceWidth,-wdt",                                m_iSourceWidth,                                       0, "Source picture width")
+  ("SourceHeight,-hgt",                               m_iSourceHeight,                                      0, "Source picture height")
+  ("InputBitDepth",                                   m_inputBitDepth[CHANNEL_TYPE_LUMA],                   8, "Bit-depth of input file")
+  ("OutputBitDepth",                                  m_outputBitDepth[CHANNEL_TYPE_LUMA],                  0, "Bit-depth of output file (default:InternalBitDepth)")
+  ("MSBExtendedBitDepth",                             m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA],             0, "bit depth of luma component after addition of MSBs of value 0 (used for synthesising High Dynamic Range source material). (default:InputBitDepth)")
+  ("InternalBitDepth",                                m_internalBitDepth[CHANNEL_TYPE_LUMA],                0, "Bit-depth the codec operates at. (default:MSBExtendedBitDepth). If different to MSBExtendedBitDepth, source data will be converted")
+  ("InputBitDepthC",                                  m_inputBitDepth[CHANNEL_TYPE_CHROMA],                 0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
+  ("OutputBitDepthC",                                 m_outputBitDepth[CHANNEL_TYPE_CHROMA],                0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
+  ("MSBExtendedBitDepthC",                            m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA],           0, "As per MSBExtendedBitDepth but for chroma component. (default:MSBExtendedBitDepth)")
+  ("InternalBitDepthC",                               m_internalBitDepth[CHANNEL_TYPE_CHROMA],              0, "As per InternalBitDepth but for chroma component. (default:InternalBitDepth)")
+  ("ExtendedPrecision",                               m_extendedPrecisionProcessingFlag,                false, "Increased internal accuracies to support high bit depths (not valid in V1 profiles)")
+  ("HighPrecisionPredictionWeighting",                m_highPrecisionOffsetsEnabledFlag,                false, "Use high precision option for weighted prediction (not valid in V1 profiles)")
+  ("InputColourSpaceConvert",                         inputColourSpaceConvert,                     string(""), "Colour space conversion to apply to input video. Permitted values are (empty string=UNCHANGED) " + getListOfColourSpaceConverts(true))
+  ("SNRInternalColourSpace",                          m_snrInternalColourSpace,                         false, "If true, then no colour space conversion is applied prior to SNR, otherwise inverse of input is applied.")
+  ("OutputInternalColourSpace",                       m_outputInternalColourSpace,                      false, "If true, then no colour space conversion is applied for reconstructed video, otherwise inverse of input is applied.")
+  ("InputChromaFormat",                               tmpInputChromaFormat,                               420, "InputChromaFormatIDC")
+  ("MSEBasedSequencePSNR",                            m_printMSEBasedSequencePSNR,                      false, "0 (default) emit sequence PSNR only as a linear average of the frame PSNRs, 1 = also emit a sequence PSNR based on an average of the frame MSEs")
+  ("PrintFrameMSE",                                   m_printFrameMSE,                                  false, "0 (default) emit only bit count and PSNRs for each frame, 1 = also emit MSE values")
+  ("PrintSequenceMSE",                                m_printSequenceMSE,                               false, "0 (default) emit only bit rate and PSNRs for the whole sequence, 1 = also emit MSE values")
+  ("CabacZeroWordPaddingEnabled",                     m_cabacZeroWordPaddingEnabled,                     true, "0 do not add conforming cabac-zero-words to bit streams, 1 (default) = add cabac-zero-words as required")
+  ("ChromaFormatIDC,-cf",                             tmpChromaFormat,                                      0, "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
+  ("ConformanceMode",                                 m_conformanceWindowMode,                              0, "Deprecated alias of ConformanceWindowMode")
+  ("ConformanceWindowMode",                           m_conformanceWindowMode,                              0, "Window conformance mode (0: no window, 1:automatic padding, 2:padding, 3:conformance")
+  ("HorizontalPadding,-pdx",                          m_aiPad[0],                                           0, "Horizontal source padding for conformance window mode 2")
+  ("VerticalPadding,-pdy",                            m_aiPad[1],                                           0, "Vertical source padding for conformance window mode 2")
+  ("ConfLeft",                                        m_confWinLeft,                                        0, "Deprecated alias of ConfWinLeft")
+  ("ConfRight",                                       m_confWinRight,                                       0, "Deprecated alias of ConfWinRight")
+  ("ConfTop",                                         m_confWinTop,                                         0, "Deprecated alias of ConfWinTop")
+  ("ConfBottom",                                      m_confWinBottom,                                      0, "Deprecated alias of ConfWinBottom")
+  ("ConfWinLeft",                                     m_confWinLeft,                                        0, "Left offset for window conformance mode 3")
+  ("ConfWinRight",                                    m_confWinRight,                                       0, "Right offset for window conformance mode 3")
+  ("ConfWinTop",                                      m_confWinTop,                                         0, "Top offset for window conformance mode 3")
+  ("ConfWinBottom",                                   m_confWinBottom,                                      0, "Bottom offset for window conformance mode 3")
+  ("FrameRate,-fr",                                   m_iFrameRate,                                         0, "Frame rate")
+  ("FrameSkip,-fs",                                   m_FrameSkip,                                         0u, "Number of frames to skip at start of input YUV")
+  ("FramesToBeEncoded,f",                             m_framesToBeEncoded,                                  0, "Number of frames to be encoded (default=all)")
+  ("ClipInputVideoToRec709Range",                     m_bClipInputVideoToRec709Range,                   false, "If true then clip input video to the Rec. 709 Range on loading when InternalBitDepth is less than MSBExtendedBitDepth")
+  ("ClipOutputVideoToRec709Range",                    m_bClipOutputVideoToRec709Range,                  false, "If true then clip output video to the Rec. 709 Range on saving when OutputBitDepth is less than InternalBitDepth")
+  ("SummaryOutFilename",                              m_summaryOutFilename,                          string(), "Filename to use for producing summary output file. If empty, do not produce a file.")
+  ("SummaryPicFilenameBase",                          m_summaryPicFilenameBase,                      string(), "Base filename to use for producing summary picture output files. The actual filenames used will have I.txt, P.txt and B.txt appended. If empty, do not produce a file.")
+  ("SummaryVerboseness",                              m_summaryVerboseness,                                0u, "Specifies the level of the verboseness of the text output")
 
   //Field coding parameters
-  ("FieldCoding", m_isField, false, "Signals if it's a field based coding")
-  ("TopFieldFirst, Tff", m_isTopFieldFirst, false, "In case of field based coding, signals whether if it's a top field first or not")
-  
+  ("FieldCoding",                                     m_isField,                                        false, "Signals if it's a field based coding")
+  ("TopFieldFirst, Tff",                              m_isTopFieldFirst,                                false, "In case of field based coding, signals whether if it's a top field first or not")
+  ("EfficientFieldIRAPEnabled",                       m_bEfficientFieldIRAPEnabled,                      true, "Enable to code fields in a specific, potentially more efficient, order.")
+  ("HarmonizeGopFirstFieldCoupleEnabled",             m_bHarmonizeGopFirstFieldCoupleEnabled,            true, "Enables harmonization of Gop first field couple")
+
   // Profile and level
-#if H_MV
-  ("Profile", cfg_profiles,   string(""),           "Profile in VpsProfileTierLevel (Indication only)")
-  ("Level",   cfg_levels ,    string(""),           "Level indication in VpsProfileTierLevel (Indication only)")
-  ("Tier",    cfg_tiers  ,    string(""),           "Tier indication in VpsProfileTierLevel (Indication only)")
-  ("InblFlag",m_inblFlag ,    std::vector<Bool>(0), "InblFlags in VpsProfileTierLevel (Indication only)" )
+#if NH_MV
+  ("Profile" ,                                        cfg_profiles,                                string(""), "Profile in VpsProfileTierLevel (Indication only)")
+  ("Level"   ,                                        cfg_levels ,                                 string(""), "Level indication in VpsProfileTierLevel (Indication only)")
+  ("Tier"    ,                                        cfg_tiers  ,                                 string(""), "Tier indication in VpsProfileTierLevel (Indication only)")
+  ("InblFlag",                                        m_inblFlag ,                       std::vector<Bool>(0), "InblFlags in VpsProfileTierLevel (Indication only)" )
 #else
-  ("Profile", m_profile,   Profile::NONE, "Profile to be used when encoding (Incomplete)")
-  ("Level",   m_level,     Level::NONE,   "Level limit to be used, eg 5.1 (Incomplete)")
-  ("Tier",    m_levelTier, Level::MAIN,   "Tier to use for interpretation of --Level")
-#endif
-  ("ProgressiveSource", m_progressiveSourceFlag, false, "Indicate that source is progressive")
-  ("InterlacedSource",  m_interlacedSourceFlag,  false, "Indicate that source is interlaced")
-  ("NonPackedSource",   m_nonPackedConstraintFlag, false, "Indicate that source does not contain frame packing")
-  ("FrameOnly",         m_frameOnlyConstraintFlag, false, "Indicate that the bitstream contains only frames")
-  
+  ("Profile",                                         extendedProfile,                                   NONE, "Profile name to use for encoding. Use main (for main), main10 (for main10), main-still-picture, main-RExt (for Range Extensions profile), any of the RExt specific profile names, or none")
+  ("Level",                                           m_level,                                    Level::NONE, "Level limit to be used, eg 5.1, or none")
+  ("Tier",                                            m_levelTier,                                Level::MAIN, "Tier to use for interpretation of --Level (main or high only)")
+#endif
+  ("MaxBitDepthConstraint",                           m_bitDepthConstraint,                                0u, "Bit depth to use for profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
+  ("MaxChromaFormatConstraint",                       tmpConstraintChromaFormat,                            0, "Chroma-format to use for the profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
+  ("IntraConstraintFlag",                             m_intraConstraintFlag,                            false, "Value of general_intra_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
+  ("OnePictureOnlyConstraintFlag",                    m_onePictureOnlyConstraintFlag,                   false, "Value of general_one_picture_only_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
+  ("LowerBitRateConstraintFlag",                      m_lowerBitRateConstraintFlag,                      true, "Value of general_lower_bit_rate_constraint_flag to use for RExt profiles")
+
+  ("ProgressiveSource",                               m_progressiveSourceFlag,                          false, "Indicate that source is progressive")
+  ("InterlacedSource",                                m_interlacedSourceFlag,                           false, "Indicate that source is interlaced")
+  ("NonPackedSource",                                 m_nonPackedConstraintFlag,                        false, "Indicate that source does not contain frame packing")
+  ("FrameOnly",                                       m_frameOnlyConstraintFlag,                        false, "Indicate that the bitstream contains only frames")
+
   // Unit definition parameters
-  ("MaxCUWidth",              m_uiMaxCUWidth,             64u)
-  ("MaxCUHeight",             m_uiMaxCUHeight,            64u)
+  ("MaxCUWidth",                                      m_uiMaxCUWidth,                                     64u)
+  ("MaxCUHeight",                                     m_uiMaxCUHeight,                                    64u)
   // todo: remove defaults from MaxCUSize
-  ("MaxCUSize,s",             m_uiMaxCUWidth,             64u, "Maximum CU size")
-  ("MaxCUSize,s",             m_uiMaxCUHeight,            64u, "Maximum CU size")
-  ("MaxPartitionDepth,h",     m_uiMaxCUDepth,              4u, "CU depth")
-  
-  ("QuadtreeTULog2MaxSize",   m_uiQuadtreeTULog2MaxSize,   6u, "Maximum TU size in logarithm base 2")
-  ("QuadtreeTULog2MinSize",   m_uiQuadtreeTULog2MinSize,   2u, "Minimum TU size in logarithm base 2")
-  
-  ("QuadtreeTUMaxDepthIntra", m_uiQuadtreeTUMaxDepthIntra, 1u, "Depth of TU tree for intra CUs")
-  ("QuadtreeTUMaxDepthInter", m_uiQuadtreeTUMaxDepthInter, 2u, "Depth of TU tree for inter CUs")
-#if H_MV  
+  ("MaxCUSize,s",                                     m_uiMaxCUWidth,                                     64u, "Maximum CU size")
+  ("MaxCUSize,s",                                     m_uiMaxCUHeight,                                    64u, "Maximum CU size")
+  ("MaxPartitionDepth,h",                             m_uiMaxCUDepth,                                      4u, "CU depth")
+
+  ("QuadtreeTULog2MaxSize",                           m_uiQuadtreeTULog2MaxSize,                           6u, "Maximum TU size in logarithm base 2")
+  ("QuadtreeTULog2MinSize",                           m_uiQuadtreeTULog2MinSize,                           2u, "Minimum TU size in logarithm base 2")
+
+  ("QuadtreeTUMaxDepthIntra",                         m_uiQuadtreeTUMaxDepthIntra,                         1u, "Depth of TU tree for intra CUs")
+  ("QuadtreeTUMaxDepthInter",                         m_uiQuadtreeTUMaxDepthInter,                         2u, "Depth of TU tree for inter CUs")
+#if NH_MV  
   // Coding structure parameters
-  ("IntraPeriod,-ip",         m_iIntraPeriod,std::vector<Int>(1,-1), "Intra period in frames, (-1: only first frame), per layer")
+  ("IntraPeriod,-ip",                                 m_iIntraPeriod,std::vector<Int>(1,-1)                  , "Intra period in frames, (-1: only first frame), per layer")
 #else
   // Coding structure paramters
-("IntraPeriod,-ip",         m_iIntraPeriod,              -1, "Intra period in frames, (-1: only first frame)")
-#endif
-#if ALLOW_RECOVERY_POINT_AS_RAP
-  ("DecodingRefreshType,-dr", m_iDecodingRefreshType,       0, "Intra refresh type (0:none 1:CRA 2:IDR 3:RecPointSEI)")
-#else
-  ("DecodingRefreshType,-dr", m_iDecodingRefreshType,       0, "Intra refresh type (0:none 1:CRA 2:IDR)")
-#endif
-  ("GOPSize,g",               m_iGOPSize,                   1, "GOP size of temporal structure")
-  // motion options
-  ("FastSearch",              m_iFastSearch,                1, "0:Full search  1:Diamond  2:PMVFAST")
-  ("SearchRange,-sr",         m_iSearchRange,              96, "Motion search range")
-#if H_MV
+  ("IntraPeriod,-ip",                                 m_iIntraPeriod,                                      -1, "Intra period in frames, (-1: only first frame)")
+#endif
+  ("DecodingRefreshType,-dr",                         m_iDecodingRefreshType,                               0, "Intra refresh type (0:none 1:CRA 2:IDR 3:RecPointSEI)")
+  ("GOPSize,g",                                       m_iGOPSize,                                           1, "GOP size of temporal structure")
+
+  // motion search options
+  ("DisableIntraInInter",                             m_bDisableIntraPUsInInterSlices,                  false, "Flag to disable intra PUs in inter slices")
+  ("FastSearch",                                      m_iFastSearch,                                        1, "0:Full search  1:Diamond  2:PMVFAST")
+  ("SearchRange,-sr",                                 m_iSearchRange,                                      96, "Motion search range")
+#if NH_MV
   ("DispSearchRangeRestriction",  m_bUseDisparitySearchRangeRestriction, false, "restrict disparity search range")
   ("VerticalDispSearchRange",     m_iVerticalDisparitySearchRange, 56, "vertical disparity search range")
 #endif
-  ("BipredSearchRange",       m_bipredSearchRange,          4, "Motion search range for bipred refinement")
-  ("HadamardME",              m_bUseHADME,               true, "Hadamard ME for fractional-pel")
-  ("ASR",                     m_bUseASR,                false, "Adaptive motion search range")
+  ("BipredSearchRange",                               m_bipredSearchRange,                                  4, "Motion search range for bipred refinement")
+  ("ClipForBiPredMEEnabled",                          m_bClipForBiPredMeEnabled,                        false, "Enables clipping in the Bi-Pred ME. It is disabled to reduce encoder run-time")
+  ("FastMEAssumingSmootherMVEnabled",                 m_bFastMEAssumingSmootherMVEnabled,                true, "Enables fast ME assuming a smoother MV.")
+
+  ("HadamardME",                                      m_bUseHADME,                                       true, "Hadamard ME for fractional-pel")
+  ("ASR",                                             m_bUseASR,                                        false, "Adaptive motion search range")
 
   // Mode decision parameters
-  ("LambdaModifier0,-LM0", m_adLambdaModifier[ 0 ], ( Double )1.0, "Lambda modifier for temporal layer 0")
-  ("LambdaModifier1,-LM1", m_adLambdaModifier[ 1 ], ( Double )1.0, "Lambda modifier for temporal layer 1")
-  ("LambdaModifier2,-LM2", m_adLambdaModifier[ 2 ], ( Double )1.0, "Lambda modifier for temporal layer 2")
-  ("LambdaModifier3,-LM3", m_adLambdaModifier[ 3 ], ( Double )1.0, "Lambda modifier for temporal layer 3")
-  ("LambdaModifier4,-LM4", m_adLambdaModifier[ 4 ], ( Double )1.0, "Lambda modifier for temporal layer 4")
-  ("LambdaModifier5,-LM5", m_adLambdaModifier[ 5 ], ( Double )1.0, "Lambda modifier for temporal layer 5")
-  ("LambdaModifier6,-LM6", m_adLambdaModifier[ 6 ], ( Double )1.0, "Lambda modifier for temporal layer 6")
+  ("LambdaModifier0,-LM0",                            m_adLambdaModifier[ 0 ],                  ( Double )1.0, "Lambda modifier for temporal layer 0")
+  ("LambdaModifier1,-LM1",                            m_adLambdaModifier[ 1 ],                  ( Double )1.0, "Lambda modifier for temporal layer 1")
+  ("LambdaModifier2,-LM2",                            m_adLambdaModifier[ 2 ],                  ( Double )1.0, "Lambda modifier for temporal layer 2")
+  ("LambdaModifier3,-LM3",                            m_adLambdaModifier[ 3 ],                  ( Double )1.0, "Lambda modifier for temporal layer 3")
+  ("LambdaModifier4,-LM4",                            m_adLambdaModifier[ 4 ],                  ( Double )1.0, "Lambda modifier for temporal layer 4")
+  ("LambdaModifier5,-LM5",                            m_adLambdaModifier[ 5 ],                  ( Double )1.0, "Lambda modifier for temporal layer 5")
+  ("LambdaModifier6,-LM6",                            m_adLambdaModifier[ 6 ],                  ( Double )1.0, "Lambda modifier for temporal layer 6")
 
   /* Quantization parameters */
-#if H_MV
+#if NH_MV
   ("QP,q",          m_fQP, std::vector<double>(1,30.0), "Qp values for each layer, if value is float, QP is switched once during encoding")
 #else
-  ("QP,q",          m_fQP,             30.0, "Qp value, if value is float, QP is switched once during encoding")
-#endif
-  ("DeltaQpRD,-dqr",m_uiDeltaQpRD,       0u, "max dQp offset for slice")
-  ("MaxDeltaQP,d",  m_iMaxDeltaQP,        0, "max dQp offset for block")
-  ("MaxCuDQPDepth,-dqd",  m_iMaxCuDQPDepth,        0, "max depth for a minimum CuDQP")
-
-  ("CbQpOffset,-cbqpofs",  m_cbQpOffset,        0, "Chroma Cb QP Offset")
-  ("CrQpOffset,-crqpofs",  m_crQpOffset,        0, "Chroma Cr QP Offset")
+  ("QP,q",                                            m_fQP,                                             30.0, "Qp value, if value is float, QP is switched once during encoding")
+#endif
+  ("DeltaQpRD,-dqr",                                  m_uiDeltaQpRD,                                       0u, "max dQp offset for slice")
+  ("MaxDeltaQP,d",                                    m_iMaxDeltaQP,                                        0, "max dQp offset for block")
+  ("MaxCuDQPDepth,-dqd",                              m_iMaxCuDQPDepth,                                     0, "max depth for a minimum CuDQP")
+  ("MaxCUChromaQpAdjustmentDepth",                    m_diffCuChromaQpOffsetDepth,                         -1, "Maximum depth for CU chroma Qp adjustment - set less than 0 to disable")
+
+  ("CbQpOffset,-cbqpofs",                             m_cbQpOffset,                                         0, "Chroma Cb QP Offset")
+  ("CrQpOffset,-crqpofs",                             m_crQpOffset,                                         0, "Chroma Cr QP Offset")
 
 #if ADAPTIVE_QP_SELECTION
-  ("AdaptiveQpSelection,-aqps",   m_bUseAdaptQpSelect,           false, "AdaptiveQpSelection")
-#endif
-
-  ("AdaptiveQP,-aq",                m_bUseAdaptiveQP,           false, "QP adaptation based on a psycho-visual model")
-  ("MaxQPAdaptationRange,-aqr",     m_iQPAdaptationRange,           6, "QP adaptation range")
-  ("dQPFile,m",                     cfg_dQPFile,           string(""), "dQP file name")
-  ("RDOQ",                          m_useRDOQ,                  true )
-  ("RDOQTS",                        m_useRDOQTS,                true )
-  ("RDpenalty",                     m_rdPenalty,                0,  "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disbaled  1:RD-penalty  2:maximum RD-penalty")
-  
+  ("AdaptiveQpSelection,-aqps",                       m_bUseAdaptQpSelect,                              false, "AdaptiveQpSelection")
+#endif
+
+  ("AdaptiveQP,-aq",                                  m_bUseAdaptiveQP,                                 false, "QP adaptation based on a psycho-visual model")
+  ("MaxQPAdaptationRange,-aqr",                       m_iQPAdaptationRange,                                 6, "QP adaptation range")
+  ("dQPFile,m",                                       cfg_dQPFile,                                 string(""), "dQP file name")
+  ("RDOQ",                                            m_useRDOQ,                                         true)
+  ("RDOQTS",                                          m_useRDOQTS,                                       true)
+#if T0196_SELECTIVE_RDOQ
+  ("SelectiveRDOQ",                                   m_useSelectiveRDOQ,                               false, "Enable selective RDOQ")
+#endif
+  ("RDpenalty",                                       m_rdPenalty,                                          0,  "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disabled  1:RD-penalty  2:maximum RD-penalty")
+
   // Deblocking filter parameters
-#if H_MV
-  ("LoopFilterDisable",              m_bLoopFilterDisable,             std::vector<Bool>(1,false), "Disable Loop Filter per Layer" )
+#if NH_MV
+  ("LoopFilterDisable",                               m_bLoopFilterDisable,                             std::vector<Bool>(1,false), "Disable Loop Filter per Layer" )
 #else
-  ("LoopFilterDisable",              m_bLoopFilterDisable,             false )
-#endif
-  ("LoopFilterOffsetInPPS",          m_loopFilterOffsetInPPS,          false )
-  ("LoopFilterBetaOffset_div2",      m_loopFilterBetaOffsetDiv2,           0 )
-  ("LoopFilterTcOffset_div2",        m_loopFilterTcOffsetDiv2,             0 )
-  ("DeblockingFilterControlPresent", m_DeblockingFilterControlPresent, false )
-  ("DeblockingFilterMetric",         m_DeblockingFilterMetric,         false )
-
-#if H_3D_IC
-  ("IlluCompEnable",           m_abUseIC, true, "Enable illumination compensation")
-  ("IlluCompLowLatencyEnc",    m_bUseLowLatencyICEnc, false, "Enable low-latency illumination compensation encoding")
-#endif
+  ("LoopFilterDisable",                               m_bLoopFilterDisable,                             false)
+#endif
+  ("LoopFilterOffsetInPPS",                           m_loopFilterOffsetInPPS,                           true)
+  ("LoopFilterBetaOffset_div2",                       m_loopFilterBetaOffsetDiv2,                           0)
+  ("LoopFilterTcOffset_div2",                         m_loopFilterTcOffsetDiv2,                             0)
+  ("DeblockingFilterMetric",                          m_DeblockingFilterMetric,                         false)
+
   // Coding tools
-  ("AMP",                      m_enableAMP,                 true,  "Enable asymmetric motion partitions")
-  ("TransformSkip",            m_useTransformSkip,          false, "Intra transform skipping")
-  ("TransformSkipFast",        m_useTransformSkipFast,      false, "Fast intra transform skipping")
-#if H_MV
+  ("AMP",                                             m_enableAMP,                                       true, "Enable asymmetric motion partitions")
+  ("CrossComponentPrediction",                        m_crossComponentPredictionEnabledFlag,            false, "Enable the use of cross-component prediction (not valid in V1 profiles)")
+  ("ReconBasedCrossCPredictionEstimate",              m_reconBasedCrossCPredictionEstimate,             false, "When determining the alpha value for cross-component prediction, use the decoded residual rather than the pre-transform encoder-side residual")
+  ("SaoLumaOffsetBitShift",                           saoOffsetBitShift[CHANNEL_TYPE_LUMA],                 0, "Specify the luma SAO bit-shift. If negative, automatically calculate a suitable value based upon bit depth and initial QP")
+  ("SaoChromaOffsetBitShift",                         saoOffsetBitShift[CHANNEL_TYPE_CHROMA],               0, "Specify the chroma SAO bit-shift. If negative, automatically calculate a suitable value based upon bit depth and initial QP")
+  ("TransformSkip",                                   m_useTransformSkip,                               false, "Intra transform skipping")
+  ("TransformSkipFast",                               m_useTransformSkipFast,                           false, "Fast intra transform skipping")
+  ("TransformSkipLog2MaxSize",                        m_log2MaxTransformSkipBlockSize,                     2U, "Specify transform-skip maximum size. Minimum 2. (not valid in V1 profiles)")
+  ("ImplicitResidualDPCM",                            m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT],        false, "Enable implicitly signalled residual DPCM for intra (also known as sample-adaptive intra predict) (not valid in V1 profiles)")
+  ("ExplicitResidualDPCM",                            m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT],        false, "Enable explicitly signalled residual DPCM for inter (not valid in V1 profiles)")
+  ("ResidualRotation",                                m_transformSkipRotationEnabledFlag,               false, "Enable rotation of transform-skipped and transquant-bypassed TUs through 180 degrees prior to entropy coding (not valid in V1 profiles)")
+  ("SingleSignificanceMapContext",                    m_transformSkipContextEnabledFlag,                false, "Enable, for transform-skipped and transquant-bypassed TUs, the selection of a single significance map context variable for all coefficients (not valid in V1 profiles)")
+  ("GolombRiceParameterAdaptation",                   m_persistentRiceAdaptationEnabledFlag,            false, "Enable the adaptation of the Golomb-Rice parameter over the course of each slice")
+  ("AlignCABACBeforeBypass",                          m_cabacBypassAlignmentEnabledFlag,                false, "Align the CABAC engine to a defined fraction of a bit prior to coding bypass data. Must be 1 in high bit rate profile, 0 otherwise" )
+#if NH_MV
   ("SAO",                      m_bUseSAO, std::vector<Bool>(1,true), "Enable Sample Adaptive Offset per Layer")
 #else
-  ("SAO",                      m_bUseSAO,                   true,  "Enable Sample Adaptive Offset")
-#endif
-  ("MaxNumOffsetsPerPic",      m_maxNumOffsetsPerPic,       2048,  "Max number of SAO offset per picture (Default: 2048)")   
-  ("SAOLcuBoundary",           m_saoLcuBoundary,            false, "0: right/bottom LCU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
-  ("SliceMode",                m_sliceMode,                0,     "0: Disable all Recon slice limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
-  ("SliceArgument",            m_sliceArgument,            0,     "Depending on SliceMode being:"
-                                                                   "\t1: max number of CTUs per slice"
-                                                                   "\t2: max number of bytes per slice"
-                                                                   "\t3: max number of tiles per slice")
-  ("SliceSegmentMode",         m_sliceSegmentMode,       0,     "0: Disable all slice segment limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
-  ("SliceSegmentArgument",     m_sliceSegmentArgument,   0,     "Depending on SliceSegmentMode being:"
-                                                                   "\t1: max number of CTUs per slice segment"
-                                                                   "\t2: max number of bytes per slice segment"
-                                                                   "\t3: max number of tiles per slice segment")
-  ("LFCrossSliceBoundaryFlag", m_bLFCrossSliceBoundaryFlag, true)
-
-  ("ConstrainedIntraPred",     m_bUseConstrainedIntraPred,  false, "Constrained Intra Prediction")
-
-  ("PCMEnabledFlag",           m_usePCM,                    false)
-  ("PCMLog2MaxSize",           m_pcmLog2MaxSize,            5u)
-  ("PCMLog2MinSize",           m_uiPCMLog2MinSize,          3u)
-  ("PCMInputBitDepthFlag",     m_bPCMInputBitDepthFlag,     true)
-  ("PCMFilterDisableFlag",     m_bPCMFilterDisableFlag,    false)
-
-  ("WeightedPredP,-wpP",          m_useWeightedPred,               false,      "Use weighted prediction in P slices")
-  ("WeightedPredB,-wpB",          m_useWeightedBiPred,             false,      "Use weighted (bidirectional) prediction in B slices")
-  ("Log2ParallelMergeLevel",      m_log2ParallelMergeLevel,     2u,          "Parallel merge estimation region")
-
-  //deprecated copies of renamed tile parameters
-  ("UniformSpacingIdc",           m_tileUniformSpacingFlag,        false,      "deprecated alias of TileUniformSpacing")
-  ("ColumnWidthArray",            cfgColumnWidth,                  string(""), "deprecated alias of TileColumnWidthArray")
-  ("RowHeightArray",              cfgRowHeight,                    string(""), "deprecated alias of TileRowHeightArray")
-
-  ("TileUniformSpacing",          m_tileUniformSpacingFlag,        false,      "Indicates that tile columns and rows are distributed uniformly")
-  ("NumTileColumnsMinus1",        m_numTileColumnsMinus1,          0,          "Number of tile columns in a picture minus 1")
-  ("NumTileRowsMinus1",           m_numTileRowsMinus1,             0,          "Number of rows in a picture minus 1")
-  ("TileColumnWidthArray",        cfgColumnWidth,                  string(""), "Array containing tile column width values in units of LCU")
-  ("TileRowHeightArray",          cfgRowHeight,                    string(""), "Array containing tile row height values in units of LCU")
-  ("LFCrossTileBoundaryFlag",      m_bLFCrossTileBoundaryFlag,             true,          "1: cross-tile-boundary loop filtering. 0:non-cross-tile-boundary loop filtering")
-  ("WaveFrontSynchro",            m_iWaveFrontSynchro,             0,          "0: no synchro; 1 synchro with TR; 2 TRR etc")
-  ("ScalingList",                 m_useScalingListId,              0,          "0: no scaling list, 1: default scaling lists, 2: scaling lists specified in ScalingListFile")
-  ("ScalingListFile",             cfg_ScalingListFile,             string(""), "Scaling list file name")
-  ("SignHideFlag,-SBH",                m_signHideFlag, 1)
-  ("MaxNumMergeCand",             m_maxNumMergeCand,             5u,         "Maximum number of merge candidates")
-
+  ("SAO",                                             m_bUseSAO,                                         true, "Enable Sample Adaptive Offset")
+#endif
+  ("TestSAODisableAtPictureLevel",                    m_bTestSAODisableAtPictureLevel,                  false, "Enables the testing of disabling SAO at the picture level after having analysed all blocks")
+  ("SaoEncodingRate",                                 m_saoEncodingRate,                                 0.75, "When >0 SAO early picture termination is enabled for luma and chroma")
+  ("SaoEncodingRateChroma",                           m_saoEncodingRateChroma,                            0.5, "The SAO early picture termination rate to use for chroma (when m_SaoEncodingRate is >0). If <=0, use results for luma")
+  ("MaxNumOffsetsPerPic",                             m_maxNumOffsetsPerPic,                             2048, "Max number of SAO offset per picture (Default: 2048)")
+  ("SAOLcuBoundary",                                  m_saoCtuBoundary,                                 false, "0: right/bottom CTU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
+  ("SliceMode",                                       m_sliceMode,                                          0, "0: Disable all Recon slice limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
+  ("SliceArgument",                                   m_sliceArgument,                                      0, "Depending on SliceMode being:"
+                                                                                                               "\t1: max number of CTUs per slice"
+                                                                                                               "\t2: max number of bytes per slice"
+                                                                                                               "\t3: max number of tiles per slice")
+  ("SliceSegmentMode",                                m_sliceSegmentMode,                                   0, "0: Disable all slice segment limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
+  ("SliceSegmentArgument",                            m_sliceSegmentArgument,                               0, "Depending on SliceSegmentMode being:"
+                                                                                                               "\t1: max number of CTUs per slice segment"
+                                                                                                               "\t2: max number of bytes per slice segment"
+                                                                                                               "\t3: max number of tiles per slice segment")
+  ("LFCrossSliceBoundaryFlag",                        m_bLFCrossSliceBoundaryFlag,                       true)
+
+  ("ConstrainedIntraPred",                            m_bUseConstrainedIntraPred,                       false, "Constrained Intra Prediction")
+  ("FastUDIUseMPMEnabled",                            m_bFastUDIUseMPMEnabled,                           true, "If enabled, adapt intra direction search, accounting for MPM")
+  ("FastMEForGenBLowDelayEnabled",                    m_bFastMEForGenBLowDelayEnabled,                   true, "If enabled use a fast ME for generalised B Low Delay slices")
+  ("UseBLambdaForNonKeyLowDelayPictures",             m_bUseBLambdaForNonKeyLowDelayPictures,            true, "Enables use of B-Lambda for non-key low-delay pictures")
+  ("PCMEnabledFlag",                                  m_usePCM,                                         false)
+  ("PCMLog2MaxSize",                                  m_pcmLog2MaxSize,                                    5u)
+  ("PCMLog2MinSize",                                  m_uiPCMLog2MinSize,                                  3u)
+
+  ("PCMInputBitDepthFlag",                            m_bPCMInputBitDepthFlag,                           true)
+  ("PCMFilterDisableFlag",                            m_bPCMFilterDisableFlag,                          false)
+  ("IntraReferenceSmoothing",                         m_enableIntraReferenceSmoothing,                   true, "0: Disable use of intra reference smoothing. 1: Enable use of intra reference smoothing (not valid in V1 profiles)")
+  ("WeightedPredP,-wpP",                              m_useWeightedPred,                                false, "Use weighted prediction in P slices")
+  ("WeightedPredB,-wpB",                              m_useWeightedBiPred,                              false, "Use weighted (bidirectional) prediction in B slices")
+  ("Log2ParallelMergeLevel",                          m_log2ParallelMergeLevel,                            2u, "Parallel merge estimation region")
+    //deprecated copies of renamed tile parameters
+  ("UniformSpacingIdc",                               m_tileUniformSpacingFlag,                         false,      "deprecated alias of TileUniformSpacing")
+  ("ColumnWidthArray",                                cfg_ColumnWidth,                        cfg_ColumnWidth, "deprecated alias of TileColumnWidthArray")
+  ("RowHeightArray",                                  cfg_RowHeight,                            cfg_RowHeight, "deprecated alias of TileRowHeightArray")
+
+  ("TileUniformSpacing",                              m_tileUniformSpacingFlag,                         false,      "Indicates that tile columns and rows are distributed uniformly")
+  ("NumTileColumnsMinus1",                            m_numTileColumnsMinus1,                               0,          "Number of tile columns in a picture minus 1")
+  ("NumTileRowsMinus1",                               m_numTileRowsMinus1,                                  0,          "Number of rows in a picture minus 1")
+  ("TileColumnWidthArray",                            cfg_ColumnWidth,                        cfg_ColumnWidth, "Array containing tile column width values in units of CTU")
+  ("TileRowHeightArray",                              cfg_RowHeight,                            cfg_RowHeight, "Array containing tile row height values in units of CTU")
+  ("LFCrossTileBoundaryFlag",                         m_bLFCrossTileBoundaryFlag,                        true, "1: cross-tile-boundary loop filtering. 0:non-cross-tile-boundary loop filtering")
+  ("WaveFrontSynchro",                                m_iWaveFrontSynchro,                                  0, "0: no synchro; 1 synchro with top-right-right")
+  ("ScalingList",                                     m_useScalingListId,                    SCALING_LIST_OFF, "0/off: no scaling list, 1/default: default scaling lists, 2/file: scaling lists specified in ScalingListFile")
+  ("ScalingListFile",                                 cfg_ScalingListFile,                         string(""), "Scaling list file name. Use an empty string to produce help.")
+  ("SignHideFlag,-SBH",                               m_signHideFlag,                                    true)
+  ("MaxNumMergeCand",                                 m_maxNumMergeCand,                                   5u, "Maximum number of merge candidates")
   /* Misc. */
-  ("SEIDecodedPictureHash",       m_decodedPictureHashSEIEnabled, 0, "Control generation of decode picture hash SEI messages\n"
-                                                                    "\t3: checksum\n"
-                                                                    "\t2: CRC\n"
-                                                                    "\t1: use MD5\n"
-                                                                    "\t0: disable")
-  ("SEIpictureDigest",            m_decodedPictureHashSEIEnabled, 0, "deprecated alias for SEIDecodedPictureHash")
-  ("TMVPMode", m_TMVPModeId, 1, "TMVP mode 0: TMVP disable for all slices. 1: TMVP enable for all slices (default) 2: TMVP enable for certain slices only")
-  ("FEN", m_bUseFastEnc, false, "fast encoder setting")
-  ("ECU", m_bUseEarlyCU, false, "Early CU setting") 
-  ("FDM", m_useFastDecisionForMerge, true, "Fast decision for Merge RD Cost") 
-  ("CFM", m_bUseCbfFastMode, false, "Cbf fast mode setting")
-  ("ESD", m_useEarlySkipDetection, false, "Early SKIP detection setting")
-  ( "RateControl",         m_RCEnableRateControl,   false, "Rate control: enable rate control" )
-  ( "TargetBitrate",       m_RCTargetBitrate,           0, "Rate control: target bitrate" )
-  ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit,     0, "Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation" )
-  ( "LCULevelRateControl", m_RCLCULevelRC,           true, "Rate control: true: LCU level RC; false: picture level RC" )
-  ( "RCLCUSeparateModel",  m_RCUseLCUSeparateModel,  true, "Rate control: use LCU level separate R-lambda model" )
-  ( "InitialQP",           m_RCInitialQP,               0, "Rate control: initial QP" )
-  ( "RCForceIntraQP",      m_RCForceIntraQP,        false, "Rate control: force intra QP to be equal to initial QP" )
+  ("SEIDecodedPictureHash",                           m_decodedPictureHashSEIEnabled,                       0, "Control generation of decode picture hash SEI messages\n"
+                                                                                                               "\t3: checksum\n"
+                                                                                                               "\t2: CRC\n"
+                                                                                                               "\t1: use MD5\n"
+                                                                                                               "\t0: disable")
+  ("TMVPMode",                                        m_TMVPModeId,                                         1, "TMVP mode 0: TMVP disable for all slices. 1: TMVP enable for all slices (default) 2: TMVP enable for certain slices only")
+  ("FEN",                                             m_bUseFastEnc,                                    false, "fast encoder setting")
+  ("ECU",                                             m_bUseEarlyCU,                                    false, "Early CU setting")
+  ("FDM",                                             m_useFastDecisionForMerge,                         true, "Fast decision for Merge RD Cost")
+  ("CFM",                                             m_bUseCbfFastMode,                                false, "Cbf fast mode setting")
+  ("ESD",                                             m_useEarlySkipDetection,                          false, "Early SKIP detection setting")
+  ( "RateControl",                                    m_RCEnableRateControl,                            false, "Rate control: enable rate control" )
+  ( "TargetBitrate",                                  m_RCTargetBitrate,                                    0, "Rate control: target bit-rate" )
+  ( "KeepHierarchicalBit",                            m_RCKeepHierarchicalBit,                              0, "Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation" )
+  ( "LCULevelRateControl",                            m_RCLCULevelRC,                                    true, "Rate control: true: CTU level RC; false: picture level RC" )
+  ( "RCLCUSeparateModel",                             m_RCUseLCUSeparateModel,                           true, "Rate control: use CTU level separate R-lambda model" )
+  ( "InitialQP",                                      m_RCInitialQP,                                        0, "Rate control: initial QP" )
+  ( "RCForceIntraQP",                                 m_RCForceIntraQP,                                 false, "Rate control: force intra QP to be equal to initial QP" )
 
 #if KWU_RC_VIEWRC_E0227
@@ -617,5 +1131,5 @@
   ("DepthMADPred, -dm", m_depthMADPred, (UInt)0, "Depth based MAD prediction on/off")
 #endif
-#if H_MV
+#if NH_MV
 // A lot of this stuff could should actually be derived by the encoder.
   // VPS VUI
@@ -626,6 +1140,6 @@
   ("BitRatePresentVpsFlag"       , m_bitRatePresentVpsFlag       , false                                           , "BitRatePresentVpsFlag       ")
   ("PicRatePresentVpsFlag"       , m_picRatePresentVpsFlag       , false                                           , "PicRatePresentVpsFlag       ")
-  ("BitRatePresentFlag"          , m_bitRatePresentFlag          , std::vector< Bool >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "BitRatePresentFlag per sub layer for the N-th layer set")
-  ("PicRatePresentFlag"          , m_picRatePresentFlag          , std::vector< Bool >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "PicRatePresentFlag per sub layer for the N-th layer set")
+  ("BitRatePresentFlag"          , m_bitRatePresentFlag          , BoolAry1d(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "BitRatePresentFlag per sub layer for the N-th layer set")
+  ("PicRatePresentFlag"          , m_picRatePresentFlag          , BoolAry1d(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "PicRatePresentFlag per sub layer for the N-th layer set")
   ("AvgBitRate"                  , m_avgBitRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "AvgBitRate         per sub layer for the N-th layer set")
   ("MaxBitRate"                  , m_maxBitRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "MaxBitRate         per sub layer for the N-th layer set")
@@ -633,12 +1147,12 @@
   ("AvgPicRate"                  , m_avgPicRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "AvgPicRate         per sub layer for the N-th layer set")
   ("TilesNotInUseFlag"            , m_tilesNotInUseFlag            , true                                          , "TilesNotInUseFlag            ")
-  ("TilesInUseFlag"               , m_tilesInUseFlag               , std::vector< Bool >(1,false)                   , "TilesInUseFlag               ")
-  ("LoopFilterNotAcrossTilesFlag" , m_loopFilterNotAcrossTilesFlag , std::vector< Bool >(1,false)                  , "LoopFilterNotAcrossTilesFlag ")
+  ("TilesInUseFlag"               , m_tilesInUseFlag               , BoolAry1d(1,false)                   , "TilesInUseFlag               ")
+  ("LoopFilterNotAcrossTilesFlag" , m_loopFilterNotAcrossTilesFlag , BoolAry1d(1,false)                  , "LoopFilterNotAcrossTilesFlag ")
   ("WppNotInUseFlag"              , m_wppNotInUseFlag              , true                                          , "WppNotInUseFlag              ")
-  ("WppInUseFlag"                 , m_wppInUseFlag                 , std::vector< Bool >(1,0)                      , "WppInUseFlag                 ")
-  ("TileBoundariesAlignedFlag"   , m_tileBoundariesAlignedFlag   , std::vector< Bool >(1,0)  ,MAX_NUM_LAYERS       , "TileBoundariesAlignedFlag    per direct reference for the N-th layer")
+  ("WppInUseFlag"                 , m_wppInUseFlag                 , BoolAry1d(1,0)                      , "WppInUseFlag                 ")
+  ("TileBoundariesAlignedFlag"   , m_tileBoundariesAlignedFlag   , BoolAry1d(1,0)  ,MAX_NUM_LAYERS       , "TileBoundariesAlignedFlag    per direct reference for the N-th layer")
   ("IlpRestrictedRefLayersFlag"  , m_ilpRestrictedRefLayersFlag  , false                                           , "IlpRestrictedRefLayersFlag")
   ("MinSpatialSegmentOffsetPlus1", m_minSpatialSegmentOffsetPlus1, std::vector< Int  >(1,0)  ,MAX_NUM_LAYERS       , "MinSpatialSegmentOffsetPlus1 per direct reference for the N-th layer")
-  ("CtuBasedOffsetEnabledFlag"   , m_ctuBasedOffsetEnabledFlag   , std::vector< Bool >(1,0)  ,MAX_NUM_LAYERS       , "CtuBasedOffsetEnabledFlag    per direct reference for the N-th layer")
+  ("CtuBasedOffsetEnabledFlag"   , m_ctuBasedOffsetEnabledFlag   , BoolAry1d(1,0)  ,MAX_NUM_LAYERS       , "CtuBasedOffsetEnabledFlag    per direct reference for the N-th layer")
   ("MinHorizontalCtuOffsetPlus1" , m_minHorizontalCtuOffsetPlus1 , std::vector< Int  >(1,0)  ,MAX_NUM_LAYERS       , "MinHorizontalCtuOffsetPlus1  per direct reference for the N-th layer")
   ("SingleLayerForNonIrapFlag", m_singleLayerForNonIrapFlag, false                                          , "SingleLayerForNonIrapFlag")
@@ -646,155 +1160,208 @@
 #endif
 
-  ("TransquantBypassEnableFlag", m_TransquantBypassEnableFlag, false, "transquant_bypass_enable_flag indicator in PPS")
-  ("CUTransquantBypassFlagForce", m_CUTransquantBypassFlagForce, false, "Force transquant bypass mode, when transquant_bypass_enable_flag is enabled")
-  ("RecalculateQPAccordingToLambda", m_recalculateQPAccordingToLambda, false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
-  ("StrongIntraSmoothing,-sis",      m_useStrongIntraSmoothing,           true, "Enable strong intra smoothing for 32x32 blocks")
-  ("SEIActiveParameterSets",         m_activeParameterSetsSEIEnabled,          0, "Enable generation of active parameter sets SEI messages")
-  ("VuiParametersPresent,-vui",      m_vuiParametersPresentFlag,           false, "Enable generation of vui_parameters()")
-  ("AspectRatioInfoPresent",         m_aspectRatioInfoPresentFlag,         false, "Signals whether aspect_ratio_idc is present")
-  ("AspectRatioIdc",                 m_aspectRatioIdc,                         0, "aspect_ratio_idc")
-  ("SarWidth",                       m_sarWidth,                               0, "horizontal size of the sample aspect ratio")
-  ("SarHeight",                      m_sarHeight,                              0, "vertical size of the sample aspect ratio")
-  ("OverscanInfoPresent",            m_overscanInfoPresentFlag,            false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
-  ("OverscanAppropriate",            m_overscanAppropriateFlag,            false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
-  ("VideoSignalTypePresent",         m_videoSignalTypePresentFlag,         false, "Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present")
-  ("VideoFormat",                    m_videoFormat,                            5, "Indicates representation of pictures")
-  ("VideoFullRange",                 m_videoFullRangeFlag,                 false, "Indicates the black level and range of luma and chroma signals")
-  ("ColourDescriptionPresent",       m_colourDescriptionPresentFlag,       false, "Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present")
-  ("ColourPrimaries",                m_colourPrimaries,                        2, "Indicates chromaticity coordinates of the source primaries")
-  ("TransferCharacteristics",        m_transferCharacteristics,                2, "Indicates the opto-electronic transfer characteristics of the source")
-  ("MatrixCoefficients",             m_matrixCoefficients,                     2, "Describes the matrix coefficients used in deriving luma and chroma from RGB primaries")
-  ("ChromaLocInfoPresent",           m_chromaLocInfoPresentFlag,           false, "Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present")
-  ("ChromaSampleLocTypeTopField",    m_chromaSampleLocTypeTopField,            0, "Specifies the location of chroma samples for top field")
-  ("ChromaSampleLocTypeBottomField", m_chromaSampleLocTypeBottomField,         0, "Specifies the location of chroma samples for bottom field")
-  ("NeutralChromaIndication",        m_neutralChromaIndicationFlag,        false, "Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)")
-  ("DefaultDisplayWindowFlag",       m_defaultDisplayWindowFlag,           false, "Indicates the presence of the Default Window parameters")
-  ("DefDispWinLeftOffset",           m_defDispWinLeftOffset,                   0, "Specifies the left offset of the default display window from the conformance window")
-  ("DefDispWinRightOffset",          m_defDispWinRightOffset,                  0, "Specifies the right offset of the default display window from the conformance window")
-  ("DefDispWinTopOffset",            m_defDispWinTopOffset,                    0, "Specifies the top offset of the default display window from the conformance window")
-  ("DefDispWinBottomOffset",         m_defDispWinBottomOffset,                 0, "Specifies the bottom offset of the default display window from the conformance window")
-  ("FrameFieldInfoPresentFlag",      m_frameFieldInfoPresentFlag,               false, "Indicates that pic_struct and field coding related values are present in picture timing SEI messages")
-  ("PocProportionalToTimingFlag",   m_pocProportionalToTimingFlag,         false, "Indicates that the POC value is proportional to the output time w.r.t. first picture in CVS")
-  ("NumTicksPocDiffOneMinus1",      m_numTicksPocDiffOneMinus1,                0, "Number of ticks minus 1 that for a POC difference of one")
-  ("BitstreamRestriction",           m_bitstreamRestrictionFlag,           false, "Signals whether bitstream restriction parameters are present")
-  ("TilesFixedStructure",            m_tilesFixedStructureFlag,            false, "Indicates that each active picture parameter set has the same values of the syntax elements related to tiles")
-  ("MotionVectorsOverPicBoundaries", m_motionVectorsOverPicBoundariesFlag, false, "Indicates that no samples outside the picture boundaries are used for inter prediction")
-  ("MaxBytesPerPicDenom",            m_maxBytesPerPicDenom,                    2, "Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture")
-  ("MaxBitsPerMinCuDenom",           m_maxBitsPerMinCuDenom,                   1, "Indicates an upper bound for the number of bits of coding_unit() data")
-  ("Log2MaxMvLengthHorizontal",      m_log2MaxMvLengthHorizontal,             15, "Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units")
-  ("Log2MaxMvLengthVertical",        m_log2MaxMvLengthVertical,               15, "Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units")
-  ("SEIRecoveryPoint",               m_recoveryPointSEIEnabled,                0, "Control generation of recovery point SEI messages")
-  ("SEIBufferingPeriod",             m_bufferingPeriodSEIEnabled,              0, "Control generation of buffering period SEI messages")
-  ("SEIPictureTiming",               m_pictureTimingSEIEnabled,                0, "Control generation of picture timing SEI messages")
-  ("SEIToneMappingInfo",                       m_toneMappingInfoSEIEnabled,    false, "Control generation of Tone Mapping SEI messages")
-  ("SEIToneMapId",                             m_toneMapId,                        0, "Specifies Id of Tone Mapping SEI message for a given session")
-  ("SEIToneMapCancelFlag",                     m_toneMapCancelFlag,            false, "Indicates that Tone Mapping SEI message cancels the persistance or follows")
-  ("SEIToneMapPersistenceFlag",                m_toneMapPersistenceFlag,        true, "Specifies the persistence of the Tone Mapping SEI message")
-  ("SEIToneMapCodedDataBitDepth",              m_toneMapCodedDataBitDepth,         8, "Specifies Coded Data BitDepth of Tone Mapping SEI messages")
-  ("SEIToneMapTargetBitDepth",                 m_toneMapTargetBitDepth,            8, "Specifies Output BitDepth of Tome mapping function")
-  ("SEIToneMapModelId",                        m_toneMapModelId,                   0, "Specifies Model utilized for mapping coded data into target_bit_depth range\n"
-                                                                                      "\t0:  linear mapping with clipping\n"
-                                                                                      "\t1:  sigmoidal mapping\n"
-                                                                                      "\t2:  user-defined table mapping\n"
-                                                                                      "\t3:  piece-wise linear mapping\n"
-                                                                                      "\t4:  luminance dynamic range information ")
-  ("SEIToneMapMinValue",                              m_toneMapMinValue,                          0, "Specifies the minimum value in mode 0")
-  ("SEIToneMapMaxValue",                              m_toneMapMaxValue,                       1023, "Specifies the maxmum value in mode 0")
-  ("SEIToneMapSigmoidMidpoint",                       m_sigmoidMidpoint,                        512, "Specifies the centre point in mode 1")
-  ("SEIToneMapSigmoidWidth",                          m_sigmoidWidth,                           960, "Specifies the distance between 5% and 95% values of the target_bit_depth in mode 1")
-  ("SEIToneMapStartOfCodedInterval",                  cfg_startOfCodedInterval,          string(""), "Array of user-defined mapping table")
-  ("SEIToneMapNumPivots",                             m_numPivots,                                0, "Specifies the number of pivot points in mode 3")
-  ("SEIToneMapCodedPivotValue",                       cfg_codedPivotValue,               string(""), "Array of pivot point")
-  ("SEIToneMapTargetPivotValue",                      cfg_targetPivotValue,              string(""), "Array of pivot point")
-  ("SEIToneMapCameraIsoSpeedIdc",                     m_cameraIsoSpeedIdc,                        0, "Indicates the camera ISO speed for daylight illumination")
-  ("SEIToneMapCameraIsoSpeedValue",                   m_cameraIsoSpeedValue,                    400, "Specifies the camera ISO speed for daylight illumination of Extended_ISO")
-  ("SEIToneMapExposureIndexIdc",                      m_exposureIndexIdc,                         0, "Indicates the exposure index setting of the camera")
-  ("SEIToneMapExposureIndexValue",                    m_exposureIndexValue,                     400, "Specifies the exposure index setting of the cameran of Extended_ISO")
-  ("SEIToneMapExposureCompensationValueSignFlag",     m_exposureCompensationValueSignFlag,        0, "Specifies the sign of ExposureCompensationValue")
-  ("SEIToneMapExposureCompensationValueNumerator",    m_exposureCompensationValueNumerator,       0, "Specifies the numerator of ExposureCompensationValue")
-  ("SEIToneMapExposureCompensationValueDenomIdc",     m_exposureCompensationValueDenomIdc,        2, "Specifies the denominator of ExposureCompensationValue")
-  ("SEIToneMapRefScreenLuminanceWhite",               m_refScreenLuminanceWhite,                350, "Specifies reference screen brightness setting in units of candela per square metre")
-  ("SEIToneMapExtendedRangeWhiteLevel",               m_extendedRangeWhiteLevel,                800, "Indicates the luminance dynamic range")
-  ("SEIToneMapNominalBlackLevelLumaCodeValue",        m_nominalBlackLevelLumaCodeValue,          16, "Specifies luma sample value of the nominal black level assigned decoded pictures")
-  ("SEIToneMapNominalWhiteLevelLumaCodeValue",        m_nominalWhiteLevelLumaCodeValue,         235, "Specifies luma sample value of the nominal white level assigned decoded pictures")
-  ("SEIToneMapExtendedWhiteLevelLumaCodeValue",       m_extendedWhiteLevelLumaCodeValue,        300, "Specifies luma sample value of the extended dynamic range assigned decoded pictures")
-  ("SEIFramePacking",                m_framePackingSEIEnabled,                 0, "Control generation of frame packing SEI messages")
-  ("SEIFramePackingType",            m_framePackingSEIType,                    0, "Define frame packing arrangement\n"
-                                                                                  "\t0: checkerboard - pixels alternatively represent either frames\n"
-                                                                                  "\t1: column alternation - frames are interlaced by column\n"
-                                                                                  "\t2: row alternation - frames are interlaced by row\n"
-                                                                                  "\t3: side by side - frames are displayed horizontally\n"
-                                                                                  "\t4: top bottom - frames are displayed vertically\n"
-                                                                                  "\t5: frame alternation - one frame is alternated with the other")
-  ("SEIFramePackingId",              m_framePackingSEIId,                      0, "Id of frame packing SEI message for a given session")
-  ("SEIFramePackingQuincunx",        m_framePackingSEIQuincunx,                0, "Indicate the presence of a Quincunx type video frame")
-  ("SEIFramePackingInterpretation",  m_framePackingSEIInterpretation,          0, "Indicate the interpretation of the frame pair\n"
-                                                                                  "\t0: unspecified\n"
-                                                                                  "\t1: stereo pair, frame0 represents left view\n"
-                                                                                  "\t2: stereo pair, frame0 represents right view")
-  ("SEIDisplayOrientation",          m_displayOrientationSEIAngle,             0, "Control generation of display orientation SEI messages\n"
-                                                              "\tN: 0 < N < (2^16 - 1) enable display orientation SEI message with anticlockwise_rotation = N and display_orientation_repetition_period = 1\n"
-                                                              "\t0: disable")
-  ("SEITemporalLevel0Index",         m_temporalLevel0IndexSEIEnabled,          0, "Control generation of temporal level 0 index SEI messages")
-  ("SEIGradualDecodingRefreshInfo",  m_gradualDecodingRefreshInfoEnabled,      0, "Control generation of gradual decoding refresh information SEI message")
-  ("SEIDecodingUnitInfo",             m_decodingUnitInfoSEIEnabled,                       0, "Control generation of decoding unit information SEI message.")
-  ("SEISOPDescription",              m_SOPDescriptionSEIEnabled,              0, "Control generation of SOP description SEI messages")
-  ("SEIScalableNesting",             m_scalableNestingSEIEnabled,              0, "Control generation of scalable nesting SEI messages")
-#if H_MV
-  ("SubBitstreamPropSEIEnabled",              m_subBistreamPropSEIEnabled,    false                     ,"Enable signaling of sub-bitstream property SEI message")
-  ("SEISubBitstreamNumAdditionalSubStreams",  m_sbPropNumAdditionalSubStreams,0, "Number of substreams for which additional information is signalled")
-  ("SEISubBitstreamSubBitstreamMode",         m_sbPropSubBitstreamMode,       std::vector< Int  >(1,0)  ,"Specifies mode of generation of the i-th sub-bitstream (0 or 1)")
-  ("SEISubBitstreamOutputLayerSetIdxToVps",   m_sbPropOutputLayerSetIdxToVps, std::vector< Int  >(1,0)  ,"Specifies output layer set index of the i-th sub-bitstream ")
-  ("SEISubBitstreamHighestSublayerId",        m_sbPropHighestSublayerId,      std::vector< Int  >(1,0)  ,"Specifies highest TemporalId of the i-th sub-bitstream")
-  ("SEISubBitstreamAvgBitRate",               m_sbPropAvgBitRate,             std::vector< Int  >(1,0)  ,"Specifies average bit rate of the i-th sub-bitstream")
-  ("SEISubBitstreamMaxBitRate",               m_sbPropMaxBitRate,             std::vector< Int  >(1,0)  ,"Specifies maximum bit rate of the i-th sub-bitstream")
-
-  ("OutputVpsInfo",                           m_outputVpsInfo,                false                     ,"Output information about the layer dependencies and layer sets")
-#endif
-#if H_3D
-  ("CameraParameterFile,cpf", m_pchCameraParameterFile,    (Char *) 0, "Camera Parameter File Name")
-  ("BaseViewCameraNumbers" ,  m_pchBaseViewCameraNumbers,  (Char *) 0, "Numbers of base views")
-  ("CodedCamParsPrecision",   m_iCodedCamParPrecision,  STD_CAM_PARAMETERS_PRECISION, "precision for coding of camera parameters (in units of 2^(-x) luma samples)" )
-/* View Synthesis Optimization */
-
-#if H_3D_VSO
-  ("VSOConfig",                       m_pchVSOConfig            , (Char *) 0    , "VSO configuration")
-  ("VSO",                             m_bUseVSO                 , false         , "Use VSO" )    
-  ("VSOMode",                         m_uiVSOMode               , (UInt)   4    , "VSO Mode")
-  ("LambdaScaleVSO",                  m_dLambdaScaleVSO         , (Double) 1    , "Lambda Scaling for VSO")
-  ("VSOLSTable",                      m_bVSOLSTable             , true          , "Depth QP dependent video/depth rate allocation by Lagrange multiplier" )      
-  ("ForceLambdaScaleVSO",             m_bForceLambdaScaleVSO    , false         , "Force using Lambda Scale VSO also in non-VSO-Mode")
-  ("AllowNegDist",                    m_bAllowNegDist           , true          , "Allow negative Distortion in VSO")
-  
-  ("UseEstimatedVSD",                 m_bUseEstimatedVSD        , true          , "Model based VSD estimation instead of rendering based for some encoder decisions" )      
-  ("VSOEarlySkip",                    m_bVSOEarlySkip           , true          , "Early skip of VSO computation if synthesis error assumed to be zero" )      
-  
-  ("WVSO",                            m_bUseWVSO                , true          , "Use depth fidelity term for VSO" )
-  ("VSOWeight",                       m_iVSOWeight              , 10            , "Synthesized View Distortion Change weight" )
-  ("VSDWeight",                       m_iVSDWeight              , 1             , "View Synthesis Distortion estimate weight" )
-  ("DWeight",                         m_iDWeight                , 1             , "Depth Distortion weight" )
-
+  ("TransquantBypassEnableFlag",                      m_TransquantBypassEnableFlag,                     false, "transquant_bypass_enable_flag indicator in PPS")
+  ("CUTransquantBypassFlagForce",                     m_CUTransquantBypassFlagForce,                    false, "Force transquant bypass mode, when transquant_bypass_enable_flag is enabled")
+  ("CostMode",                                        m_costMode,                         COST_STANDARD_LOSSY, "Use alternative cost functions: choose between 'lossy', 'sequence_level_lossless', 'lossless' (which forces QP to " MACRO_TO_STRING(LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP) ") and 'mixed_lossless_lossy' (which used QP'=" MACRO_TO_STRING(LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME) " for pre-estimates of transquant-bypass blocks).")
+  ("RecalculateQPAccordingToLambda",                  m_recalculateQPAccordingToLambda,                 false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
+  ("StrongIntraSmoothing,-sis",                       m_useStrongIntraSmoothing,                         true, "Enable strong intra smoothing for 32x32 blocks")
+  ("SEIActiveParameterSets",                          m_activeParameterSetsSEIEnabled,                      0, "Enable generation of active parameter sets SEI messages")
+  ("VuiParametersPresent,-vui",                       m_vuiParametersPresentFlag,                       false, "Enable generation of vui_parameters()")
+  ("AspectRatioInfoPresent",                          m_aspectRatioInfoPresentFlag,                     false, "Signals whether aspect_ratio_idc is present")
+  ("AspectRatioIdc",                                  m_aspectRatioIdc,                                     0, "aspect_ratio_idc")
+  ("SarWidth",                                        m_sarWidth,                                           0, "horizontal size of the sample aspect ratio")
+  ("SarHeight",                                       m_sarHeight,                                          0, "vertical size of the sample aspect ratio")
+  ("OverscanInfoPresent",                             m_overscanInfoPresentFlag,                        false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
+  ("OverscanAppropriate",                             m_overscanAppropriateFlag,                        false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
+  ("VideoSignalTypePresent",                          m_videoSignalTypePresentFlag,                     false, "Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present")
+  ("VideoFormat",                                     m_videoFormat,                                        5, "Indicates representation of pictures")
+  ("VideoFullRange",                                  m_videoFullRangeFlag,                             false, "Indicates the black level and range of luma and chroma signals")
+  ("ColourDescriptionPresent",                        m_colourDescriptionPresentFlag,                   false, "Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present")
+  ("ColourPrimaries",                                 m_colourPrimaries,                                    2, "Indicates chromaticity coordinates of the source primaries")
+  ("TransferCharacteristics",                         m_transferCharacteristics,                            2, "Indicates the opto-electronic transfer characteristics of the source")
+  ("MatrixCoefficients",                              m_matrixCoefficients,                                 2, "Describes the matrix coefficients used in deriving luma and chroma from RGB primaries")
+  ("ChromaLocInfoPresent",                            m_chromaLocInfoPresentFlag,                       false, "Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present")
+  ("ChromaSampleLocTypeTopField",                     m_chromaSampleLocTypeTopField,                        0, "Specifies the location of chroma samples for top field")
+  ("ChromaSampleLocTypeBottomField",                  m_chromaSampleLocTypeBottomField,                     0, "Specifies the location of chroma samples for bottom field")
+  ("NeutralChromaIndication",                         m_neutralChromaIndicationFlag,                    false, "Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)")
+  ("DefaultDisplayWindowFlag",                        m_defaultDisplayWindowFlag,                       false, "Indicates the presence of the Default Window parameters")
+  ("DefDispWinLeftOffset",                            m_defDispWinLeftOffset,                               0, "Specifies the left offset of the default display window from the conformance window")
+  ("DefDispWinRightOffset",                           m_defDispWinRightOffset,                              0, "Specifies the right offset of the default display window from the conformance window")
+  ("DefDispWinTopOffset",                             m_defDispWinTopOffset,                                0, "Specifies the top offset of the default display window from the conformance window")
+  ("DefDispWinBottomOffset",                          m_defDispWinBottomOffset,                             0, "Specifies the bottom offset of the default display window from the conformance window")
+  ("FrameFieldInfoPresentFlag",                       m_frameFieldInfoPresentFlag,                      false, "Indicates that pic_struct and field coding related values are present in picture timing SEI messages")
+  ("PocProportionalToTimingFlag",                     m_pocProportionalToTimingFlag,                    false, "Indicates that the POC value is proportional to the output time w.r.t. first picture in CVS")
+  ("NumTicksPocDiffOneMinus1",                        m_numTicksPocDiffOneMinus1,                           0, "Number of ticks minus 1 that for a POC difference of one")
+  ("BitstreamRestriction",                            m_bitstreamRestrictionFlag,                       false, "Signals whether bitstream restriction parameters are present")
+  ("TilesFixedStructure",                             m_tilesFixedStructureFlag,                        false, "Indicates that each active picture parameter set has the same values of the syntax elements related to tiles")
+  ("MotionVectorsOverPicBoundaries",                  m_motionVectorsOverPicBoundariesFlag,             false, "Indicates that no samples outside the picture boundaries are used for inter prediction")
+  ("MaxBytesPerPicDenom",                             m_maxBytesPerPicDenom,                                2, "Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture")
+  ("MaxBitsPerMinCuDenom",                            m_maxBitsPerMinCuDenom,                               1, "Indicates an upper bound for the number of bits of coding_unit() data")
+  ("Log2MaxMvLengthHorizontal",                       m_log2MaxMvLengthHorizontal,                         15, "Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units")
+  ("Log2MaxMvLengthVertical",                         m_log2MaxMvLengthVertical,                           15, "Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units")
+  ("SEIRecoveryPoint",                                m_recoveryPointSEIEnabled,                            0, "Control generation of recovery point SEI messages")
+  ("SEIBufferingPeriod",                              m_bufferingPeriodSEIEnabled,                          0, "Control generation of buffering period SEI messages")
+  ("SEIPictureTiming",                                m_pictureTimingSEIEnabled,                            0, "Control generation of picture timing SEI messages")
+  ("SEIToneMappingInfo",                              m_toneMappingInfoSEIEnabled,                      false, "Control generation of Tone Mapping SEI messages")
+  ("SEIToneMapId",                                    m_toneMapId,                                          0, "Specifies Id of Tone Mapping SEI message for a given session")
+  ("SEIToneMapCancelFlag",                            m_toneMapCancelFlag,                              false, "Indicates that Tone Mapping SEI message cancels the persistence or follows")
+  ("SEIToneMapPersistenceFlag",                       m_toneMapPersistenceFlag,                          true, "Specifies the persistence of the Tone Mapping SEI message")
+  ("SEIToneMapCodedDataBitDepth",                     m_toneMapCodedDataBitDepth,                           8, "Specifies Coded Data BitDepth of Tone Mapping SEI messages")
+  ("SEIToneMapTargetBitDepth",                        m_toneMapTargetBitDepth,                              8, "Specifies Output BitDepth of Tone mapping function")
+  ("SEIToneMapModelId",                               m_toneMapModelId,                                     0, "Specifies Model utilized for mapping coded data into target_bit_depth range\n"
+                                                                                                               "\t0:  linear mapping with clipping\n"
+                                                                                                               "\t1:  sigmoidal mapping\n"
+                                                                                                               "\t2:  user-defined table mapping\n"
+                                                                                                               "\t3:  piece-wise linear mapping\n"
+                                                                                                               "\t4:  luminance dynamic range information ")
+  ("SEIToneMapMinValue",                              m_toneMapMinValue,                                    0, "Specifies the minimum value in mode 0")
+  ("SEIToneMapMaxValue",                              m_toneMapMaxValue,                                 1023, "Specifies the maximum value in mode 0")
+  ("SEIToneMapSigmoidMidpoint",                       m_sigmoidMidpoint,                                  512, "Specifies the centre point in mode 1")
+  ("SEIToneMapSigmoidWidth",                          m_sigmoidWidth,                                     960, "Specifies the distance between 5% and 95% values of the target_bit_depth in mode 1")
+  ("SEIToneMapStartOfCodedInterval",                  cfg_startOfCodedInterval,      cfg_startOfCodedInterval, "Array of user-defined mapping table")
+  ("SEIToneMapNumPivots",                             m_numPivots,                                          0, "Specifies the number of pivot points in mode 3")
+  ("SEIToneMapCodedPivotValue",                       cfg_codedPivotValue,                cfg_codedPivotValue, "Array of pivot point")
+  ("SEIToneMapTargetPivotValue",                      cfg_targetPivotValue,              cfg_targetPivotValue, "Array of pivot point")
+  ("SEIToneMapCameraIsoSpeedIdc",                     m_cameraIsoSpeedIdc,                                  0, "Indicates the camera ISO speed for daylight illumination")
+  ("SEIToneMapCameraIsoSpeedValue",                   m_cameraIsoSpeedValue,                              400, "Specifies the camera ISO speed for daylight illumination of Extended_ISO")
+  ("SEIToneMapExposureIndexIdc",                      m_exposureIndexIdc,                                   0, "Indicates the exposure index setting of the camera")
+  ("SEIToneMapExposureIndexValue",                    m_exposureIndexValue,                               400, "Specifies the exposure index setting of the camera of Extended_ISO")
+  ("SEIToneMapExposureCompensationValueSignFlag",     m_exposureCompensationValueSignFlag,               false, "Specifies the sign of ExposureCompensationValue")
+  ("SEIToneMapExposureCompensationValueNumerator",    m_exposureCompensationValueNumerator,                 0, "Specifies the numerator of ExposureCompensationValue")
+  ("SEIToneMapExposureCompensationValueDenomIdc",     m_exposureCompensationValueDenomIdc,                  2, "Specifies the denominator of ExposureCompensationValue")
+  ("SEIToneMapRefScreenLuminanceWhite",               m_refScreenLuminanceWhite,                          350, "Specifies reference screen brightness setting in units of candela per square metre")
+  ("SEIToneMapExtendedRangeWhiteLevel",               m_extendedRangeWhiteLevel,                          800, "Indicates the luminance dynamic range")
+  ("SEIToneMapNominalBlackLevelLumaCodeValue",        m_nominalBlackLevelLumaCodeValue,                    16, "Specifies luma sample value of the nominal black level assigned decoded pictures")
+  ("SEIToneMapNominalWhiteLevelLumaCodeValue",        m_nominalWhiteLevelLumaCodeValue,                   235, "Specifies luma sample value of the nominal white level assigned decoded pictures")
+  ("SEIToneMapExtendedWhiteLevelLumaCodeValue",       m_extendedWhiteLevelLumaCodeValue,                  300, "Specifies luma sample value of the extended dynamic range assigned decoded pictures")
+  ("SEIChromaSamplingFilterHint",                     m_chromaSamplingFilterSEIenabled,                 false, "Control generation of the chroma sampling filter hint SEI message")
+  ("SEIChromaSamplingHorizontalFilterType",           m_chromaSamplingHorFilterIdc,                         2, "Defines the Index of the chroma sampling horizontal filter\n"
+                                                                                                               "\t0: unspecified  - Chroma filter is unknown or is determined by the application"
+                                                                                                               "\t1: User-defined - Filter coefficients are specified in the chroma sampling filter hint SEI message"
+                                                                                                               "\t2: Standards-defined - ITU-T Rec. T.800 | ISO/IEC15444-1, 5/3 filter")
+  ("SEIChromaSamplingVerticalFilterType",             m_chromaSamplingVerFilterIdc,                         2, "Defines the Index of the chroma sampling vertical filter\n"
+                                                                                                               "\t0: unspecified  - Chroma filter is unknown or is determined by the application"
+                                                                                                               "\t1: User-defined - Filter coefficients are specified in the chroma sampling filter hint SEI message"
+                                                                                                               "\t2: Standards-defined - ITU-T Rec. T.800 | ISO/IEC15444-1, 5/3 filter")
+  ("SEIFramePacking",                                 m_framePackingSEIEnabled,                             0, "Control generation of frame packing SEI messages")
+  ("SEIFramePackingType",                             m_framePackingSEIType,                                0, "Define frame packing arrangement\n"
+                                                                                                               "\t3: side by side - frames are displayed horizontally\n"
+                                                                                                               "\t4: top bottom - frames are displayed vertically\n"
+                                                                                                               "\t5: frame alternation - one frame is alternated with the other")
+  ("SEIFramePackingId",                               m_framePackingSEIId,                                  0, "Id of frame packing SEI message for a given session")
+  ("SEIFramePackingQuincunx",                         m_framePackingSEIQuincunx,                            0, "Indicate the presence of a Quincunx type video frame")
+  ("SEIFramePackingInterpretation",                   m_framePackingSEIInterpretation,                      0, "Indicate the interpretation of the frame pair\n"
+                                                                                                               "\t0: unspecified\n"
+                                                                                                               "\t1: stereo pair, frame0 represents left view\n"
+                                                                                                               "\t2: stereo pair, frame0 represents right view")
+  ("SEISegmentedRectFramePacking",                    m_segmentedRectFramePackingSEIEnabled,                0, "Controls generation of segmented rectangular frame packing SEI messages")
+  ("SEISegmentedRectFramePackingCancel",              m_segmentedRectFramePackingSEICancel,             false, "If equal to 1, cancels the persistence of any previous SRFPA SEI message")
+  ("SEISegmentedRectFramePackingType",                m_segmentedRectFramePackingSEIType,                   0, "Specifies the arrangement of the frames in the reconstructed picture")
+  ("SEISegmentedRectFramePackingPersistence",         m_segmentedRectFramePackingSEIPersistence,        false, "If equal to 0, the SEI applies to the current frame only")
+  ("SEIDisplayOrientation",                           m_displayOrientationSEIAngle,                         0, "Control generation of display orientation SEI messages\n"
+                                                                                                               "\tN: 0 < N < (2^16 - 1) enable display orientation SEI message with anticlockwise_rotation = N and display_orientation_repetition_period = 1\n"
+                                                                                                               "\t0: disable")
+  ("SEITemporalLevel0Index",                          m_temporalLevel0IndexSEIEnabled,                      0, "Control generation of temporal level 0 index SEI messages")
+  ("SEIGradualDecodingRefreshInfo",                   m_gradualDecodingRefreshInfoEnabled,                  0, "Control generation of gradual decoding refresh information SEI message")
+  ("SEINoDisplay",                                    m_noDisplaySEITLayer,                                 0, "Control generation of no display SEI message\n"
+                                                                                                               "\tN: 0 < N enable no display SEI message for temporal layer N or higher\n"
+                                                                                                               "\t0: disable")
+  ("SEIDecodingUnitInfo",                             m_decodingUnitInfoSEIEnabled,                         0, "Control generation of decoding unit information SEI message.")
+  ("SEISOPDescription",                               m_SOPDescriptionSEIEnabled,                           0, "Control generation of SOP description SEI messages")
+  ("SEIScalableNesting",                              m_scalableNestingSEIEnabled,                          0, "Control generation of scalable nesting SEI messages")
+  ("SEITempMotionConstrainedTileSets",                m_tmctsSEIEnabled,                                false, "Control generation of temporal motion constrained tile sets SEI message")
+  ("SEITimeCodeEnabled",                              m_timeCodeSEIEnabled,                             false, "Control generation of time code information SEI message")
+  ("SEITimeCodeNumClockTs",                           m_timeCodeSEINumTs,                                   0, "Number of clock time sets [0..3]")
+  ("SEITimeCodeTimeStampFlag",                        cfg_timeCodeSeiTimeStampFlag,          cfg_timeCodeSeiTimeStampFlag,         "Time stamp flag associated to each time set")
+  ("SEITimeCodeFieldBasedFlag",                       cfg_timeCodeSeiNumUnitFieldBasedFlag,  cfg_timeCodeSeiNumUnitFieldBasedFlag, "Field based flag associated to each time set")
+  ("SEITimeCodeCountingType",                         cfg_timeCodeSeiCountingType,           cfg_timeCodeSeiCountingType,          "Counting type associated to each time set")
+  ("SEITimeCodeFullTsFlag",                           cfg_timeCodeSeiFullTimeStampFlag,      cfg_timeCodeSeiFullTimeStampFlag,     "Full time stamp flag associated to each time set")
+  ("SEITimeCodeDiscontinuityFlag",                    cfg_timeCodeSeiDiscontinuityFlag,      cfg_timeCodeSeiDiscontinuityFlag,     "Discontinuity flag associated to each time set")
+  ("SEITimeCodeCntDroppedFlag",                       cfg_timeCodeSeiCntDroppedFlag,         cfg_timeCodeSeiCntDroppedFlag,        "Counter dropped flag associated to each time set")
+  ("SEITimeCodeNumFrames",                            cfg_timeCodeSeiNumberOfFrames,         cfg_timeCodeSeiNumberOfFrames,        "Number of frames associated to each time set")
+  ("SEITimeCodeSecondsValue",                         cfg_timeCodeSeiSecondsValue,           cfg_timeCodeSeiSecondsValue,          "Seconds value for each time set")
+  ("SEITimeCodeMinutesValue",                         cfg_timeCodeSeiMinutesValue,           cfg_timeCodeSeiMinutesValue,          "Minutes value for each time set")
+  ("SEITimeCodeHoursValue",                           cfg_timeCodeSeiHoursValue,             cfg_timeCodeSeiHoursValue,            "Hours value for each time set")
+  ("SEITimeCodeSecondsFlag",                          cfg_timeCodeSeiSecondsFlag,            cfg_timeCodeSeiSecondsFlag,           "Flag to signal seconds value presence in each time set")
+  ("SEITimeCodeMinutesFlag",                          cfg_timeCodeSeiMinutesFlag,            cfg_timeCodeSeiMinutesFlag,           "Flag to signal minutes value presence in each time set")
+  ("SEITimeCodeHoursFlag",                            cfg_timeCodeSeiHoursFlag,              cfg_timeCodeSeiHoursFlag,             "Flag to signal hours value presence in each time set")
+  ("SEITimeCodeOffsetLength",                         cfg_timeCodeSeiTimeOffsetLength,       cfg_timeCodeSeiTimeOffsetLength,      "Time offset length associated to each time set")
+  ("SEITimeCodeTimeOffset",                           cfg_timeCodeSeiTimeOffsetValue,        cfg_timeCodeSeiTimeOffsetValue,       "Time offset associated to each time set")
+  ("SEIKneeFunctionInfo",                             m_kneeSEIEnabled,                                 false, "Control generation of Knee function SEI messages")
+  ("SEIKneeFunctionId",                               m_kneeSEIId,                                          0, "Specifies Id of Knee function SEI message for a given session")
+  ("SEIKneeFunctionCancelFlag",                       m_kneeSEICancelFlag,                              false, "Indicates that Knee function SEI message cancels the persistence or follows")
+  ("SEIKneeFunctionPersistenceFlag",                  m_kneeSEIPersistenceFlag,                          true, "Specifies the persistence of the Knee function SEI message")
+  ("SEIKneeFunctionInputDrange",                      m_kneeSEIInputDrange,                              1000, "Specifies the peak luminance level for the input picture of Knee function SEI messages")
+  ("SEIKneeFunctionInputDispLuminance",               m_kneeSEIInputDispLuminance,                        100, "Specifies the expected display brightness for the input picture of Knee function SEI messages")
+  ("SEIKneeFunctionOutputDrange",                     m_kneeSEIOutputDrange,                             4000, "Specifies the peak luminance level for the output picture of Knee function SEI messages")
+  ("SEIKneeFunctionOutputDispLuminance",              m_kneeSEIOutputDispLuminance,                       800, "Specifies the expected display brightness for the output picture of Knee function SEI messages")
+  ("SEIKneeFunctionNumKneePointsMinus1",              m_kneeSEINumKneePointsMinus1,                         2, "Specifies the number of knee points - 1")
+  ("SEIKneeFunctionInputKneePointValue",              cfg_kneeSEIInputKneePointValue,   cfg_kneeSEIInputKneePointValue, "Array of input knee point")
+  ("SEIKneeFunctionOutputKneePointValue",             cfg_kneeSEIOutputKneePointValue, cfg_kneeSEIOutputKneePointValue, "Array of output knee point")
+  ("SEIMasteringDisplayColourVolume",                 m_masteringDisplay.colourVolumeSEIEnabled,         false, "Control generation of mastering display colour volume SEI messages")
+  ("SEIMasteringDisplayMaxLuminance",                 m_masteringDisplay.maxLuminance,                  10000u, "Specifies the mastering display maximum luminance value in units of 1/10000 candela per square metre (32-bit code value)")
+  ("SEIMasteringDisplayMinLuminance",                 m_masteringDisplay.minLuminance,                      0u, "Specifies the mastering display minimum luminance value in units of 1/10000 candela per square metre (32-bit code value)")
+  ("SEIMasteringDisplayPrimaries",                    cfg_DisplayPrimariesCode,       cfg_DisplayPrimariesCode, "Mastering display primaries for all three colour planes in CIE xy coordinates in increments of 1/50000 (results in the ranges 0 to 50000 inclusive)")
+  ("SEIMasteringDisplayWhitePoint",                   cfg_DisplayWhitePointCode,     cfg_DisplayWhitePointCode, "Mastering display white point CIE xy coordinates in normalised increments of 1/50000 (e.g. 0.333 = 16667)")
+#if NH_MV
+  ("SubBitstreamPropSEIEnabled",                      m_subBistreamPropSEIEnabled,    false                     ,"Enable signaling of sub-bitstream property SEI message")
+  ("SEISubBitstreamNumAdditionalSubStreams",          m_sbPropNumAdditionalSubStreams,0                         ,"Number of substreams for which additional information is signalled")
+  ("SEISubBitstreamSubBitstreamMode",                 m_sbPropSubBitstreamMode,       std::vector< Int  >(1,0)  ,"Specifies mode of generation of the i-th sub-bitstream (0 or 1)")
+  ("SEISubBitstreamOutputLayerSetIdxToVps",           m_sbPropOutputLayerSetIdxToVps, std::vector< Int  >(1,0)  ,"Specifies output layer set index of the i-th sub-bitstream ")
+  ("SEISubBitstreamHighestSublayerId",                m_sbPropHighestSublayerId,      std::vector< Int  >(1,0)  ,"Specifies highest TemporalId of the i-th sub-bitstream")
+  ("SEISubBitstreamAvgBitRate",                       m_sbPropAvgBitRate,             std::vector< Int  >(1,0)  ,"Specifies average bit rate of the i-th sub-bitstream")
+  ("SEISubBitstreamMaxBitRate",                       m_sbPropMaxBitRate,             std::vector< Int  >(1,0)  ,"Specifies maximum bit rate of the i-th sub-bitstream")
+
+  ("OutputVpsInfo",                                   m_outputVpsInfo,                false                     ,"Output information about the layer dependencies and layer sets")
+#endif
+#if NH_3D
+/* Camera parameters */  
+  ("Depth420OutputFlag",                              m_depth420OutputFlag,           true                     , "Output depth layers in 4:2:0 ") 
+  ("CameraParameterFile,cpf",                         m_pchCameraParameterFile,    (Char *) 0,                    "Camera Parameter File Name")
+  ("BaseViewCameraNumbers",                           m_pchBaseViewCameraNumbers,  (Char *) 0,                    "Numbers of base views")
+  ("CodedCamParsPrecision",                           m_iCodedCamParPrecision,      STD_CAM_PARAMETERS_PRECISION, "precision for coding of camera parameters (in units of 2^(-x) luma samples)" )
+
+#if NH_3D_VSO
+  /* View Synthesis Optimization */
+  ("VSOConfig",                                       m_pchVSOConfig            , (Char *) 0                    ,"VSO configuration")
+  ("VSO",                                             m_bUseVSO                 , false                         ,"Use VSO" )    
+  ("VSOMode",                                         m_uiVSOMode               , (UInt)   4                    ,"VSO Mode")
+  ("LambdaScaleVSO",                                  m_dLambdaScaleVSO         , (Double) 1                    ,"Lambda Scaling for VSO")
+  ("VSOLSTable",                                      m_bVSOLSTable             , true                          ,"Depth QP dependent video/depth rate allocation by Lagrange multiplier" )      
+  ("ForceLambdaScaleVSO",                             m_bForceLambdaScaleVSO    , false                         ,"Force using Lambda Scale VSO also in non-VSO-Mode")
+  ("AllowNegDist",                                    m_bAllowNegDist           , true                          ,"Allow negative Distortion in VSO")
+                                                                                                              
+  ("UseEstimatedVSD",                                 m_bUseEstimatedVSD        , true                          ,"Model based VSD estimation instead of rendering based for some encoder decisions" )      
+  ("VSOEarlySkip",                                    m_bVSOEarlySkip           , true                          ,"Early skip of VSO computation if synthesis error assumed to be zero" )      
+                                                                                                               
+  ("WVSO",                                            m_bUseWVSO                , true                          ,"Use depth fidelity term for VSO" )
+  ("VSOWeight",                                       m_iVSOWeight              , 10                            ,"Synthesized View Distortion Change weight" )
+  ("VSDWeight",                                       m_iVSDWeight              , 1                             ,"View Synthesis Distortion estimate weight" )
+  ("DWeight",                                         m_iDWeight                , 1                             ,"Depth Distortion weight" )
 #endif //HHI_VSO
-  ("QTL",                             m_bUseQTL                 , true          , "Use depth quad tree limitation (encoder only)" )
-
-  ("IvMvPredFlag"          , m_ivMvPredFlag          , std::vector< Bool >(2,true)                    , "Inter-view motion prediction"              )
-  ("IvMvScalingFlag"       , m_ivMvScalingFlag       , std::vector< Bool >(2,true)                    , "Inter-view motion vector scaling"          )
-  ("Log2SubPbSizeMinus3"   , m_log2SubPbSizeMinus3   , 0                                              , "Log2 minus 3 of sub Pb size"               )
-  ("IvResPredFlag"         , m_ivResPredFlag         , true                                           , "Inter-view residual prediction"            )
-  ("DepthRefinementFlag"   , m_depthRefinementFlag   , true                                           , "Depth to refine disparity"                 )
-  ("ViewSynthesisPredFlag" , m_viewSynthesisPredFlag , true                                           , "View synthesis prediction"                 )
-  ("DepthBasedBlkPartFlag" , m_depthBasedBlkPartFlag , true                                           , "Depth base block partitioning"             )
-  ("MpiFlag"               , m_mpiFlag               , true                                           , "Motion inheritance from texture to depth"  )
-  ("Log2MpiSubPbSizeMinus3", m_log2MpiSubPbSizeMinus3, 0                                              , "Log2 minus 3 of sub Pb size for MPI"       )
-  ("IntraContourFlag"      , m_intraContourFlag      , true                                           , "Intra contour mode"                        )
-  ("IntraWedgeFlag"        , m_intraWedgeFlag        , true                                           , "Intra wedge mode and segmental depth DCs"  )
-  ("IntraSdcFlag"          , m_intraSdcFlag          , true                                           , "Intra depth DCs"                           )
-  ("QtPredFlag"            , m_qtPredFlag            , true                                           , "Quad tree prediction from texture to depth")
-  ("InterSdcFlag"          , m_interSdcFlag          , true                                           , "Inter depth DCs"                           )
-  ("DepthIntraSkip"        , m_depthIntraSkipFlag    , true                                           , "Depth intra skip mode"                     )
+/* 3D- HEVC Tools */                                                            
+  ("QTL"                   ,                          m_bUseQTL                 , true                          , "Use depth quad tree limitation (encoder only)" )
+  ("IvMvPredFlag"          ,                          m_ivMvPredFlag            , BoolAry1d(2,true)             , "Inter-view motion prediction"              )
+  ("IvMvScalingFlag"       ,                          m_ivMvScalingFlag         , BoolAry1d(2,true)             , "Inter-view motion vector scaling"          )
+  ("Log2SubPbSizeMinus3"   ,                          m_log2SubPbSizeMinus3     , 0                             , "Log2 minus 3 of sub Pb size"               )
+  ("IvResPredFlag"         ,                          m_ivResPredFlag           , true                          , "Inter-view residual prediction"            )
+  ("DepthRefinementFlag"   ,                          m_depthRefinementFlag     , true                          , "Depth to refine disparity"                 )
+  ("ViewSynthesisPredFlag" ,                          m_viewSynthesisPredFlag   , true                          , "View synthesis prediction"                 )
+  ("DepthBasedBlkPartFlag" ,                          m_depthBasedBlkPartFlag   , true                          , "Depth base block partitioning"             )
+  ("MpiFlag"               ,                          m_mpiFlag                 , true                          , "Motion inheritance from texture to depth"  )
+  ("Log2MpiSubPbSizeMinus3",                          m_log2MpiSubPbSizeMinus3  , 0                             , "Log2 minus 3 of sub Pb size for MPI"       )
+  ("IntraContourFlag"      ,                          m_intraContourFlag        , true                          , "Intra contour mode"                        )
+  ("IntraWedgeFlag"        ,                          m_intraWedgeFlag          , true                          , "Intra wedge mode and segmental depth DCs"  )
+  ("IntraSdcFlag"          ,                          m_intraSdcFlag            , true                          , "Intra depth DCs"                           )
+  ("QtPredFlag"            ,                          m_qtPredFlag              , true                          , "Quad tree prediction from texture to depth")
+  ("InterSdcFlag"          ,                          m_interSdcFlag            , true                          , "Inter depth DCs"                           )
+  ("DepthIntraSkip"        ,                          m_depthIntraSkipFlag      , true                          , "Depth intra skip mode"                     )
+  ("DLT"                   ,                          m_useDLT                  , true                          , "Depth lookup table"                        )
+  ("IlluCompEnable"        ,                          m_abUseIC                 , true                          , "Enable illumination compensation"          )
+  ("IlluCompLowLatencyEnc" ,                          m_bUseLowLatencyICEnc     , false                         , "Enable low-latency illumination compensation encoding")
 #endif //H_3D
+    
   ;
 
-#if H_MV
+#if NH_MV    
   // parse coding structure
   for( Int k = 0; k < MAX_NUM_LAYERS; k++ )
@@ -827,6 +1394,6 @@
 
 
-      for( Int i = 1; i < MAX_GOP + 1; i++ ) 
-      {
+  for(Int i=1; i<MAX_GOP+1; i++)
+  {
         std::ostringstream cOSS2;
         cOSS2<<"Frame"<<i<<"_l"<<k;
@@ -840,5 +1407,6 @@
   }
 #else
-  for(Int i=1; i<MAX_GOP+1; i++) {
+  for(Int i=1; i<MAX_GOP+1; i++)
+  {
     std::ostringstream cOSS;
     cOSS<<"Frame"<<i;
@@ -847,5 +1415,40 @@
 #endif
   po::setDefaults(opts);
-  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
+  po::ErrorReporter err;
+  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv, err);
+
+  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  {
+    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
+  }
+
+  if (argc == 1 || do_help)
+  {
+    /* argc == 1: no options have been specified */
+    po::doHelp(cout, opts);
+    return false;
+  }
+
+  if (err.is_errored)
+  {
+    if (!warnUnknowParameter)
+    {
+      /* error report has already been printed on stderr */
+      return false;
+    }
+  }
+
+  /*
+   * Set any derived parameters
+   */
+  /* convert std::string to c string for compatability */
+#if !NH_MV
+  m_pchInputFile = cfg_InputFile.empty() ? NULL : strdup(cfg_InputFile.c_str());
+#endif
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+#if !NH_MV
+  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
+#endif
+  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
 
   if(m_isField)
@@ -858,55 +1461,25 @@
     m_framesToBeEncoded *= 2;
   }
-  
-  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
-  {
-    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
-  }
-  
-  if (argc == 1 || do_help)
-  {
-    /* argc == 1: no options have been specified */
-    po::doHelp(cout, opts);
-    return false;
-  }
-  
-  /*
-   * Set any derived parameters
-   */
-  /* convert std::string to c string for compatability */
-#if !H_MV
-  m_pchInputFile = cfg_InputFile.empty() ? NULL : strdup(cfg_InputFile.c_str());
-#endif
-  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
-#if !H_MV
-  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
-#endif
-  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
-  
-  Char* pColumnWidth = cfgColumnWidth.empty() ? NULL: strdup(cfgColumnWidth.c_str());
-  Char* pRowHeight = cfgRowHeight.empty() ? NULL : strdup(cfgRowHeight.c_str());
 
   if( !m_tileUniformSpacingFlag && m_numTileColumnsMinus1 > 0 )
   {
-    char *str;
-    int  i=0;
-    m_tileColumnWidth.resize( m_numTileColumnsMinus1 );
-    str = strtok(pColumnWidth, " ,-");
-    while(str!=NULL)
-    {
-      if( i >= m_numTileColumnsMinus1 )
-      {
-        printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
-        exit( EXIT_FAILURE );
-      }
-      m_tileColumnWidth[i] = atoi( str );
-      str = strtok(NULL, " ,-");
-      i++;
-    }
-    if( i < m_numTileColumnsMinus1 )
+    if (cfg_ColumnWidth.values.size() > m_numTileColumnsMinus1)
+    {
+      printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
+      exit( EXIT_FAILURE );
+    }
+    else if (cfg_ColumnWidth.values.size() < m_numTileColumnsMinus1)
     {
       printf( "The width of some columns is not defined.\n" );
       exit( EXIT_FAILURE );
     }
+    else
+    {
+      m_tileColumnWidth.resize(m_numTileColumnsMinus1);
+      for(UInt i=0; i<cfg_ColumnWidth.values.size(); i++)
+      {
+        m_tileColumnWidth[i]=cfg_ColumnWidth.values[i];
+      }
+    }
   }
   else
@@ -917,24 +1490,22 @@
   if( !m_tileUniformSpacingFlag && m_numTileRowsMinus1 > 0 )
   {
-    char *str;
-    int  i=0;
-    m_tileRowHeight.resize(m_numTileRowsMinus1);
-    str = strtok(pRowHeight, " ,-");
-    while(str!=NULL)
-    {
-      if( i>=m_numTileRowsMinus1 )
-      {
-        printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
-        exit( EXIT_FAILURE );
-      }
-      m_tileRowHeight[i] = atoi( str );
-      str = strtok(NULL, " ,-");
-      i++;
-    }
-    if( i < m_numTileRowsMinus1 )
+    if (cfg_RowHeight.values.size() > m_numTileRowsMinus1)
+    {
+      printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
+      exit( EXIT_FAILURE );
+    }
+    else if (cfg_RowHeight.values.size() < m_numTileRowsMinus1)
     {
       printf( "The height of some rows is not defined.\n" );
       exit( EXIT_FAILURE );
-   }
+    }
+    else
+    {
+      m_tileRowHeight.resize(m_numTileRowsMinus1);
+      for(UInt i=0; i<cfg_RowHeight.values.size(); i++)
+      {
+        m_tileRowHeight[i]=cfg_RowHeight.values[i];
+      }
+    }
   }
   else
@@ -942,18 +1513,197 @@
     m_tileRowHeight.clear();
   }
-#if H_MV
-  free ( pColumnWidth );
-  free ( pRowHeight   ); 
-#endif
+
   m_scalingListFile = cfg_ScalingListFile.empty() ? NULL : strdup(cfg_ScalingListFile.c_str());
-  
+
   /* rules for input, output and internal bitdepths as per help text */
-  if (!m_internalBitDepthY) { m_internalBitDepthY = m_inputBitDepthY; }
-  if (!m_internalBitDepthC) { m_internalBitDepthC = m_internalBitDepthY; }
-  if (!m_inputBitDepthC) { m_inputBitDepthC = m_inputBitDepthY; }
-  if (!m_outputBitDepthY) { m_outputBitDepthY = m_internalBitDepthY; }
-  if (!m_outputBitDepthC) { m_outputBitDepthC = m_internalBitDepthC; }
-
-  // TODO:ChromaFmt assumes 4:2:0 below
+  if (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] == 0)
+  {
+    m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] = m_inputBitDepth      [CHANNEL_TYPE_LUMA  ];
+  }
+  if (m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] == 0)
+  {
+    m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] = m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ];
+  }
+  if (m_internalBitDepth   [CHANNEL_TYPE_LUMA  ] == 0)
+  {
+    m_internalBitDepth   [CHANNEL_TYPE_LUMA  ] = m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ];
+  }
+  if (m_internalBitDepth   [CHANNEL_TYPE_CHROMA] == 0)
+  {
+    m_internalBitDepth   [CHANNEL_TYPE_CHROMA] = m_internalBitDepth   [CHANNEL_TYPE_LUMA  ];
+  }
+  if (m_inputBitDepth      [CHANNEL_TYPE_CHROMA] == 0)
+  {
+    m_inputBitDepth      [CHANNEL_TYPE_CHROMA] = m_inputBitDepth      [CHANNEL_TYPE_LUMA  ];
+  }
+  if (m_outputBitDepth     [CHANNEL_TYPE_LUMA  ] == 0)
+  {
+    m_outputBitDepth     [CHANNEL_TYPE_LUMA  ] = m_internalBitDepth   [CHANNEL_TYPE_LUMA  ];
+  }
+  if (m_outputBitDepth     [CHANNEL_TYPE_CHROMA] == 0)
+  {
+    m_outputBitDepth     [CHANNEL_TYPE_CHROMA] = m_internalBitDepth   [CHANNEL_TYPE_CHROMA];
+  }
+
+  m_InputChromaFormatIDC = numberToChromaFormat(tmpInputChromaFormat);
+  m_chromaFormatIDC      = ((tmpChromaFormat == 0) ? (m_InputChromaFormatIDC) : (numberToChromaFormat(tmpChromaFormat)));
+
+#if NH_MV
+  // parse PTL
+  Bool anyEmpty = false; 
+  if( cfg_profiles.empty() )
+  {
+#if NH_3D
+    cfg_profiles = string("main main 3d-main");
+#else
+    cfg_profiles = string("main main multiview-main");    
+#endif
+    fprintf(stderr, "\nWarning: No profiles given, using defaults: %s", cfg_profiles.c_str() );
+    anyEmpty = true; 
+  }
+
+  if( cfg_levels.empty() )
+  {
+    cfg_levels = string("5.1 5.1 5.1");
+    fprintf(stderr, "\nWarning: No levels given, using defaults: %s", cfg_levels.c_str() );
+    anyEmpty = true; 
+  }
+
+  if( cfg_tiers.empty() )
+  {
+    cfg_tiers = string("main main main");
+    fprintf(stderr, "\nWarning: No tiers given, using defaults: %s", cfg_tiers.c_str());
+    anyEmpty = true; 
+  }
+
+  if( m_inblFlag.empty() )
+  {
+    fprintf(stderr, "\nWarning: No inblFlags given, using defaults:");
+    for( Int i = 0; i < 3; i++)
+    {
+      m_inblFlag.push_back( false );
+      fprintf(stderr," %d", (Int) m_inblFlag[i]);
+    }
+    anyEmpty = true; 
+  }   
+
+  if ( anyEmpty )
+  {
+    fprintf( stderr, "\n" );
+  }
+
+  xReadStrToEnum( cfg_profiles, extendedProfiles  ); 
+  xReadStrToEnum( cfg_levels,   m_level     ); 
+  xReadStrToEnum( cfg_tiers ,   m_levelTier ); 
+
+
+#if NH_MV
+  m_profiles.resize( extendedProfiles.size()); 
+
+  for (Int i = 0; i < m_profiles.size(); i++)
+  {
+    Profile::Name& m_profile             = m_profiles      [i];  
+    ExtendedProfileName& extendedProfile = extendedProfiles[i];  
+#endif
+#endif
+
+  if (extendedProfile >= 1000 && extendedProfile <= 12316)
+    {
+      m_profile = Profile::MAINREXT;
+      if (m_bitDepthConstraint != 0 || tmpConstraintChromaFormat != 0)
+      {
+        fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
+        exit(EXIT_FAILURE);
+      }
+      m_bitDepthConstraint     = (extendedProfile%100);
+    m_intraConstraintFlag          = ((extendedProfile%10000)>=2000);
+    m_onePictureOnlyConstraintFlag = (extendedProfile >= 10000);
+      switch ((extendedProfile/100)%10)
+      {
+      case 0:  tmpConstraintChromaFormat=400; break;
+      case 1:  tmpConstraintChromaFormat=420; break;
+      case 2:  tmpConstraintChromaFormat=422; break;
+      default: tmpConstraintChromaFormat=444; break;
+      }
+    }
+    else
+    {
+      m_profile = Profile::Name(extendedProfile);
+    }
+
+    if (m_profile == Profile::HIGHTHROUGHPUTREXT )
+    {
+      if (m_bitDepthConstraint == 0)
+      {
+        m_bitDepthConstraint = 16;
+      }
+      m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? CHROMA_444 : numberToChromaFormat(tmpConstraintChromaFormat);
+    }
+    else if (m_profile == Profile::MAINREXT)
+    {
+      if (m_bitDepthConstraint == 0 && tmpConstraintChromaFormat == 0)
+      {
+        // produce a valid combination, if possible.
+      const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag        ||
+                                           m_transformSkipContextEnabledFlag         ||
+                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ||
+                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ||
+          !m_enableIntraReferenceSmoothing         ||
+                                           m_persistentRiceAdaptationEnabledFlag     ||
+                                           m_log2MaxTransformSkipBlockSize!=2;
+      const Bool bUsingChromaQPAdjustment= m_diffCuChromaQpOffsetDepth >= 0;
+      const Bool bUsingExtendedPrecision = m_extendedPrecisionProcessingFlag;
+      if (m_onePictureOnlyConstraintFlag)
+      {
+        m_chromaFormatConstraint = CHROMA_444;
+        if (m_intraConstraintFlag != true)
+        {
+          fprintf(stderr, "Error: Intra constraint flag must be true when one_picture_only_constraint_flag is true\n");
+          exit(EXIT_FAILURE);
+        }
+        const Int maxBitDepth = m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
+        m_bitDepthConstraint = maxBitDepth>8 ? 16:8;
+      }
+      else
+      {
+        m_chromaFormatConstraint = NUM_CHROMA_FORMAT;
+        automaticallySelectRExtProfile(bUsingGeneralRExtTools,
+          bUsingChromaQPAdjustment,
+          bUsingExtendedPrecision,
+          m_intraConstraintFlag,
+          m_bitDepthConstraint,
+          m_chromaFormatConstraint,
+          m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]),
+          m_chromaFormatIDC);
+      }
+    }
+      else if (m_bitDepthConstraint == 0 || tmpConstraintChromaFormat == 0)
+      {
+        fprintf(stderr, "Error: The bit depth and chroma format constraints must either both be specified or both be configured automatically\n");
+        exit(EXIT_FAILURE);
+      }
+      else
+      {
+        m_chromaFormatConstraint = numberToChromaFormat(tmpConstraintChromaFormat);
+      }
+    }
+    else
+    {
+      m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? m_chromaFormatIDC : numberToChromaFormat(tmpConstraintChromaFormat);
+      m_bitDepthConstraint = (m_profile == Profile::MAIN10?10:8);
+    }
+#if NH_MV
+  }
+
+  if ( m_numberOfLayers != 0 && ( m_profiles[0] != Profile::MAIN || m_profiles[1] != Profile::MAIN )  )
+  {
+    fprintf(stderr, "Error: The base layer must conform to the Main profile for Multilayer coding.\n");
+    exit(EXIT_FAILURE);
+  }
+#endif
+
+
+  m_inputColourSpaceConvert = stringToInputColourSpaceConvert(inputColourSpaceConvert, true);
+
   switch (m_conformanceWindowMode)
   {
@@ -984,10 +1734,10 @@
         }
       }
-      if (m_aiPad[0] % TComSPS::getWinUnitX(CHROMA_420) != 0)
+      if (m_aiPad[0] % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0)
       {
         fprintf(stderr, "Error: picture width is not an integer multiple of the specified chroma subsampling\n");
         exit(EXIT_FAILURE);
       }
-      if (m_aiPad[1] % TComSPS::getWinUnitY(CHROMA_420) != 0)
+      if (m_aiPad[1] % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0)
       {
         fprintf(stderr, "Error: picture height is not an integer multiple of the specified chroma subsampling\n");
@@ -1020,7 +1770,13 @@
     }
   }
-  
+
   // allocate slice-based dQP values
-#if H_MV
+#if NH_MV
+  for (Int i = m_layerIdInNuh.size(); i < m_numberOfLayers; i++ )
+  {
+    m_layerIdInNuh.push_back( i == 0 ? 0 : m_layerIdInNuh[ i - 1 ] + 1 ); 
+  }
+  xResizeVector( m_layerIdInNuh ); 
+
   xResizeVector( m_viewOrderIndex    ); 
 
@@ -1041,5 +1797,5 @@
   xResizeVector( m_auxId );
 
-#if H_3D
+#if NH_3D
   xResizeVector( m_depthFlag ); 
 #endif
@@ -1062,4 +1818,23 @@
       {
         m_aidQP[layer][i] = 1;
+      }
+    }
+
+    for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+    {
+      if (saoOffsetBitShift[ch]<0)
+      {
+        if (m_internalBitDepth[ch]>10)
+        {
+          m_log2SaoOffsetScale[layer][ch]=UInt(Clip3<Int>(0, m_internalBitDepth[ch]-10, Int(m_internalBitDepth[ch]-10 + 0.165*m_iQP[layer] - 3.22 + 0.5) ) );
+        }
+        else
+        {
+          m_log2SaoOffsetScale[layer][ch]=0;
+        }
+      }
+      else
+      {
+        m_log2SaoOffsetScale[layer][ch]=UInt(saoOffsetBitShift[ch]);
       }
     }
@@ -1080,5 +1855,5 @@
   m_aidQP = new Int[ m_framesToBeEncoded + m_iGOPSize + 1 ];
   ::memset( m_aidQP, 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
-  
+
   // handling of floating-point QP values
   // if QP is not integer, sequence is split into two sections having QP and QP+1
@@ -1087,5 +1862,5 @@
   {
     Int iSwitchPOC = (Int)( m_framesToBeEncoded - (m_fQP - m_iQP)*m_framesToBeEncoded + 0.5 );
-    
+
     iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
     for ( Int i=iSwitchPOC; i<m_framesToBeEncoded + m_iGOPSize + 1; i++ )
@@ -1094,6 +1869,26 @@
     }
   }
-#endif
-  
+
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    if (saoOffsetBitShift[ch]<0)
+    {
+      if (m_internalBitDepth[ch]>10)
+      {
+        m_log2SaoOffsetScale[ch]=UInt(Clip3<Int>(0, m_internalBitDepth[ch]-10, Int(m_internalBitDepth[ch]-10 + 0.165*m_iQP - 3.22 + 0.5) ) );
+      }
+      else
+      {
+        m_log2SaoOffsetScale[ch]=0;
+      }
+    }
+    else
+    {
+      m_log2SaoOffsetScale[ch]=UInt(saoOffsetBitShift[ch]);
+    }
+  }
+
+#endif
+
   // reading external dQP description from file
   if ( m_pchdQPFile )
@@ -1102,5 +1897,5 @@
     if ( fpt )
     {
-#if H_MV
+#if NH_MV
       for( Int layer = 0; layer < m_numberOfLayers; layer++ )
       {
@@ -1110,6 +1905,9 @@
       while ( iPOC < m_framesToBeEncoded )
       {
-        if ( fscanf(fpt, "%d", &iValue ) == EOF ) break;
-#if H_MV
+        if ( fscanf(fpt, "%d", &iValue ) == EOF )
+        {
+          break;
+        }
+#if NH_MV
         m_aidQP[layer][ iPOC ] = iValue;
         iPOC++;
@@ -1123,26 +1921,28 @@
     }
   }
-  m_iWaveFrontSubstreams = m_iWaveFrontSynchro ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
-
+
+  if( m_masteringDisplay.colourVolumeSEIEnabled )
+  {
+    for(UInt idx=0; idx<6; idx++)
+    {
+      m_masteringDisplay.primaries[idx/2][idx%2] = UShort((cfg_DisplayPrimariesCode.values.size() > idx) ? cfg_DisplayPrimariesCode.values[idx] : 0);
+    }
+    for(UInt idx=0; idx<2; idx++)
+    {
+      m_masteringDisplay.whitePoint[idx] = UShort((cfg_DisplayWhitePointCode.values.size() > idx) ? cfg_DisplayWhitePointCode.values[idx] : 0);
+    }
+  }
+    
   if( m_toneMappingInfoSEIEnabled && !m_toneMapCancelFlag )
   {
-    Char* pcStartOfCodedInterval = cfg_startOfCodedInterval.empty() ? NULL: strdup(cfg_startOfCodedInterval.c_str());
-    Char* pcCodedPivotValue = cfg_codedPivotValue.empty() ? NULL: strdup(cfg_codedPivotValue.c_str());
-    Char* pcTargetPivotValue = cfg_targetPivotValue.empty() ? NULL: strdup(cfg_targetPivotValue.c_str());
-    if( m_toneMapModelId == 2 && pcStartOfCodedInterval )
-    {
-      char *startOfCodedInterval;
-      UInt num = 1u<< m_toneMapTargetBitDepth;
+    if( m_toneMapModelId == 2 && !cfg_startOfCodedInterval.values.empty() )
+    {
+      const UInt num = 1u<< m_toneMapTargetBitDepth;
       m_startOfCodedInterval = new Int[num];
-      ::memset( m_startOfCodedInterval, 0, sizeof(Int)*num );
-      startOfCodedInterval = strtok(pcStartOfCodedInterval, " .");
-      int i = 0;
-      while( startOfCodedInterval && ( i < num ) )
-      {
-        m_startOfCodedInterval[i] = atoi( startOfCodedInterval );
-        startOfCodedInterval = strtok(NULL, " .");
-        i++;
-      }
-    } 
+      for(UInt i=0; i<num; i++)
+      {
+        m_startOfCodedInterval[i] = cfg_startOfCodedInterval.values.size() > i ? cfg_startOfCodedInterval.values[i] : 0;
+      }
+    }
     else
     {
@@ -1151,27 +1951,12 @@
     if( ( m_toneMapModelId == 3 ) && ( m_numPivots > 0 ) )
     {
-      if( pcCodedPivotValue && pcTargetPivotValue )
-      {
-        char *codedPivotValue;
-        char *targetPivotValue;
-        m_codedPivotValue = new Int[m_numPivots];
+      if( !cfg_codedPivotValue.values.empty() && !cfg_targetPivotValue.values.empty() )
+      {
+        m_codedPivotValue  = new Int[m_numPivots];
         m_targetPivotValue = new Int[m_numPivots];
-        ::memset( m_codedPivotValue, 0, sizeof(Int)*( m_numPivots ) );
-        ::memset( m_targetPivotValue, 0, sizeof(Int)*( m_numPivots ) );
-        codedPivotValue = strtok(pcCodedPivotValue, " .");
-        int i=0;
-        while(codedPivotValue&&i<m_numPivots)
+        for(UInt i=0; i<m_numPivots; i++)
         {
-          m_codedPivotValue[i] = atoi( codedPivotValue );
-          codedPivotValue = strtok(NULL, " .");
-          i++;
-        }
-        i=0;
-        targetPivotValue = strtok(pcTargetPivotValue, " .");
-        while(targetPivotValue&&i<m_numPivots)
-        {
-          m_targetPivotValue[i]= atoi( targetPivotValue );
-          targetPivotValue = strtok(NULL, " .");
-          i++;
+          m_codedPivotValue[i]  = cfg_codedPivotValue.values.size()  > i ? cfg_codedPivotValue.values [i] : 0;
+          m_targetPivotValue[i] = cfg_targetPivotValue.values.size() > i ? cfg_targetPivotValue.values[i] : 0;
         }
       }
@@ -1184,65 +1969,49 @@
   }
 
-#if H_MV
-  // parse PTL
-  Bool anyEmpty = false; 
-  if( cfg_profiles.empty() )
-  {
-#if H_3D
-    cfg_profiles = string("main main 3d-main");
-#else
-    cfg_profiles = string("main main multiview-main");    
-#endif
-    fprintf(stderr, "\nWarning: No profiles given, using defaults: %s", cfg_profiles.c_str() );
-    anyEmpty = true; 
-  }
-
-  if( cfg_levels.empty() )
-  {
-    cfg_levels = string("none none none");
-    fprintf(stderr, "\nWarning: No levels given, using defaults: %s", cfg_levels.c_str() );
-    anyEmpty = true; 
-  }
-
-  if( cfg_tiers.empty() )
-  {
-    cfg_tiers = string("main main main");
-    fprintf(stderr, "\nWarning: No tiers given, using defaults: %s", cfg_tiers.c_str());
-    anyEmpty = true; 
-  }
-
-  if( m_inblFlag.empty() )
-  {
-    fprintf(stderr, "\nWarning: No inblFlags given, using defaults:");
-    for( Int i = 0; i < 3; i++)
-    {
-      m_inblFlag.push_back( false );
-      fprintf(stderr," %d", (Int) m_inblFlag[i]);
-    }
-    anyEmpty = true; 
-  }   
-
-  if ( anyEmpty )
-  {
-    fprintf( stderr, "\n" );
-  }
-
-  xReadStrToEnum( cfg_profiles, m_profile   ); 
-  xReadStrToEnum( cfg_levels,   m_level     ); 
-  xReadStrToEnum( cfg_tiers ,   m_levelTier ); 
-#endif
-#if H_3D
-  // set global varibles
-  xSetGlobal();
-#if H_3D_VSO
-// Table base optimization 
+  if( m_kneeSEIEnabled && !m_kneeSEICancelFlag )
+  {
+    assert ( m_kneeSEINumKneePointsMinus1 >= 0 && m_kneeSEINumKneePointsMinus1 < 999 );
+    m_kneeSEIInputKneePoint  = new Int[m_kneeSEINumKneePointsMinus1+1];
+    m_kneeSEIOutputKneePoint = new Int[m_kneeSEINumKneePointsMinus1+1];
+    for(Int i=0; i<(m_kneeSEINumKneePointsMinus1+1); i++)
+    {
+      m_kneeSEIInputKneePoint[i]  = cfg_kneeSEIInputKneePointValue.values.size()  > i ? cfg_kneeSEIInputKneePointValue.values[i]  : 1;
+      m_kneeSEIOutputKneePoint[i] = cfg_kneeSEIOutputKneePointValue.values.size() > i ? cfg_kneeSEIOutputKneePointValue.values[i] : 0;
+    }
+  }
+
+  if(m_timeCodeSEIEnabled)
+  {
+    for(Int i = 0; i < m_timeCodeSEINumTs && i < MAX_TIMECODE_SEI_SETS; i++)
+    {
+      m_timeSetArray[i].clockTimeStampFlag    = cfg_timeCodeSeiTimeStampFlag        .values.size()>i ? cfg_timeCodeSeiTimeStampFlag        .values [i] : false;
+      m_timeSetArray[i].numUnitFieldBasedFlag = cfg_timeCodeSeiNumUnitFieldBasedFlag.values.size()>i ? cfg_timeCodeSeiNumUnitFieldBasedFlag.values [i] : 0;
+      m_timeSetArray[i].countingType          = cfg_timeCodeSeiCountingType         .values.size()>i ? cfg_timeCodeSeiCountingType         .values [i] : 0;
+      m_timeSetArray[i].fullTimeStampFlag     = cfg_timeCodeSeiFullTimeStampFlag    .values.size()>i ? cfg_timeCodeSeiFullTimeStampFlag    .values [i] : 0;
+      m_timeSetArray[i].discontinuityFlag     = cfg_timeCodeSeiDiscontinuityFlag    .values.size()>i ? cfg_timeCodeSeiDiscontinuityFlag    .values [i] : 0;
+      m_timeSetArray[i].cntDroppedFlag        = cfg_timeCodeSeiCntDroppedFlag       .values.size()>i ? cfg_timeCodeSeiCntDroppedFlag       .values [i] : 0;
+      m_timeSetArray[i].numberOfFrames        = cfg_timeCodeSeiNumberOfFrames       .values.size()>i ? cfg_timeCodeSeiNumberOfFrames       .values [i] : 0;
+      m_timeSetArray[i].secondsValue          = cfg_timeCodeSeiSecondsValue         .values.size()>i ? cfg_timeCodeSeiSecondsValue         .values [i] : 0;
+      m_timeSetArray[i].minutesValue          = cfg_timeCodeSeiMinutesValue         .values.size()>i ? cfg_timeCodeSeiMinutesValue         .values [i] : 0;
+      m_timeSetArray[i].hoursValue            = cfg_timeCodeSeiHoursValue           .values.size()>i ? cfg_timeCodeSeiHoursValue           .values [i] : 0;
+      m_timeSetArray[i].secondsFlag           = cfg_timeCodeSeiSecondsFlag          .values.size()>i ? cfg_timeCodeSeiSecondsFlag          .values [i] : 0;
+      m_timeSetArray[i].minutesFlag           = cfg_timeCodeSeiMinutesFlag          .values.size()>i ? cfg_timeCodeSeiMinutesFlag          .values [i] : 0;
+      m_timeSetArray[i].hoursFlag             = cfg_timeCodeSeiHoursFlag            .values.size()>i ? cfg_timeCodeSeiHoursFlag            .values [i] : 0;
+      m_timeSetArray[i].timeOffsetLength      = cfg_timeCodeSeiTimeOffsetLength     .values.size()>i ? cfg_timeCodeSeiTimeOffsetLength     .values [i] : 0;
+      m_timeSetArray[i].timeOffsetValue       = cfg_timeCodeSeiTimeOffsetValue      .values.size()>i ? cfg_timeCodeSeiTimeOffsetValue      .values [i] : 0;
+    }
+  }
+
+#if NH_3D
+#if NH_3D_VSO
+  // Table base optimization 
   // Q&D
   Double adLambdaScaleTable[] = 
   {  0.031250, 0.031639, 0.032029, 0.032418, 0.032808, 0.033197, 0.033586, 0.033976, 0.034365, 0.034755, 
-     0.035144, 0.035533, 0.035923, 0.036312, 0.036702, 0.037091, 0.037480, 0.037870, 0.038259, 0.038648, 
-     0.039038, 0.039427, 0.039817, 0.040206, 0.040595, 0.040985, 0.041374, 0.041764, 0.042153, 0.042542, 
-     0.042932, 0.043321, 0.043711, 0.044100, 0.044194, 0.053033, 0.061872, 0.070711, 0.079550, 0.088388, 
-     0.117851, 0.147314, 0.176777, 0.235702, 0.294628, 0.353553, 0.471405, 0.589256, 0.707107, 0.707100, 
-     0.753550, 0.800000  
+  0.035144, 0.035533, 0.035923, 0.036312, 0.036702, 0.037091, 0.037480, 0.037870, 0.038259, 0.038648, 
+  0.039038, 0.039427, 0.039817, 0.040206, 0.040595, 0.040985, 0.041374, 0.041764, 0.042153, 0.042542, 
+  0.042932, 0.043321, 0.043711, 0.044100, 0.044194, 0.053033, 0.061872, 0.070711, 0.079550, 0.088388, 
+  0.117851, 0.147314, 0.176777, 0.235702, 0.294628, 0.353553, 0.471405, 0.589256, 0.707107, 0.707100, 
+  0.753550, 0.800000  
   }; 
   if ( m_bUseVSO && m_bVSOLSTable )
@@ -1261,37 +2030,47 @@
     m_dLambdaScaleVSO *= adLambdaScaleTable[m_iQP[firstDepthLayer]]; 
   }
-#endif
-#if H_3D_VSO
-if ( m_bUseVSO && m_uiVSOMode == 4)
-{
-  m_cRenModStrParser.setString( m_iNumberOfViews, m_pchVSOConfig );
+  if ( m_bUseVSO && m_uiVSOMode == 4)
+  {
+    m_cRenModStrParser.setString( m_iNumberOfViews, m_pchVSOConfig );
+    m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
+      m_internalBitDepth[ CHANNEL_TYPE_LUMA],
+      (UInt)m_iCodedCamParPrecision,
+      m_FrameSkip,
+      (UInt)m_framesToBeEncoded,
+      m_pchCameraParameterFile,
+      m_pchBaseViewCameraNumbers,
+      NULL,
+      m_cRenModStrParser.getSynthViews(),
+      LOG2_DISP_PREC_LUT );
+  }
+  else if ( m_bUseVSO && m_uiVSOMode != 4 )
+  {
+    m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
+      m_internalBitDepth[ CHANNEL_TYPE_LUMA],
+      (UInt)m_iCodedCamParPrecision,
+      m_FrameSkip,
+      (UInt)m_framesToBeEncoded,
+      m_pchCameraParameterFile,
+      m_pchBaseViewCameraNumbers,
+      m_pchVSOConfig,
+      NULL,
+      LOG2_DISP_PREC_LUT );
+  }
+  else
+  {
+    m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
+      m_internalBitDepth[ CHANNEL_TYPE_LUMA],
+      (UInt) m_iCodedCamParPrecision,
+      m_FrameSkip,
+      (UInt) m_framesToBeEncoded,
+      m_pchCameraParameterFile,
+      m_pchBaseViewCameraNumbers,
+      NULL,
+      NULL,
+      LOG2_DISP_PREC_LUT );
+  }
+#else
   m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
-                                      g_bitDepthY,
-                                (UInt)m_iCodedCamParPrecision,
-                                      m_FrameSkip,
-                                (UInt)m_framesToBeEncoded,
-                                      m_pchCameraParameterFile,
-                                      m_pchBaseViewCameraNumbers,
-                                      NULL,
-                                      m_cRenModStrParser.getSynthViews(),
-                                      LOG2_DISP_PREC_LUT );
-}
-else if ( m_bUseVSO && m_uiVSOMode != 4 )
-{
-  m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
-                                      g_bitDepthY,
-                                (UInt)m_iCodedCamParPrecision,
-                                      m_FrameSkip,
-                                (UInt)m_framesToBeEncoded,
-                                      m_pchCameraParameterFile,
-                                      m_pchBaseViewCameraNumbers,
-                                      m_pchVSOConfig,
-                                      NULL,
-                                      LOG2_DISP_PREC_LUT );
-}
-else
-{
-  m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
-    g_bitDepthY,
+    m_internalBitDepth[ CHANNEL_TYPE_LUMA],
     (UInt) m_iCodedCamParPrecision,
     m_FrameSkip,
@@ -1302,37 +2081,32 @@
     NULL,
     LOG2_DISP_PREC_LUT );
-}
-#else
-  m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
-    g_bitDepthY,
-    (UInt) m_iCodedCamParPrecision,
-    m_FrameSkip,
-    (UInt) m_framesToBeEncoded,
-    m_pchCameraParameterFile,
-    m_pchBaseViewCameraNumbers,
-    NULL,
-    NULL,
-    LOG2_DISP_PREC_LUT );
 #endif
   m_cCameraData.check( false, true );
 #endif
+
   // check validity of input parameters
   xCheckParameter();
 
-#if !H_3D
-  // set global varibles
-  xSetGlobal();
-#endif
-  
+  // compute actual CU depth with respect to config depth and max transform size
+  UInt uiAddCUDepth  = 0;
+  while( (m_uiMaxCUWidth>>m_uiMaxCUDepth) > ( 1 << ( m_uiQuadtreeTULog2MinSize + uiAddCUDepth )  ) )
+  {
+    uiAddCUDepth++;
+  }
+
+  m_uiMaxTotalCUDepth = m_uiMaxCUDepth + uiAddCUDepth + getMaxCUDepthOffset(m_chromaFormatIDC, m_uiQuadtreeTULog2MinSize); // if minimum TU larger than 4x4, allow for additional part indices for 4:2:2 SubTUs.
+  uiAddCUDepth++;
+  m_uiLog2DiffMaxMinCodingBlockSize = m_uiMaxCUDepth - 1;
+
   // print-out parameters
   xPrintParameter();
-  
+
   return true;
 }
+
+
 // ====================================================================================================================
 // Private member functions
 // ====================================================================================================================
-
-Bool confirmPara(Bool bflag, const Char* message);
 
 Void TAppEncCfg::xCheckParameter()
@@ -1348,5 +2122,5 @@
 
 
-#if !H_MV
+#if !NH_MV
   if( m_profile==Profile::NONE )
   {
@@ -1365,10 +2139,120 @@
   Bool check_failed = false; /* abort if there is a fatal configuration problem */
 #define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+
+  const UInt maxBitDepth=(m_chromaFormatIDC==CHROMA_400) ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
+  xConfirmPara(m_bitDepthConstraint<maxBitDepth, "The internalBitDepth must not be greater than the bitDepthConstraint value");
+  xConfirmPara(m_chromaFormatConstraint<m_chromaFormatIDC, "The chroma format used must not be greater than the chromaFormatConstraint value");
+#if NH_MV
+  Profile::Name & m_profile = m_profiles[0];
+#endif
+
+  if (m_profile==Profile::MAINREXT || m_profile==Profile::HIGHTHROUGHPUTREXT)
+  {
+    xConfirmPara(m_lowerBitRateConstraintFlag==false && m_intraConstraintFlag==false, "The lowerBitRateConstraint flag cannot be false when intraConstraintFlag is false");
+    xConfirmPara(m_cabacBypassAlignmentEnabledFlag && m_profile!=Profile::HIGHTHROUGHPUTREXT, "AlignCABACBeforeBypass must not be enabled unless the high throughput profile is being used.");
+    if (m_profile == Profile::MAINREXT)
+    {
+      const UInt intraIdx = m_intraConstraintFlag ? 1:0;
+      const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
+      const UInt chromaFormatIdx = UInt(m_chromaFormatConstraint);
+      const Bool bValidProfile = (bitDepthIdx > 3 || chromaFormatIdx>3) ? false : (validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx] != NONE);
+      xConfirmPara(!bValidProfile, "Invalid intra constraint flag, bit depth constraint flag and chroma format constraint flag combination for a RExt profile");
+      const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag        ||
+                                           m_transformSkipContextEnabledFlag         ||
+                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ||
+                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ||
+                                           !m_enableIntraReferenceSmoothing         ||
+                                           m_persistentRiceAdaptationEnabledFlag     ||
+                                           m_log2MaxTransformSkipBlockSize!=2;
+      const Bool bUsingChromaQPTool      = m_diffCuChromaQpOffsetDepth >= 0;
+      const Bool bUsingExtendedPrecision = m_extendedPrecisionProcessingFlag;
+
+      xConfirmPara((m_chromaFormatConstraint==CHROMA_420 || m_chromaFormatConstraint==CHROMA_400) && bUsingChromaQPTool, "CU Chroma QP adjustment cannot be used for 4:0:0 or 4:2:0 RExt profiles");
+      xConfirmPara(m_bitDepthConstraint != 16 && bUsingExtendedPrecision, "Extended precision can only be used in 16-bit RExt profiles");
+      if (!(m_chromaFormatConstraint == CHROMA_400 && m_bitDepthConstraint == 16) && m_chromaFormatConstraint!=CHROMA_444)
+      {
+        xConfirmPara(bUsingGeneralRExtTools, "Combination of tools and profiles are not possible in the specified RExt profile.");
+      }
+      xConfirmPara( m_onePictureOnlyConstraintFlag && m_chromaFormatConstraint!=CHROMA_444, "chroma format constraint must be 4:4:4 when one-picture-only constraint flag is 1");
+      xConfirmPara( m_onePictureOnlyConstraintFlag && m_bitDepthConstraint != 8 && m_bitDepthConstraint != 16, "bit depth constraint must be 8 or 16 when one-picture-only constraint flag is 1");
+      xConfirmPara( m_onePictureOnlyConstraintFlag && m_framesToBeEncoded > 1, "Number of frames to be encoded must be 1 when one-picture-only constraint flag is 1.");
+
+      if (!m_intraConstraintFlag && m_bitDepthConstraint==16 && m_chromaFormatConstraint==CHROMA_444)
+      {
+        fprintf(stderr, "********************************************************************************************************\n");
+        fprintf(stderr, "** WARNING: The RExt constraint flags describe a non standard combination (used for development only) **\n");
+        fprintf(stderr, "********************************************************************************************************\n");
+      }
+    }
+    else
+    {
+      xConfirmPara( m_chromaFormatConstraint != CHROMA_444, "chroma format constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
+      xConfirmPara( m_bitDepthConstraint     != 16,         "bit depth constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
+      xConfirmPara( m_intraConstraintFlag    != 1,          "intra constraint flag must be 1 in the High Throughput 4:4:4 16-bit Intra profile.");
+    }
+  }
+  else
+  {
+    xConfirmPara(m_bitDepthConstraint!=((m_profile==Profile::MAIN10)?10:8), "BitDepthConstraint must be 8 for MAIN profile and 10 for MAIN10 profile.");
+    xConfirmPara(m_chromaFormatConstraint!=CHROMA_420, "ChromaFormatConstraint must be 420 for non main-RExt profiles.");
+    xConfirmPara(m_intraConstraintFlag==true, "IntraConstraintFlag must be false for non main_RExt profiles.");
+    xConfirmPara(m_lowerBitRateConstraintFlag==false, "LowerBitrateConstraintFlag must be true for non main-RExt profiles.");
+    xConfirmPara(m_profile == Profile::MAINSTILLPICTURE && m_framesToBeEncoded > 1, "Number of frames to be encoded must be 1 when main still picture profile is used.");
+
+    xConfirmPara(m_crossComponentPredictionEnabledFlag==true, "CrossComponentPrediction must not be used for non main-RExt profiles.");
+    xConfirmPara(m_log2MaxTransformSkipBlockSize!=2, "Transform Skip Log2 Max Size must be 2 for V1 profiles.");
+    xConfirmPara(m_transformSkipRotationEnabledFlag==true, "UseResidualRotation must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_transformSkipContextEnabledFlag==true, "UseSingleSignificanceMapContext must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT]==true, "ImplicitResidualDPCM must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT]==true, "ExplicitResidualDPCM must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_persistentRiceAdaptationEnabledFlag==true, "GolombRiceParameterAdaption must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_extendedPrecisionProcessingFlag==true, "UseExtendedPrecision must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_highPrecisionOffsetsEnabledFlag==true, "UseHighPrecisionPredictionWeighting must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_enableIntraReferenceSmoothing==false, "EnableIntraReferenceSmoothing must be enabled for non main-RExt profiles.");
+    xConfirmPara(m_cabacBypassAlignmentEnabledFlag, "AlignCABACBeforeBypass cannot be enabled for non main-RExt profiles.");
+  }
+
   // check range of parameters
-  xConfirmPara( m_inputBitDepthY < 8,                                                     "InputBitDepth must be at least 8" );
-  xConfirmPara( m_inputBitDepthC < 8,                                                     "InputBitDepthC must be at least 8" );
+  xConfirmPara( m_inputBitDepth[CHANNEL_TYPE_LUMA  ] < 8,                                   "InputBitDepth must be at least 8" );
+  xConfirmPara( m_inputBitDepth[CHANNEL_TYPE_CHROMA] < 8,                                   "InputBitDepthC must be at least 8" );
+
+#if !RExt__HIGH_BIT_DEPTH_SUPPORT
+  if (m_extendedPrecisionProcessingFlag)
+  {
+    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+    {
+      xConfirmPara((m_internalBitDepth[channelType] > 8) , "Model is not configured to support high enough internal accuracies - enable RExt__HIGH_BIT_DEPTH_SUPPORT to use increased precision internal data types etc...");
+    }
+  }
+  else
+  {
+    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+    {
+      xConfirmPara((m_internalBitDepth[channelType] > 12) , "Model is not configured to support high enough internal accuracies - enable RExt__HIGH_BIT_DEPTH_SUPPORT to use increased precision internal data types etc...");
+    }
+  }
+#endif
+
+  xConfirmPara( (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] < m_inputBitDepth[CHANNEL_TYPE_LUMA  ]), "MSB-extended bit depth for luma channel (--MSBExtendedBitDepth) must be greater than or equal to input bit depth for luma channel (--InputBitDepth)" );
+  xConfirmPara( (m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] < m_inputBitDepth[CHANNEL_TYPE_CHROMA]), "MSB-extended bit depth for chroma channel (--MSBExtendedBitDepthC) must be greater than or equal to input bit depth for chroma channel (--InputBitDepthC)" );
+
+#if NH_MV
+  for (Int i = 0; i < m_numberOfLayers; i++)
+  {
+    xConfirmPara( m_log2SaoOffsetScale[i][CHANNEL_TYPE_LUMA]   > (m_internalBitDepth[CHANNEL_TYPE_LUMA  ]<10?0:(m_internalBitDepth[CHANNEL_TYPE_LUMA  ]-10)), "SaoLumaOffsetBitShift must be in the range of 0 to InternalBitDepth-10, inclusive");
+    xConfirmPara( m_log2SaoOffsetScale[i][CHANNEL_TYPE_CHROMA] > (m_internalBitDepth[CHANNEL_TYPE_CHROMA]<10?0:(m_internalBitDepth[CHANNEL_TYPE_CHROMA]-10)), "SaoChromaOffsetBitShift must be in the range of 0 to InternalBitDepthC-10, inclusive");
+  }
+#else
+  xConfirmPara( m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA]   > (m_internalBitDepth[CHANNEL_TYPE_LUMA  ]<10?0:(m_internalBitDepth[CHANNEL_TYPE_LUMA  ]-10)), "SaoLumaOffsetBitShift must be in the range of 0 to InternalBitDepth-10, inclusive");
+  xConfirmPara( m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA] > (m_internalBitDepth[CHANNEL_TYPE_CHROMA]<10?0:(m_internalBitDepth[CHANNEL_TYPE_CHROMA]-10)), "SaoChromaOffsetBitShift must be in the range of 0 to InternalBitDepthC-10, inclusive");
+#endif
+
+  xConfirmPara( m_chromaFormatIDC >= NUM_CHROMA_FORMAT,                                     "ChromaFormatIDC must be either 400, 420, 422 or 444" );
+  std::string sTempIPCSC="InputColourSpaceConvert must be empty, "+getListOfColourSpaceConverts(true);
+  xConfirmPara( m_inputColourSpaceConvert >= NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS,         sTempIPCSC.c_str() );
+  xConfirmPara( m_InputChromaFormatIDC >= NUM_CHROMA_FORMAT,                                "InputChromaFormatIDC must be either 400, 420, 422 or 444" );
   xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
   xConfirmPara( m_framesToBeEncoded <= 0,                                                   "Total Number Of Frames encoded must be more than 0" );
-#if H_MV
+#if NH_MV
   xConfirmPara( m_numberOfLayers > MAX_NUM_LAYER_IDS ,                                      "NumberOfLayers must be less than or equal to MAX_NUM_LAYER_IDS");
 
@@ -1376,6 +2260,6 @@
   xConfirmPara( m_layerIdInNuh[0] != 0      , "LayerIdInNuh must be 0 for the first layer. ");
   xConfirmPara( (m_layerIdInNuh.size()!=1) && (m_layerIdInNuh.size() < m_numberOfLayers) , "LayerIdInNuh must be given for all layers. ");
-  
-#if H_3D
+
+#if NH_3D
   xConfirmPara( m_scalabilityMask != 2 && m_scalabilityMask != 3, "Scalability Mask must be equal to 2 or 3. ");
 #else
@@ -1383,5 +2267,5 @@
 #endif
 
-#if H_3D
+#if NH_3D
   if ( m_scalabilityMask & ( 1 << DEPTH_ID ) )
   {
@@ -1404,5 +2288,5 @@
   dimBitOffset[ 0 ] = 0; 
   for (Int j = 1; j <= ((Int) m_dimIds.size() - m_splittingFlag ? 1 : 0); j++ )
- {
+  {
     dimBitOffset[ j ] = dimBitOffset[ j - 1 ] + m_dimensionIdLen[ j - 1]; 
   }
@@ -1412,5 +2296,5 @@
     dimBitOffset[ (Int) m_dimIds.size() ] = 6; 
   }
-  
+
   for( Int j = 0; j < m_dimIds.size(); j++ )
   {    
@@ -1418,8 +2302,8 @@
     xConfirmPara( (m_dimIds[j][0] != 0)                 , "DimensionId of layer 0 must be 0. " );
     xConfirmPara( m_dimensionIdLen[j] < 1 || m_dimensionIdLen[j] > 8, "DimensionIdLen must be greater than 0 and less than 9 in all dimensions. " ); 
-     
-
-   for( Int i = 1; i < m_numberOfLayers; i++ )
-   {     
+
+
+    for( Int i = 1; i < m_numberOfLayers; i++ )
+    {     
       xConfirmPara(  ( m_dimIds[j][i] < 0 ) || ( m_dimIds[j][i] > ( ( 1 << m_dimensionIdLen[j] ) - 1 ) )   , "DimensionId shall be in the range of 0 to 2^DimensionIdLen - 1. " );
       if ( m_splittingFlag )
@@ -1428,48 +2312,48 @@
         xConfirmPara( ( ( layerIdInNuh & ( (1 << dimBitOffset[ j + 1 ] ) - 1) ) >> dimBitOffset[ j ] )  != m_dimIds[j][ i ]  , "When Splitting Flag is equal to 1 dimension ids shall match values derived from layer ids. "); 
       }
-   }
- }
-
- for( Int i = 0; i < m_numberOfLayers; i++ )
- {
-   for( Int j = 0; j < i; j++ )
-   {     
-     Int numDiff  = 0; 
-     Int lastDiff = -1; 
-     for( Int dim = 0; dim < m_dimIds.size(); dim++ )
-     {
-       if ( m_dimIds[dim][i] != m_dimIds[dim][j] )
-       {
-         numDiff ++; 
-         lastDiff = dim; 
-       }
-     }
-
-     Bool allEqual = ( numDiff == 0 ); 
-
-     if ( allEqual ) 
-     {
-       printf( "\nError: Positions of Layers %d and %d are identical in scalability space\n", i, j);
-     }
-
-     xConfirmPara( allEqual , "Each layer shall have a different position in scalability space." );
+    }
+  }
+
+  for( Int i = 0; i < m_numberOfLayers; i++ )
+  {
+    for( Int j = 0; j < i; j++ )
+    {     
+      Int numDiff  = 0; 
+      Int lastDiff = -1; 
+      for( Int dim = 0; dim < m_dimIds.size(); dim++ )
+      {
+        if ( m_dimIds[dim][i] != m_dimIds[dim][j] )
+        {
+          numDiff ++; 
+          lastDiff = dim; 
+        }
+      }
+
+      Bool allEqual = ( numDiff == 0 ); 
+
+      if ( allEqual ) 
+      {
+        printf( "\nError: Positions of Layers %d and %d are identical in scalability space\n", i, j);
+      }
+
+      xConfirmPara( allEqual , "Each layer shall have a different position in scalability space." );
 
 #if !H_3D_FCO
-     if ( numDiff  == 1 ) 
-     {
-       Bool inc = m_dimIds[ lastDiff ][ i ] > m_dimIds[ lastDiff ][ j ]; 
-       Bool shallBeButIsNotIncreasing = ( !inc  ) ; 
-       if ( shallBeButIsNotIncreasing )
-       {       
-         printf( "\nError: Positions of Layers %d and %d is not increasing in dimension %d \n", i, j, lastDiff);        
-       }
-       xConfirmPara( shallBeButIsNotIncreasing,  "DimensionIds shall be increasing within one dimension. " );
-     }
-#endif
-   }
- }
-
- /// ViewId 
- xConfirmPara( m_viewId.size() != m_iNumberOfViews, "The number of ViewIds must be equal to the number of views." ); 
+      if ( numDiff  == 1 ) 
+      {
+        Bool inc = m_dimIds[ lastDiff ][ i ] > m_dimIds[ lastDiff ][ j ]; 
+        Bool shallBeButIsNotIncreasing = ( !inc  ) ; 
+        if ( shallBeButIsNotIncreasing )
+        {       
+          printf( "\nError: Positions of Layers %d and %d is not increasing in dimension %d \n", i, j, lastDiff);        
+        }
+        xConfirmPara( shallBeButIsNotIncreasing,  "DimensionIds shall be increasing within one dimension. " );
+      }
+#endif
+    }
+  }
+
+  /// ViewId 
+  xConfirmPara( m_viewId.size() != m_iNumberOfViews, "The number of ViewIds must be equal to the number of views." ); 
 
   /// Layer sets
@@ -1532,18 +2416,18 @@
 
   // PTL
-    xConfirmPara( ( m_profile.size() != m_inblFlag.size() || m_profile.size() != m_level.size()  ||  m_profile.size() != m_levelTier.size() ), "The number of Profiles, Levels, Tiers and InblFlags must be equal." ); 
-
-    if ( m_numberOfLayers > 1)
-    {
-      xConfirmPara( m_profile.size() <= 1, "The number of profiles, tiers, levels, and inblFlags must be greater than 1.");
-      xConfirmPara( m_inblFlag[0], "VpsProfileTierLevel[0] must have inblFlag equal to 0");
-      if (m_profile.size() > 1 )
-      {
-        xConfirmPara( m_profile[0]  != m_profile[1], "The profile in VpsProfileTierLevel[1] must be equal to the profile in VpsProfileTierLevel[0].");
-        xConfirmPara( m_inblFlag[0] != m_inblFlag[1], "inblFlag in VpsProfileTierLevel[1] must be equal to the inblFlag in VpsProfileTierLevel[0].");
-      }
-    }
-
-    // Layer Dependencies  
+  xConfirmPara( ( m_profiles.size() != m_inblFlag.size() || m_profiles.size() != m_level.size()  ||  m_profiles.size() != m_levelTier.size() ), "The number of Profiles, Levels, Tiers and InblFlags must be equal." ); 
+
+  if ( m_numberOfLayers > 1)
+  {
+    xConfirmPara( m_profiles.size() <= 1, "The number of profiles, tiers, levels, and inblFlags must be greater than 1.");
+    xConfirmPara( m_inblFlag[0], "VpsProfileTierLevel[0] must have inblFlag equal to 0");
+    if (m_profiles.size() > 1 )
+    {
+      xConfirmPara( m_profiles[0]  != m_profiles[1], "The profile in VpsProfileTierLevel[1] must be equal to the profile in VpsProfileTierLevel[0].");
+      xConfirmPara( m_inblFlag[0] != m_inblFlag[1], "inblFlag in VpsProfileTierLevel[1] must be equal to the inblFlag in VpsProfileTierLevel[0].");
+    }
+  }
+
+  // Layer Dependencies  
   for (Int i = 0; i < m_numberOfLayers; i++ )
   {
@@ -1557,7 +2441,8 @@
   }  
 #endif
+
   xConfirmPara( m_iGOPSize < 1 ,                                                            "GOP Size must be greater or equal to 1" );
   xConfirmPara( m_iGOPSize > 1 &&  m_iGOPSize % 2,                                          "GOP Size must be a multiple of 2, if GOP Size is greater than 1" );
-#if H_MV
+#if NH_MV
   for( Int layer = 0; layer < m_numberOfLayers; layer++ )
   {
@@ -1567,5 +2452,4 @@
   xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < m_iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
 #endif
-#if ALLOW_RECOVERY_POINT_AS_RAP
   xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 3,                   "Decoding Refresh Type must be comprised between 0 and 3 included" );
   if(m_iDecodingRefreshType == 3)
@@ -1573,21 +2457,61 @@
     xConfirmPara( !m_recoveryPointSEIEnabled,                                               "When using RecoveryPointSEI messages as RA points, recoveryPointSEI must be enabled" );
   }
+
+  if (m_isField)
+  {
+    if (!m_pictureTimingSEIEnabled)
+    {
+      fprintf(stderr, "****************************************************************************\n");
+      fprintf(stderr, "** WARNING: Picture Timing SEI should be enabled for field coding!        **\n");
+      fprintf(stderr, "****************************************************************************\n");
+    }
+  }
+
+  if(m_crossComponentPredictionEnabledFlag && (m_chromaFormatIDC != CHROMA_444))
+  {
+    fprintf(stderr, "****************************************************************************\n");
+    fprintf(stderr, "** WARNING: Cross-component prediction is specified for 4:4:4 format only **\n");
+    fprintf(stderr, "****************************************************************************\n");
+
+    m_crossComponentPredictionEnabledFlag = false;
+  }
+
+  if ( m_CUTransquantBypassFlagForce && m_bUseHADME )
+  {
+    fprintf(stderr, "****************************************************************************\n");
+    fprintf(stderr, "** WARNING: --HadamardME has been disabled due to the enabling of         **\n");
+    fprintf(stderr, "**          --CUTransquantBypassFlagForce                                 **\n");
+    fprintf(stderr, "****************************************************************************\n");
+
+    m_bUseHADME = false; // this has been disabled so that the lambda is calculated slightly differently for lossless modes (as a result of JCTVC-R0104).
+  }
+
+  xConfirmPara (m_log2MaxTransformSkipBlockSize < 2, "Transform Skip Log2 Max Size must be at least 2 (4x4)");
+
+  if (m_log2MaxTransformSkipBlockSize!=2 && m_useTransformSkipFast)
+  {
+    fprintf(stderr, "***************************************************************************\n");
+    fprintf(stderr, "** WARNING: Transform skip fast is enabled (which only tests NxN splits),**\n");
+    fprintf(stderr, "**          but transform skip log2 max size is not 2 (4x4)              **\n");
+    fprintf(stderr, "**          It may be better to disable transform skip fast mode         **\n");
+    fprintf(stderr, "***************************************************************************\n");
+  }
+#if NH_MV
+  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
+  {
+    xConfirmPara( m_iQP[layer] <  -6 * (m_internalBitDepth[CHANNEL_TYPE_LUMA] - 8) || m_iQP[layer] > 51,      "QP exceeds supported range (-QpBDOffsety to 51)" );
+    xConfirmPara( m_DeblockingFilterMetric && (m_bLoopFilterDisable[layer] || m_loopFilterOffsetInPPS), "If DeblockingFilterMetric is true then both LoopFilterDisable and LoopFilterOffsetInPPS must be 0");
+  }
 #else
-  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 2,                   "Decoding Refresh Type must be equal to 0, 1 or 2" );
-#endif
-#if H_MV
-  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
-  {
-    xConfirmPara( m_iQP[layer] <  -6 * (m_internalBitDepthY - 8) || m_iQP[layer] > 51,      "QP exceeds supported range (-QpBDOffsety to 51)" );
-  }
-#else
-  xConfirmPara( m_iQP <  -6 * (m_internalBitDepthY - 8) || m_iQP > 51,                    "QP exceeds supported range (-QpBDOffsety to 51)" );
-#endif
-  xConfirmPara( m_loopFilterBetaOffsetDiv2 < -6 || m_loopFilterBetaOffsetDiv2 > 6,          "Loop Filter Beta Offset div. 2 exceeds supported range (-6 to 6)");
-  xConfirmPara( m_loopFilterTcOffsetDiv2 < -6 || m_loopFilterTcOffsetDiv2 > 6,              "Loop Filter Tc Offset div. 2 exceeds supported range (-6 to 6)");
+  xConfirmPara( m_iQP <  -6 * (m_internalBitDepth[CHANNEL_TYPE_LUMA] - 8) || m_iQP > 51,    "QP exceeds supported range (-QpBDOffsety to 51)" );
+  xConfirmPara( m_DeblockingFilterMetric && (m_bLoopFilterDisable || m_loopFilterOffsetInPPS), "If DeblockingFilterMetric is true then both LoopFilterDisable and LoopFilterOffsetInPPS must be 0");
+#endif
+  
+  xConfirmPara( m_loopFilterBetaOffsetDiv2 < -6 || m_loopFilterBetaOffsetDiv2 > 6,        "Loop Filter Beta Offset div. 2 exceeds supported range (-6 to 6)");
+  xConfirmPara( m_loopFilterTcOffsetDiv2 < -6 || m_loopFilterTcOffsetDiv2 > 6,            "Loop Filter Tc Offset div. 2 exceeds supported range (-6 to 6)");
   xConfirmPara( m_iFastSearch < 0 || m_iFastSearch > 2,                                     "Fast Search Mode is not supported value (0:Full search  1:Diamond  2:PMVFAST)" );
   xConfirmPara( m_iSearchRange < 0 ,                                                        "Search Range must be more than 0" );
   xConfirmPara( m_bipredSearchRange < 0 ,                                                   "Search Range must be more than 0" );
-#if H_MV
+#if NH_MV
   xConfirmPara( m_iVerticalDisparitySearchRange <= 0 ,                                      "Vertical Disparity Search Range must be more than 0" );
 #endif
@@ -1603,5 +2527,5 @@
   if (m_iDecodingRefreshType == 2)
   {
-#if H_MV
+#if NH_MV
     for (Int i = 0; i < m_numberOfLayers; i++ )
     {
@@ -1618,25 +2542,19 @@
   xConfirmPara( (m_iSourceWidth  % (m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
   xConfirmPara( (m_iSourceHeight % (m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
-  
+
   xConfirmPara( m_uiQuadtreeTULog2MinSize < 2,                                        "QuadtreeTULog2MinSize must be 2 or greater.");
   xConfirmPara( m_uiQuadtreeTULog2MaxSize > 5,                                        "QuadtreeTULog2MaxSize must be 5 or smaller.");
-  xConfirmPara( (1<<m_uiQuadtreeTULog2MaxSize) > m_uiMaxCUWidth,                                        "QuadtreeTULog2MaxSize must be log2(maxCUSize) or smaller.");
-  
   xConfirmPara( m_uiQuadtreeTULog2MaxSize < m_uiQuadtreeTULog2MinSize,                "QuadtreeTULog2MaxSize must be greater than or equal to m_uiQuadtreeTULog2MinSize.");
-  xConfirmPara( (1<<m_uiQuadtreeTULog2MinSize)>(m_uiMaxCUWidth >>(m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than minimum CU size" ); // HS
-  xConfirmPara( (1<<m_uiQuadtreeTULog2MinSize)>(m_uiMaxCUHeight>>(m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than minimum CU size" ); // HS
-  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) > ( m_uiMaxCUWidth  >> m_uiMaxCUDepth ), "Minimum CU width must be greater than minimum transform size." );
-  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) > ( m_uiMaxCUHeight >> m_uiMaxCUDepth ), "Minimum CU height must be greater than minimum transform size." );
+  xConfirmPara( (1<<m_uiQuadtreeTULog2MaxSize) > m_uiMaxCUWidth,                      "QuadtreeTULog2MaxSize must be log2(maxCUSize) or smaller.");
+  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) >= ( m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than or equal to minimum CU size" );
+  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) >= ( m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than or equal to minimum CU size" );
   xConfirmPara( m_uiQuadtreeTUMaxDepthInter < 1,                                                         "QuadtreeTUMaxDepthInter must be greater than or equal to 1" );
   xConfirmPara( m_uiMaxCUWidth < ( 1 << (m_uiQuadtreeTULog2MinSize + m_uiQuadtreeTUMaxDepthInter - 1) ), "QuadtreeTUMaxDepthInter must be less than or equal to the difference between log2(maxCUSize) and QuadtreeTULog2MinSize plus 1" );
   xConfirmPara( m_uiQuadtreeTUMaxDepthIntra < 1,                                                         "QuadtreeTUMaxDepthIntra must be greater than or equal to 1" );
   xConfirmPara( m_uiMaxCUWidth < ( 1 << (m_uiQuadtreeTULog2MinSize + m_uiQuadtreeTUMaxDepthIntra - 1) ), "QuadtreeTUMaxDepthInter must be less than or equal to the difference between log2(maxCUSize) and QuadtreeTULog2MinSize plus 1" );
-  
+
   xConfirmPara(  m_maxNumMergeCand < 1,  "MaxNumMergeCand must be 1 or greater.");
   xConfirmPara(  m_maxNumMergeCand > 5,  "MaxNumMergeCand must be 5 or smaller.");
-
-#if H_3D_ARP
-#endif
-#if H_3D_SPIVMP
+#if NH_3D
   xConfirmPara( m_log2SubPbSizeMinus3 < 0,                                        "Log2SubPbSizeMinus3 must be equal to 0 or greater.");
   xConfirmPara( m_log2SubPbSizeMinus3 > 3,                                        "Log2SubPbSizeMinus3 must be equal to 3 or smaller.");
@@ -1648,5 +2566,5 @@
 #endif
 #if ADAPTIVE_QP_SELECTION
-#if H_MV
+#if NH_MV
   for( Int layer = 0; layer < m_numberOfLayers; layer++ )
   {
@@ -1661,4 +2579,8 @@
   if( m_usePCM)
   {
+    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+    {
+      xConfirmPara(((m_MSBExtendedBitDepth[channelType] > m_internalBitDepth[channelType]) && m_bPCMInputBitDepthFlag), "PCM bit depth cannot be greater than internal bit depth (PCMInputBitDepthFlag cannot be used when InputBitDepth or MSBExtendedBitDepth > InternalBitDepth)");
+    }
     xConfirmPara(  m_uiPCMLog2MinSize < 3,                                      "PCMLog2MinSize must be 3 or greater.");
     xConfirmPara(  m_uiPCMLog2MinSize > 5,                                      "PCMLog2MinSize must be 5 or smaller.");
@@ -1677,19 +2599,21 @@
     xConfirmPara( m_sliceSegmentArgument < 1 ,         "SliceSegmentArgument should be larger than or equal to 1" );
   }
-  
+
   Bool tileFlag = (m_numTileColumnsMinus1 > 0 || m_numTileRowsMinus1 > 0 );
-  xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together");
-
-  //TODO:ChromaFmt assumes 4:2:0 below
-  xConfirmPara( m_iSourceWidth  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Picture width must be an integer multiple of the specified chroma subsampling");
-  xConfirmPara( m_iSourceHeight % TComSPS::getWinUnitY(CHROMA_420) != 0, "Picture height must be an integer multiple of the specified chroma subsampling");
-
-  xConfirmPara( m_aiPad[0] % TComSPS::getWinUnitX(CHROMA_420) != 0, "Horizontal padding must be an integer multiple of the specified chroma subsampling");
-  xConfirmPara( m_aiPad[1] % TComSPS::getWinUnitY(CHROMA_420) != 0, "Vertical padding must be an integer multiple of the specified chroma subsampling");
-
-  xConfirmPara( m_confWinLeft   % TComSPS::getWinUnitX(CHROMA_420) != 0, "Left conformance window offset must be an integer multiple of the specified chroma subsampling");
-  xConfirmPara( m_confWinRight  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Right conformance window offset must be an integer multiple of the specified chroma subsampling");
-  xConfirmPara( m_confWinTop    % TComSPS::getWinUnitY(CHROMA_420) != 0, "Top conformance window offset must be an integer multiple of the specified chroma subsampling");
-  xConfirmPara( m_confWinBottom % TComSPS::getWinUnitY(CHROMA_420) != 0, "Bottom conformance window offset must be an integer multiple of the specified chroma subsampling");
+  if (m_profile!=Profile::HIGHTHROUGHPUTREXT)
+  {
+    xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together, except in the High Throughput Intra 4:4:4 16 profile");
+  }
+
+  xConfirmPara( m_iSourceWidth  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Picture width must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_iSourceHeight % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Picture height must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_aiPad[0] % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Horizontal padding must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_aiPad[1] % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Vertical padding must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_confWinLeft   % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Left conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinRight  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Right conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinTop    % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Top conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinBottom % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Bottom conformance window offset must be an integer multiple of the specified chroma subsampling");
 
   xConfirmPara( m_defaultDisplayWindowFlag && !m_vuiParametersPresentFlag, "VUI needs to be enabled for default display window");
@@ -1697,16 +2621,16 @@
   if (m_defaultDisplayWindowFlag)
   {
-    xConfirmPara( m_defDispWinLeftOffset   % TComSPS::getWinUnitX(CHROMA_420) != 0, "Left default display window offset must be an integer multiple of the specified chroma subsampling");
-    xConfirmPara( m_defDispWinRightOffset  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Right default display window offset must be an integer multiple of the specified chroma subsampling");
-    xConfirmPara( m_defDispWinTopOffset    % TComSPS::getWinUnitY(CHROMA_420) != 0, "Top default display window offset must be an integer multiple of the specified chroma subsampling");
-    xConfirmPara( m_defDispWinBottomOffset % TComSPS::getWinUnitY(CHROMA_420) != 0, "Bottom default display window offset must be an integer multiple of the specified chroma subsampling");
-  }
-
-#if H_3D
+    xConfirmPara( m_defDispWinLeftOffset   % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Left default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinRightOffset  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Right default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinTopOffset    % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Top default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinBottomOffset % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Bottom default display window offset must be an integer multiple of the specified chroma subsampling");
+  }
+
+#if NH_3D
   xConfirmPara( m_pchCameraParameterFile    == 0                ,   "CameraParameterFile must be given");
   xConfirmPara( m_pchBaseViewCameraNumbers  == 0                ,   "BaseViewCameraNumbers must be given" );
   xConfirmPara( m_iNumberOfViews != m_cCameraData.getBaseViewNumbers().size() ,   "Number of Views in BaseViewCameraNumbers must be equal to NumberOfViews" );
   xConfirmPara    ( m_iCodedCamParPrecision < 0 || m_iCodedCamParPrecision > 5,       "CodedCamParsPrecision must be in range of 0..5" );
-#if H_3D_VSO
+#if NH_3D_VSO
     if( m_bUseVSO )
     {
@@ -1722,5 +2646,7 @@
     ui >>= 1;
     if( (ui & 1) == 1)
+    {
       xConfirmPara( ui != 1 , "Width should be 2^n");
+    }
   }
   ui = m_uiMaxCUHeight;
@@ -1729,8 +2655,10 @@
     ui >>= 1;
     if( (ui & 1) == 1)
+    {
       xConfirmPara( ui != 1 , "Height should be 2^n");
-  }
-
-#if H_MV
+    }
+  }
+
+#if NH_MV
   // validate that POC of same frame is identical across multiple layers
   Bool bErrorMvePoc = false;
@@ -1880,11 +2808,13 @@
       Int*      m_numReorderPics     = m_numReorderPicsMvc    [layer]; // It is not a member, but this name helps avoiding code duplication !!!
 #endif
+
   /* if this is an intra-only sequence, ie IntraPeriod=1, don't verify the GOP structure
    * This permits the ability to omit a GOP structure specification */
-#if H_MV
-  if (m_iIntraPeriod[layer] == 1 && m_GOPList[0].m_POC == -1) {
+#if NH_MV
+  if (m_iIntraPeriod[layer] == 1 && m_GOPList[0].m_POC == -1)
 #else
-  if (m_iIntraPeriod == 1 && m_GOPList[0].m_POC == -1) {
-#endif
+  if (m_iIntraPeriod == 1 && m_GOPList[0].m_POC == -1)
+#endif
+  {
     m_GOPList[0] = GOPEntry();
     m_GOPList[0].m_QPFactor = 1;
@@ -1894,5 +2824,9 @@
     m_GOPList[0].m_numRefPicsActive = 4;
   }
-  
+  else
+  {
+    xConfirmPara( m_intraConstraintFlag, "IntraConstraintFlag cannot be 1 for inter sequences");
+  }
+
   Bool verifiedGOP=false;
   Bool errorGOP=false;
@@ -1906,13 +2840,13 @@
   }
   Bool isOK[MAX_GOP];
-  for(Int i=0; i<MAX_GOP; i++) 
+  for(Int i=0; i<MAX_GOP; i++)
   {
     isOK[i]=false;
   }
   Int numOK=0;
-#if H_MV
+#if NH_MV
   xConfirmPara( m_iIntraPeriod[layer] >=0&&(m_iIntraPeriod[layer]%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" ); 
 #else
-xConfirmPara( m_iIntraPeriod >=0&&(m_iIntraPeriod%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" );
+  xConfirmPara( m_iIntraPeriod >=0&&(m_iIntraPeriod%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" );
 #endif
 
@@ -1924,9 +2858,9 @@
     }
   }
-  
-#if H_MV
-  if ( (m_iIntraPeriod[layer] != 1) && !m_loopFilterOffsetInPPS && m_DeblockingFilterControlPresent && (!m_bLoopFilterDisable[layer]) )
+
+#if NH_MV
+  if ( (m_iIntraPeriod[layer] != 1) && !m_loopFilterOffsetInPPS && (!m_bLoopFilterDisable[layer]) )
 #else
-  if ( (m_iIntraPeriod != 1) && !m_loopFilterOffsetInPPS && m_DeblockingFilterControlPresent && (!m_bLoopFilterDisable) )
+  if ( (m_iIntraPeriod != 1) && !m_loopFilterOffsetInPPS && (!m_bLoopFilterDisable) )
 #endif
   {
@@ -1937,13 +2871,14 @@
     }
   }
+
   m_extraRPSs=0;
   //start looping through frames in coding order until we can verify that the GOP structure is correct.
-  while(!verifiedGOP&&!errorGOP) 
+  while(!verifiedGOP&&!errorGOP)
   {
     Int curGOP = (checkGOP-1)%m_iGOPSize;
-    Int curPOC = ((checkGOP-1)/m_iGOPSize)*m_iGOPSize + m_GOPList[curGOP].m_POC;    
-    if(m_GOPList[curGOP].m_POC<0) 
-    {
-#if H_MV
+    Int curPOC = ((checkGOP-1)/m_iGOPSize)*m_iGOPSize + m_GOPList[curGOP].m_POC;
+    if(m_GOPList[curGOP].m_POC<0)
+    {
+#if NH_MV
       printf("\nError: found fewer Reference Picture Sets than GOPSize for layer %d\n", layer );
 #else
@@ -1952,9 +2887,9 @@
       errorGOP=true;
     }
-    else 
+    else
     {
       //check that all reference pictures are available, or have a POC < 0 meaning they might be available in the next GOP.
       Bool beforeI = false;
-      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++)
       {
         Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
@@ -1963,10 +2898,10 @@
           beforeI=true;
         }
-        else 
+        else
         {
           Bool found=false;
-          for(Int j=0; j<numRefs; j++) 
+          for(Int j=0; j<numRefs; j++)
           {
-            if(refList[j]==absPOC) 
+            if(refList[j]==absPOC)
             {
               found=true;
@@ -1986,5 +2921,5 @@
           if(!found)
           {
-#if H_MV
+#if NH_MV
             printf("\nError: ref pic %d is not available for GOP frame %d of layer %d\n", m_GOPList[curGOP].m_referencePics[i], curGOP+1, layer);
 #else
@@ -1998,5 +2933,5 @@
       {
         //all ref frames were present
-        if(!isOK[curGOP]) 
+        if(!isOK[curGOP])
         {
           numOK++;
@@ -2008,10 +2943,10 @@
         }
       }
-      else 
+      else
       {
         //create a new GOPEntry for this frame containing all the reference pictures that were available (POC > 0)
         m_GOPList[m_iGOPSize+m_extraRPSs]=m_GOPList[curGOP];
         Int newRefs=0;
-        for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+        for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++)
         {
           Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
@@ -2024,5 +2959,5 @@
         }
         Int numPrefRefs = m_GOPList[curGOP].m_numRefPicsActive;
-        
+
         for(Int offset = -1; offset>-checkGOP; offset--)
         {
@@ -2040,5 +2975,5 @@
               }
             }
-            for(Int i=0; i<newRefs; i++) 
+            for(Int i=0; i<newRefs; i++)
             {
               if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[i]==offPOC-curPOC)
@@ -2047,5 +2982,5 @@
               }
             }
-            if(newRef) 
+            if(newRef)
             {
               Int insertPoint=newRefs;
@@ -2095,5 +3030,5 @@
           Int refPics = m_GOPList[rIdx].m_numRefPics;
           Int newIdc=0;
-          for(Int i = 0; i<= refPics; i++) 
+          for(Int i = 0; i<= refPics; i++)
           {
             Int deltaPOC = ((i != refPics)? m_GOPList[rIdx].m_referencePics[i] : 0);  // check if the reference abs POC is >= 0
@@ -2117,7 +3052,7 @@
             newIdc++;
           }
-          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 1;  
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 1;
           m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = newIdc;
-          m_GOPList[m_iGOPSize+m_extraRPSs].m_deltaRPS = refPOC - m_GOPList[m_iGOPSize+m_extraRPSs].m_POC; 
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_deltaRPS = refPOC - m_GOPList[m_iGOPSize+m_extraRPSs].m_POC;
         }
         curGOP=m_iGOPSize+m_extraRPSs;
@@ -2125,8 +3060,8 @@
       }
       numRefs=0;
-      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++)
       {
         Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
-        if(absPOC >= 0) 
+        if(absPOC >= 0)
         {
           refList[numRefs]=absPOC;
@@ -2141,5 +3076,5 @@
   xConfirmPara(errorGOP,"Invalid GOP structure given");
   m_maxTempLayer = 1;
-  for(Int i=0; i<m_iGOPSize; i++) 
+  for(Int i=0; i<m_iGOPSize; i++)
   {
     if(m_GOPList[i].m_temporalId >= m_maxTempLayer)
@@ -2147,5 +3082,5 @@
       m_maxTempLayer = m_GOPList[i].m_temporalId+1;
     }
-    xConfirmPara(m_GOPList[i].m_sliceType!='B'&&m_GOPList[i].m_sliceType!='P'&&m_GOPList[i].m_sliceType!='I', "Slice type must be equal to B or P or I");
+    xConfirmPara(m_GOPList[i].m_sliceType!='B' && m_GOPList[i].m_sliceType!='P' && m_GOPList[i].m_sliceType!='I', "Slice type must be equal to B or P or I");
   }
   for(Int i=0; i<MAX_TLAYER; i++)
@@ -2154,5 +3089,5 @@
     m_maxDecPicBuffering[i] = 1;
   }
-  for(Int i=0; i<m_iGOPSize; i++) 
+  for(Int i=0; i<m_iGOPSize; i++)
   {
     if(m_GOPList[i].m_numRefPics+1 > m_maxDecPicBuffering[m_GOPList[i].m_temporalId])
@@ -2160,5 +3095,5 @@
       m_maxDecPicBuffering[m_GOPList[i].m_temporalId] = m_GOPList[i].m_numRefPics + 1;
     }
-    Int highestDecodingNumberWithLowerPOC = 0; 
+    Int highestDecodingNumberWithLowerPOC = 0;
     for(Int j=0; j<m_iGOPSize; j++)
     {
@@ -2171,10 +3106,10 @@
     for(Int j=0; j<highestDecodingNumberWithLowerPOC; j++)
     {
-      if(m_GOPList[j].m_temporalId <= m_GOPList[i].m_temporalId && 
+      if(m_GOPList[j].m_temporalId <= m_GOPList[i].m_temporalId &&
         m_GOPList[j].m_POC > m_GOPList[i].m_POC)
       {
         numReorder++;
       }
-    }    
+    }
     if(numReorder > m_numReorderPics[m_GOPList[i].m_temporalId])
     {
@@ -2182,5 +3117,5 @@
     }
   }
-  for(Int i=0; i<MAX_TLAYER-1; i++) 
+  for(Int i=0; i<MAX_TLAYER-1; i++)
   {
     // a lower layer can not have higher value of m_numReorderPics than a higher layer
@@ -2201,5 +3136,4 @@
   }
 
-
   // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ] -  1, inclusive
   if(m_numReorderPics[MAX_TLAYER-1] > m_maxDecPicBuffering[MAX_TLAYER-1] - 1)
@@ -2209,5 +3143,5 @@
 
   if(m_vuiParametersPresentFlag && m_bitstreamRestrictionFlag)
-  { 
+  {
     Int PicSizeInSamplesY =  m_iSourceWidth * m_iSourceHeight;
     if(tileFlag)
@@ -2221,12 +3155,12 @@
         maxTileWidth = m_uiMaxCUWidth*((widthInCU+m_numTileColumnsMinus1)/(m_numTileColumnsMinus1+1));
         maxTileHeight = m_uiMaxCUHeight*((heightInCU+m_numTileRowsMinus1)/(m_numTileRowsMinus1+1));
-        // if only the last tile-row is one treeblock higher than the others 
+        // if only the last tile-row is one treeblock higher than the others
         // the maxTileHeight becomes smaller if the last row of treeblocks has lower height than the others
         if(!((heightInCU-1)%(m_numTileRowsMinus1+1)))
         {
           maxTileHeight = maxTileHeight - m_uiMaxCUHeight + (m_iSourceHeight % m_uiMaxCUHeight);
-        }     
-        // if only the last tile-column is one treeblock wider than the others 
-        // the maxTileWidth becomes smaller if the last column of treeblocks has lower width than the others   
+        }
+        // if only the last tile-column is one treeblock wider than the others
+        // the maxTileWidth becomes smaller if the last column of treeblocks has lower width than the others
         if(!((widthInCU-1)%(m_numTileColumnsMinus1+1)))
         {
@@ -2272,5 +3206,5 @@
       m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/((2*m_iSourceHeight+m_iSourceWidth)*m_uiMaxCUHeight)-4;
     }
-    else if(m_sliceMode == 1)
+    else if(m_sliceMode == FIXED_NUMBER_OF_CTU)
     {
       m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/(m_sliceArgument*m_uiMaxCUWidth*m_uiMaxCUHeight)-4;
@@ -2281,7 +3215,6 @@
     }
   }
+
   xConfirmPara( m_iWaveFrontSynchro < 0, "WaveFrontSynchro cannot be negative" );
-  xConfirmPara( m_iWaveFrontSubstreams <= 0, "WaveFrontSubstreams must be positive" );
-  xConfirmPara( m_iWaveFrontSubstreams > 1 && !m_iWaveFrontSynchro, "Must have WaveFrontSynchro > 0 in order to have WaveFrontSubstreams > 1" );
 
   xConfirmPara( m_decodedPictureHashSEIEnabled<0 || m_decodedPictureHashSEIEnabled>3, "this hash type is not correct!\n");
@@ -2299,4 +3232,19 @@
   }
 
+  if (m_kneeSEIEnabled && !m_kneeSEICancelFlag)
+  {
+    xConfirmPara( m_kneeSEINumKneePointsMinus1 < 0 || m_kneeSEINumKneePointsMinus1 > 998, "SEIKneeFunctionNumKneePointsMinus1 must be in the range of 0 to 998");
+    for ( UInt i=0; i<=m_kneeSEINumKneePointsMinus1; i++ )
+    {
+      xConfirmPara( m_kneeSEIInputKneePoint[i] < 1 || m_kneeSEIInputKneePoint[i] > 999, "SEIKneeFunctionInputKneePointValue must be in the range of 1 to 999");
+      xConfirmPara( m_kneeSEIOutputKneePoint[i] < 0 || m_kneeSEIOutputKneePoint[i] > 1000, "SEIKneeFunctionInputKneePointValue must be in the range of 0 to 1000");
+      if ( i > 0 )
+      {
+        xConfirmPara( m_kneeSEIInputKneePoint[i-1] >= m_kneeSEIInputKneePoint[i],  "The i-th SEIKneeFunctionInputKneePointValue must be greater than the (i-1)-th value");
+        xConfirmPara( m_kneeSEIOutputKneePoint[i-1] > m_kneeSEIOutputKneePoint[i],  "The i-th SEIKneeFunctionOutputKneePointValue must be greater than or equal to the (i-1)-th value");
+      }
+    }
+  }
+
   if ( m_RCEnableRateControl )
   {
@@ -2311,5 +3259,5 @@
     xConfirmPara( m_uiDeltaQpRD > 0, "Rate control cannot be used together with slice level multiple-QP optimization!\n" );
   }
-#if H_MV
+#if NH_MV
   // VPS VUI
   for(Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++ )
@@ -2337,10 +3285,10 @@
 
   xConfirmPara(m_log2ParallelMergeLevel < 2, "Log2ParallelMergeLevel should be larger than or equal to 2");
+
   if (m_framePackingSEIEnabled)
   {
     xConfirmPara(m_framePackingSEIType < 3 || m_framePackingSEIType > 5 , "SEIFramePackingType must be in rage 3 to 5");
   }
-
-#if H_MV
+#if NH_MV
   }
   }
@@ -2363,4 +3311,21 @@
   }
 #endif
+
+  if (m_segmentedRectFramePackingSEIEnabled)
+  {
+    xConfirmPara(m_framePackingSEIEnabled > 0 , "SEISegmentedRectFramePacking must be 0 when SEIFramePacking is 1");
+  }
+
+  if((m_numTileColumnsMinus1 <= 0) && (m_numTileRowsMinus1 <= 0) && m_tmctsSEIEnabled)
+  {
+    printf("Warning: SEITempMotionConstrainedTileSets is set to false to disable temporal motion-constrained tile sets SEI message because there are no tiles enabled.\n");
+    m_tmctsSEIEnabled = false;
+  }
+
+  if(m_timeCodeSEIEnabled)
+  {
+    xConfirmPara(m_timeCodeSEINumTs > MAX_TIMECODE_SEI_SETS, "Number of time sets cannot exceed 3");
+  }
+
 #undef xConfirmPara
   if (check_failed)
@@ -2370,26 +3335,21 @@
 }
 
-/** \todo use of global variables should be removed later
- */
-Void TAppEncCfg::xSetGlobal()
+const Char *profileToString(const Profile::Name profile)
 {
-  // set max CU width & height
-  g_uiMaxCUWidth  = m_uiMaxCUWidth;
-  g_uiMaxCUHeight = m_uiMaxCUHeight;
-  
-  // compute actual CU depth with respect to config depth and max transform size
-  g_uiAddCUDepth  = 0;
-  while( (m_uiMaxCUWidth>>m_uiMaxCUDepth) > ( 1 << ( m_uiQuadtreeTULog2MinSize + g_uiAddCUDepth )  ) ) g_uiAddCUDepth++;
-  
-  m_uiMaxCUDepth += g_uiAddCUDepth;
-  g_uiAddCUDepth++;
-  g_uiMaxCUDepth = m_uiMaxCUDepth;
-  
-  // set internal bit-depth and constants
-  g_bitDepthY = m_internalBitDepthY;
-  g_bitDepthC = m_internalBitDepthC;
-  
-  g_uiPCMBitDepthLuma = m_bPCMInputBitDepthFlag ? m_inputBitDepthY : m_internalBitDepthY;
-  g_uiPCMBitDepthChroma = m_bPCMInputBitDepthFlag ? m_inputBitDepthC : m_internalBitDepthC;
+  static const UInt numberOfProfiles = sizeof(strToProfile)/sizeof(*strToProfile);
+
+  for (UInt profileIndex = 0; profileIndex < numberOfProfiles; profileIndex++)
+  {
+    if (strToProfile[profileIndex].value == profile)
+    {
+      return strToProfile[profileIndex].str;
+    }
+  }
+
+  //if we get here, we didn't find this profile in the list - so there is an error
+  std::cerr << "ERROR: Unknown profile \"" << profile << "\" in profileToString" << std::endl;
+  assert(false);
+  exit(1);
+  return "";
 }
 
@@ -2397,22 +3357,22 @@
 {
   printf("\n");
-#if H_MV
+#if NH_MV
   for( Int layer = 0; layer < m_numberOfLayers; layer++)
   {
-    printf("Input File %i                 : %s\n", layer, m_pchInputFileList[layer]);
+    printf("Input File %i                     : %s\n", layer, m_pchInputFileList[layer]);
   }
 #else
-  printf("Input          File          : %s\n", m_pchInputFile          );
-#endif
-  printf("Bitstream      File          : %s\n", m_pchBitstreamFile      );
-#if H_MV
+  printf("Input          File               : %s\n", m_pchInputFile          );
+#endif
+  printf("Bitstream      File               : %s\n", m_pchBitstreamFile      );
+#if NH_MV
   for( Int layer = 0; layer < m_numberOfLayers; layer++)
   {
-    printf("Reconstruction File %i        : %s\n", layer, m_pchReconFileList[layer]);
+    printf("Reconstruction File %i            : %s\n", layer, m_pchReconFileList[layer]);
   }
 #else
-  printf("Reconstruction File          : %s\n", m_pchReconFile          );
-#endif
-#if H_MV
+  printf("Reconstruction File               : %s\n", m_pchReconFile          );
+#endif
+#if NH_MV
   xPrintParaVector( "NuhLayerId"     , m_layerIdInNuh ); 
   if ( m_targetEncLayerIdList.size() > 0)
@@ -2421,73 +3381,176 @@
   }
   xPrintParaVector( "ViewIdVal"     , m_viewId ); 
-  xPrintParaVector( "ViewOrderIndex", m_viewOrderIndex ); 
+  xPrintParaVector( "ViewOrderIdx"  , m_viewOrderIndex ); 
   xPrintParaVector( "AuxId", m_auxId );
 #endif
-#if H_3D
-  xPrintParaVector( "DepthFlag", m_depthFlag ); 
-  printf("Coded Camera Param. Precision: %d\n", m_iCodedCamParPrecision);
-#endif
-#if H_MV  
+#if NH_3D
+  xPrintParaVector( "DepthLayerFlag", m_depthFlag ); 
+  printf("Coded Camera Param. Precision     : %d\n", m_iCodedCamParPrecision);  
+#endif
+#if NH_MV  
   xPrintParaVector( "QP"               , m_fQP                ); 
   xPrintParaVector( "LoopFilterDisable", m_bLoopFilterDisable ); 
   xPrintParaVector( "SAO"              , m_bUseSAO            ); 
 #endif
-  printf("Real     Format              : %dx%d %dHz\n", m_iSourceWidth - m_confWinLeft - m_confWinRight, m_iSourceHeight - m_confWinTop - m_confWinBottom, m_iFrameRate );
-  printf("Internal Format              : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+
+  printf("Real     Format                   : %dx%d %dHz\n", m_iSourceWidth - m_confWinLeft - m_confWinRight, m_iSourceHeight - m_confWinTop - m_confWinBottom, m_iFrameRate );
+  printf("Internal Format                   : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+  printf("Sequence PSNR output              : %s\n", (m_printMSEBasedSequencePSNR ? "Linear average, MSE-based" : "Linear average only") );
+  printf("Sequence MSE output               : %s\n", (m_printSequenceMSE ? "Enabled" : "Disabled") );
+  printf("Frame MSE output                  : %s\n", (m_printFrameMSE    ? "Enabled" : "Disabled") );
+  printf("Cabac-zero-word-padding           : %s\n", (m_cabacZeroWordPaddingEnabled? "Enabled" : "Disabled") );
   if (m_isField)
   {
-    printf("Frame/Field          : Field based coding\n");
-    printf("Field index          : %u - %d (%d fields)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
-    if (m_isTopFieldFirst)
-    {
-      printf("Field Order            : Top field first\n");
+    printf("Frame/Field                       : Field based coding\n");
+    printf("Field index                       : %u - %d (%d fields)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+    printf("Field Order                       : %s field first\n", m_isTopFieldFirst?"Top":"Bottom");
+
+  }
+  else
+  {
+    printf("Frame/Field                       : Frame based coding\n");
+    printf("Frame index                       : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+  }
+#if NH_MV
+  printf("Profile                           :");
+  for (Int i = 0; i < m_profiles.size(); i++)
+  {
+    Profile::Name m_profile = m_profiles[i];
+
+#endif
+    if (m_profile == Profile::MAINREXT)
+    {
+    ExtendedProfileName validProfileName;
+    if (m_onePictureOnlyConstraintFlag)
+    {
+      validProfileName = m_bitDepthConstraint == 8 ? MAIN_444_STILL_PICTURE : (m_bitDepthConstraint == 16 ? MAIN_444_16_STILL_PICTURE : NONE);
     }
     else
     {
-      printf("Field Order            : Bottom field first\n");
-    }
-  }
-  else
-  {
-    printf("Frame/Field                  : Frame based coding\n");
-  printf("Frame index                  : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
-  }
-  printf("CU size / depth              : %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth );
-  printf("RQT trans. size (min / max)  : %d / %d\n", 1 << m_uiQuadtreeTULog2MinSize, 1 << m_uiQuadtreeTULog2MaxSize );
-  printf("Max RQT depth inter          : %d\n", m_uiQuadtreeTUMaxDepthInter);
-  printf("Max RQT depth intra          : %d\n", m_uiQuadtreeTUMaxDepthIntra);
-  printf("Min PCM size                 : %d\n", 1 << m_uiPCMLog2MinSize);
-  printf("Motion search range          : %d\n", m_iSearchRange );
-#if H_MV
-  printf("Disp search range restriction: %d\n", m_bUseDisparitySearchRangeRestriction );
-  printf("Vertical disp search range   : %d\n", m_iVerticalDisparitySearchRange );
-#endif
-#if H_MV
+      const UInt intraIdx = m_intraConstraintFlag ? 1:0;
+      const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
+      const UInt chromaFormatIdx = UInt(m_chromaFormatConstraint);
+      validProfileName = (bitDepthIdx > 3 || chromaFormatIdx>3) ? NONE : validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx];
+    }
+      std::string rextSubProfile;
+      if (validProfileName!=NONE)
+      {
+        rextSubProfile=enumToString(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), validProfileName);
+      }
+      if (rextSubProfile == "main_444_16")
+      {
+        rextSubProfile="main_444_16 [NON STANDARD]";
+      }
+#if NH_MV
+      printf(" %s (%s) ", profileToString(m_profile), (rextSubProfile.empty())?"INVALID REXT PROFILE":rextSubProfile.c_str() );
+#else
+      printf("Profile                           : %s (%s)\n", profileToString(m_profile), (rextSubProfile.empty())?"INVALID REXT PROFILE":rextSubProfile.c_str() );
+#endif
+    }
+    else
+    {
+#if NH_MV
+      printf(" %s ", profileToString(m_profile) );
+#else
+      printf("Profile                           : %s\n", profileToString(m_profile) );
+#endif
+    }
+#if NH_MV    
+  }
+  printf("\n");
+#endif
+
+  printf("CU size / depth / total-depth     : %d / %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth, m_uiMaxTotalCUDepth );
+  printf("RQT trans. size (min / max)       : %d / %d\n", 1 << m_uiQuadtreeTULog2MinSize, 1 << m_uiQuadtreeTULog2MaxSize );
+  printf("Max RQT depth inter               : %d\n", m_uiQuadtreeTUMaxDepthInter);
+  printf("Max RQT depth intra               : %d\n", m_uiQuadtreeTUMaxDepthIntra);
+  printf("Min PCM size                      : %d\n", 1 << m_uiPCMLog2MinSize);
+  printf("Motion search range               : %d\n", m_iSearchRange );
+#if NH_MV
+  printf("Disp search range restriction     : %d\n", m_bUseDisparitySearchRangeRestriction );
+  printf("Vertical disp search range        : %d\n", m_iVerticalDisparitySearchRange );
+#endif
+#if NH_MV
   xPrintParaVector( "Intra period", m_iIntraPeriod );
 #else
-  printf("Intra period                 : %d\n", m_iIntraPeriod );
-#endif
-  printf("Decoding refresh type        : %d\n", m_iDecodingRefreshType );
-#if !H_MV
-  printf("QP                           : %5.2f\n", m_fQP );
-#endif
-  printf("Max dQP signaling depth      : %d\n", m_iMaxCuDQPDepth);
-
-  printf("Cb QP Offset                 : %d\n", m_cbQpOffset   );
-  printf("Cr QP Offset                 : %d\n", m_crQpOffset);
-
-  printf("QP adaptation                : %d (range=%d)\n", m_bUseAdaptiveQP, (m_bUseAdaptiveQP ? m_iQPAdaptationRange : 0) );
-  printf("GOP size                     : %d\n", m_iGOPSize );
-  printf("Internal bit depth           : (Y:%d, C:%d)\n", m_internalBitDepthY, m_internalBitDepthC );
-  printf("PCM sample bit depth         : (Y:%d, C:%d)\n", g_uiPCMBitDepthLuma, g_uiPCMBitDepthChroma );
-  printf("RateControl                  : %d\n", m_RCEnableRateControl );
+  printf("Intra period                      : %d\n", m_iIntraPeriod );
+#endif
+  printf("Decoding refresh type             : %d\n", m_iDecodingRefreshType );
+#if !NH_MV
+  printf("QP                                : %5.2f\n", m_fQP );
+#endif
+  printf("Max dQP signaling depth           : %d\n", m_iMaxCuDQPDepth);
+
+  printf("Cb QP Offset                      : %d\n", m_cbQpOffset   );
+  printf("Cr QP Offset                      : %d\n", m_crQpOffset);
+  printf("QP adaptation                     : %d (range=%d)\n", m_bUseAdaptiveQP, (m_bUseAdaptiveQP ? m_iQPAdaptationRange : 0) );
+  printf("GOP size                          : %d\n", m_iGOPSize );
+  printf("Input bit depth                   : (Y:%d, C:%d)\n", m_inputBitDepth[CHANNEL_TYPE_LUMA], m_inputBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("MSB-extended bit depth            : (Y:%d, C:%d)\n", m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA], m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("Internal bit depth                : (Y:%d, C:%d)\n", m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("PCM sample bit depth              : (Y:%d, C:%d)\n", m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA] : m_internalBitDepth[CHANNEL_TYPE_LUMA],
+                                                               m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] : m_internalBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("Intra reference smoothing         : %s\n", (m_enableIntraReferenceSmoothing          ? "Enabled" : "Disabled") );
+  printf("diff_cu_chroma_qp_offset_depth         : %d\n", m_diffCuChromaQpOffsetDepth);
+  printf("extended_precision_processing_flag     : %s\n", (m_extendedPrecisionProcessingFlag         ? "Enabled" : "Disabled") );
+  printf("implicit_rdpcm_enabled_flag            : %s\n", (m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ? "Enabled" : "Disabled") );
+  printf("explicit_rdpcm_enabled_flag            : %s\n", (m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ? "Enabled" : "Disabled") );
+  printf("transform_skip_rotation_enabled_flag   : %s\n", (m_transformSkipRotationEnabledFlag        ? "Enabled" : "Disabled") );
+  printf("transform_skip_context_enabled_flag    : %s\n", (m_transformSkipContextEnabledFlag         ? "Enabled" : "Disabled") );
+  printf("cross_component_prediction_enabled_flag: %s\n", (m_crossComponentPredictionEnabledFlag     ? (m_reconBasedCrossCPredictionEstimate ? "Enabled (reconstructed-residual-based estimate)" : "Enabled (encoder-side-residual-based estimate)") : "Disabled") );
+  printf("high_precision_offsets_enabled_flag    : %s\n", (m_highPrecisionOffsetsEnabledFlag         ? "Enabled" : "Disabled") );
+  printf("persistent_rice_adaptation_enabled_flag: %s\n", (m_persistentRiceAdaptationEnabledFlag     ? "Enabled" : "Disabled") );
+  printf("cabac_bypass_alignment_enabled_flag    : %s\n", (m_cabacBypassAlignmentEnabledFlag         ? "Enabled" : "Disabled") );
+#if NH_MV
+  Bool anySAO = false; 
+  IntAry1d saoOffBitShiftL;
+  IntAry1d saoOffBitShiftC;
+
+  for (Int i = 0; i < m_numberOfLayers; i++)
+  {
+    if ( m_bUseSAO[i] )
+    {
+      anySAO = true; 
+      saoOffBitShiftL.push_back( m_log2SaoOffsetScale[i][CHANNEL_TYPE_LUMA] );
+      saoOffBitShiftC.push_back( m_log2SaoOffsetScale[i][CHANNEL_TYPE_CHROMA] );
+    }
+    else
+    {
+      saoOffBitShiftL.push_back( -1 );
+      saoOffBitShiftC.push_back( -1 );
+    }
+  }
+  if (anySAO)
+  {
+    xPrintParaVector( "Sao Luma Offset bit shifts"  , saoOffBitShiftL );
+    xPrintParaVector( "Sao Chroma Offset bit shifts", saoOffBitShiftC );
+  }
+#else
+  if (m_bUseSAO)
+  {
+    printf("log2_sao_offset_scale_luma             : %d\n", m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA]);
+    printf("log2_sao_offset_scale_chroma           : %d\n", m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA]);
+  }
+#endif
+
+  switch (m_costMode)
+  {
+    case COST_STANDARD_LOSSY:               printf("Cost function:                    : Lossy coding (default)\n"); break;
+    case COST_SEQUENCE_LEVEL_LOSSLESS:      printf("Cost function:                    : Sequence_level_lossless coding\n"); break;
+    case COST_LOSSLESS_CODING:              printf("Cost function:                    : Lossless coding with fixed QP of %d\n", LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP); break;
+    case COST_MIXED_LOSSLESS_LOSSY_CODING:  printf("Cost function:                    : Mixed_lossless_lossy coding with QP'=%d for lossless evaluation\n", LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME); break;
+    default:                                printf("Cost function:                    : Unknown\n"); break;
+  }
+
+  printf("RateControl                       : %d\n", m_RCEnableRateControl );
+
   if(m_RCEnableRateControl)
   {
-    printf("TargetBitrate                : %d\n", m_RCTargetBitrate );
-    printf("KeepHierarchicalBit          : %d\n", m_RCKeepHierarchicalBit );
-    printf("LCULevelRC                   : %d\n", m_RCLCULevelRC );
-    printf("UseLCUSeparateModel          : %d\n", m_RCUseLCUSeparateModel );
-    printf("InitialQP                    : %d\n", m_RCInitialQP );
-    printf("ForceIntraQP                 : %d\n", m_RCForceIntraQP );
+    printf("TargetBitrate                     : %d\n", m_RCTargetBitrate );
+    printf("KeepHierarchicalBit               : %d\n", m_RCKeepHierarchicalBit );
+    printf("LCULevelRC                        : %d\n", m_RCLCULevelRC );
+    printf("UseLCUSeparateModel               : %d\n", m_RCUseLCUSeparateModel );
+    printf("InitialQP                         : %d\n", m_RCInitialQP );
+    printf("ForceIntraQP                      : %d\n", m_RCForceIntraQP );
 
 #if KWU_RC_MADPRED_E0227
@@ -2509,33 +3572,37 @@
     }
 #endif
-  }
-  printf("Max Num Merge Candidates     : %d\n", m_maxNumMergeCand);
-#if H_3D
-  printf("BaseViewCameraNumbers        : %s\n", m_pchBaseViewCameraNumbers ); 
-  printf("Coded Camera Param. Precision: %d\n", m_iCodedCamParPrecision);
-#if H_3D_VSO
-  printf("Force use of Lambda Scale    : %d\n", m_bForceLambdaScaleVSO );
+
+  }
+
+  printf("Max Num Merge Candidates          : %d\n", m_maxNumMergeCand);
+#if NH_3D
+  printf("BaseViewCameraNumbers             : %s\n", m_pchBaseViewCameraNumbers ); 
+  printf("Coded Camera Param. Precision     : %d\n", m_iCodedCamParPrecision);
+#if NH_3D_VSO
+  printf("Force use of Lambda Scale         : %d\n", m_bForceLambdaScaleVSO );
 
   if ( m_bUseVSO )
   {    
-    printf("VSO Lambda Scale             : %5.2f\n", m_dLambdaScaleVSO );
-    printf("VSO Mode                     : %d\n",    m_uiVSOMode       );
-    printf("VSO Config                   : %s\n",    m_pchVSOConfig    );
-    printf("VSO Negative Distortion      : %d\n",    m_bAllowNegDist ? 1 : 0);
-    printf("VSO LS Table                 : %d\n",    m_bVSOLSTable ? 1 : 0);
-    printf("VSO Estimated VSD            : %d\n",    m_bUseEstimatedVSD ? 1 : 0);
-    printf("VSO Early Skip               : %d\n",    m_bVSOEarlySkip ? 1 : 0);   
+    printf("VSO Lambda Scale                  : %5.2f\n", m_dLambdaScaleVSO );
+    printf("VSO Mode                          : %d\n",    m_uiVSOMode       );
+    printf("VSO Config                        : %s\n",    m_pchVSOConfig    );
+    printf("VSO Negative Distortion           : %d\n",    m_bAllowNegDist ? 1 : 0);
+    printf("VSO LS Table                      : %d\n",    m_bVSOLSTable ? 1 : 0);
+    printf("VSO Estimated VSD                 : %d\n",    m_bUseEstimatedVSD ? 1 : 0);
+    printf("VSO Early Skip                    : %d\n",    m_bVSOEarlySkip ? 1 : 0);   
     if ( m_bUseWVSO )
-    printf("Dist. Weights (VSO/VSD/SAD)  : %d/%d/%d\n ", m_iVSOWeight, m_iVSDWeight, m_iDWeight );
+    {
+      printf("Dist. Weights (VSO/VSD/SAD)       : %d/%d/%d\n ", m_iVSOWeight, m_iVSDWeight, m_iDWeight );    
+    }    
   }
 #endif //HHI_VSO
 #endif //H_3D
   printf("\n");
-#if H_MV
+#if NH_MV
   printf("TOOL CFG General: ");
 #else
   printf("TOOL CFG: ");
 #endif
-  printf("IBD:%d ", g_bitDepthY > m_inputBitDepthY || g_bitDepthC > m_inputBitDepthC);
+  printf("IBD:%d ", ((m_internalBitDepth[CHANNEL_TYPE_LUMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA]) || (m_internalBitDepth[CHANNEL_TYPE_CHROMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA])));
   printf("HAD:%d ", m_bUseHADME           );
   printf("RDQ:%d ", m_useRDOQ            );
@@ -2552,22 +3619,24 @@
   printf("TransformSkip:%d ",     m_useTransformSkip              );
   printf("TransformSkipFast:%d ", m_useTransformSkipFast       );
+  printf("TransformSkipLog2MaxSize:%d ", m_log2MaxTransformSkipBlockSize);
   printf("Slice: M=%d ", m_sliceMode);
-  if (m_sliceMode!=0)
+  if (m_sliceMode!=NO_SLICES)
   {
     printf("A=%d ", m_sliceArgument);
   }
   printf("SliceSegment: M=%d ",m_sliceSegmentMode);
-  if (m_sliceSegmentMode!=0)
+  if (m_sliceSegmentMode!=NO_SLICES)
   {
     printf("A=%d ", m_sliceSegmentArgument);
   }
   printf("CIP:%d ", m_bUseConstrainedIntraPred);
-#if !H_MV
+#if !NH_MV
   printf("SAO:%d ", (m_bUseSAO)?(1):(0));
 #endif
   printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
+
   if (m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce)
   {
-    printf("TransQuantBypassEnabled: =1 ");
+    printf("TransQuantBypassEnabled: =1");
   }
   else
@@ -2575,22 +3644,24 @@
     printf("TransQuantBypassEnabled:%d ", (m_TransquantBypassEnableFlag)? 1:0 );
   }
+
   printf("WPP:%d ", (Int)m_useWeightedPred);
   printf("WPB:%d ", (Int)m_useWeightedBiPred);
   printf("PME:%d ", m_log2ParallelMergeLevel);
+  const Int iWaveFrontSubstreams = m_iWaveFrontSynchro ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
   printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d",
-          m_iWaveFrontSynchro, m_iWaveFrontSubstreams);
+          m_iWaveFrontSynchro, iWaveFrontSubstreams);
   printf(" ScalingList:%d ", m_useScalingListId );
   printf("TMVPMode:%d ", m_TMVPModeId     );
 #if ADAPTIVE_QP_SELECTION
-  printf("AQpS:%d ", m_bUseAdaptQpSelect   );
+  printf("AQpS:%d", m_bUseAdaptQpSelect   );
 #endif
 
   printf(" SignBitHidingFlag:%d ", m_signHideFlag);
-  printf("RecalQP:%d ", m_recalculateQPAccordingToLambda ? 1 : 0 );
-#if H_3D_VSO
-  printf("VSO:%d ", m_bUseVSO   );
+  printf("RecalQP:%d", m_recalculateQPAccordingToLambda ? 1 : 0 );
+#if NH_3D_VSO
+  printf(" VSO:%d ", m_bUseVSO   );
   printf("WVSO:%d ", m_bUseWVSO );  
 #endif
-#if H_3D
+#if NH_3D
   printf( "QTL:%d "                  , m_bUseQTL);
   printf( "IlluCompEnable:%d "       , m_abUseIC);
@@ -2617,5 +3688,5 @@
 #endif
 
-  printf("\n\n");  
+  printf("\n\n");
 
   fflush(stdout);
@@ -2625,6 +3696,8 @@
 {
   if (!bflag)
+  {
     return false;
-  
+  }
+
   printf("Error: %s\n",message);
   return true;
Index: branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncCfg.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncCfg.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -44,5 +44,5 @@
 #include <sstream>
 #include <vector>
-#if H_3D
+#if NH_3D
 #include "TAppCommon/TAppComCamPara.h"
 #include "TLibRenderer/TRenModel.h"
@@ -61,5 +61,5 @@
 protected:
   // file I/O
-#if H_MV
+#if NH_MV
   std::vector<char*>     m_pchInputFileList;                  ///< source file names
 #else
@@ -67,5 +67,5 @@
 #endif
   Char*     m_pchBitstreamFile;                               ///< output bitstream file
-#if H_MV
+#if NH_MV
   std::vector<char*>     m_pchReconFileList;                  ///< output reconstruction file names
   Int                    m_numberOfLayers;                    ///< number of Layers to Encode
@@ -74,11 +74,11 @@
   Char*     m_pchReconFile;                                   ///< output reconstruction file
 #endif
-  #if H_MV
+  #if NH_MV
 // VPS specification
-  std::vector< std::vector<Int> > m_dimIds;                   ///< dimension ids ( pointers to m_viewId and m_depthFlag 
+  IntAry2d m_dimIds;                   ///< dimension ids ( pointers to m_viewId and m_depthFlag 
   std::vector<Int>       m_viewId;                            ///< view id
   std::vector<Int>       m_viewOrderIndex;                    ///< view order index  
   std::vector<Int>       m_auxId;                             ///< auxiliary id
-#if H_3D
+#if NH_3D
   std::vector<Int>       m_depthFlag;                         ///< depth flag
 #endif
@@ -91,17 +91,17 @@
 // layer sets   
   Int                    m_vpsNumLayerSets;                   ///< Number of layer sets
-  std::vector< std::vector<Int> > m_layerIdsInSets;           ///< LayerIds in vps of layer set 
+  IntAry2d m_layerIdsInSets;           ///< LayerIds in vps of layer set 
   Int                    m_numAddLayerSets;                    ///< Number of additional layer sets
-  std::vector< std::vector<Int> > m_highestLayerIdxPlus1;      ///< HighestLayerIdxPlus1 for each additional layer set and each independent layer (value with index 0 will be ignored)
+  IntAry2d m_highestLayerIdxPlus1;      ///< HighestLayerIdxPlus1 for each additional layer set and each independent layer (value with index 0 will be ignored)
   Int                    m_defaultOutputLayerIdc;             ///< Specifies output layers of layer sets, 0: output all layers, 1: output highest layers, 2: specified by LayerIdsInDefOuputLayerSet
   std::vector<Int>       m_outputLayerSetIdx;                 ///< Indices of layer sets used as additional output layer sets  
-  std::vector< std::vector<Int> > m_layerIdsInAddOutputLayerSet; ///< LayerIds in vps of additional output layers
-  std::vector< std::vector<Int> > m_layerIdsInDefOutputLayerSet; ///< Indices in vps of output layers in layer sets
-  std::vector< std::vector< Int > > m_profileTierLevelIdx;      ///< Indices of of profile, per layer in layer set
+  IntAry2d m_layerIdsInAddOutputLayerSet; ///< LayerIds in vps of additional output layers
+  IntAry2d m_layerIdsInDefOutputLayerSet; ///< Indices in vps of output layers in layer sets
+  IntAry2d               m_profileTierLevelIdx;      ///< Indices of of profile, per layer in layer set
   std::vector<Bool>      m_altOutputLayerFlag;                ///< Alt output layer flag
 
   // Dependencies
-  std::vector< std::vector<Int> > m_directRefLayers;          ///< LayerIds of direct reference layers
-  std::vector< std::vector<Int> > m_dependencyTypes;          ///< Dependency types of direct reference layers
+  IntAry2d m_directRefLayers;          ///< LayerIds of direct reference layers
+  IntAry2d m_dependencyTypes;          ///< Dependency types of direct reference layers
 
   // VPS VUI
@@ -119,8 +119,8 @@
   std::vector< std::vector<Int  > > m_avgPicRate;
   Bool                              m_tilesNotInUseFlag; 
-  std::vector< Bool >               m_tilesInUseFlag;
-  std::vector< Bool >               m_loopFilterNotAcrossTilesFlag; 
+  BoolAry1d               m_tilesInUseFlag;
+  BoolAry1d               m_loopFilterNotAcrossTilesFlag; 
   Bool                              m_wppNotInUseFlag;
-  std::vector< Bool >               m_wppInUseFlag;
+  BoolAry1d               m_wppInUseFlag;
 
   std::vector< std::vector<Bool > > m_tileBoundariesAlignedFlag;  
@@ -133,7 +133,7 @@
 
 
-#if H_3D_IC
-  Bool   m_abUseIC;
-  Bool   m_bUseLowLatencyICEnc;
+#if NH_3D
+  Bool      m_abUseIC;
+  Bool      m_bUseLowLatencyICEnc;
 #endif
 
@@ -142,13 +142,15 @@
   // source specification
   Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
-  UInt      m_FrameSkip;                                      ///< number of skipped frames from the beginning
+  UInt      m_FrameSkip;                                   ///< number of skipped frames from the beginning
   Int       m_iSourceWidth;                                   ///< source width in pixel
   Int       m_iSourceHeight;                                  ///< source height in pixel (when interlaced = field height)
-  
+
   Int       m_iSourceHeightOrg;                               ///< original source height in pixel (when interlaced = frame height)
-  
-  bool      m_isField;                                        ///< enable field coding
-  bool      m_isTopFieldFirst;
-  
+
+  Bool      m_isField;                                        ///< enable field coding
+  Bool      m_isTopFieldFirst;
+  Bool      m_bEfficientFieldIRAPEnabled;                     ///< enable an efficient field IRAP structure.
+  Bool      m_bHarmonizeGopFirstFieldCoupleEnabled;
+
   Int       m_conformanceWindowMode;
   Int       m_confWinLeft;
@@ -158,8 +160,19 @@
   Int       m_framesToBeEncoded;                              ///< number of encoded frames
   Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
-  
+  InputColourSpaceConversion m_inputColourSpaceConvert;       ///< colour space conversion to apply to input video
+  Bool      m_snrInternalColourSpace;                       ///< if true, then no colour space conversion is applied for snr calculation, otherwise inverse of input is applied.
+  Bool      m_outputInternalColourSpace;                    ///< if true, then no colour space conversion is applied for reconstructed video, otherwise inverse of input is applied.
+  ChromaFormat m_InputChromaFormatIDC;
+
+  Bool      m_printMSEBasedSequencePSNR;
+  Bool      m_printFrameMSE;
+  Bool      m_printSequenceMSE;
+  Bool      m_cabacZeroWordPaddingEnabled;
+  Bool      m_bClipInputVideoToRec709Range;
+  Bool      m_bClipOutputVideoToRec709Range;
+
   // profile/level
-#if H_MV
-  std::vector< Profile::Name > m_profile;
+#if NH_MV
+  std::vector< Profile::Name > m_profiles;
   std::vector< Level::Tier   > m_levelTier;
   std::vector< Level::Name   > m_level;
@@ -170,11 +183,16 @@
   Level::Name   m_level;
 #endif
-
+  UInt          m_bitDepthConstraint;
+  ChromaFormat  m_chromaFormatConstraint;
+  Bool          m_intraConstraintFlag;
+  Bool          m_onePictureOnlyConstraintFlag;
+  Bool          m_lowerBitRateConstraintFlag;
   Bool m_progressiveSourceFlag;
   Bool m_interlacedSourceFlag;
   Bool m_nonPackedConstraintFlag;
   Bool m_frameOnlyConstraintFlag;
+
   // coding structure
-#if H_MV
+#if NH_MV
   std::vector<Int> m_iIntraPeriod;                            ///< period of I-slice (random access period)
 #else
@@ -183,5 +201,5 @@
   Int       m_iDecodingRefreshType;                           ///< random access type
   Int       m_iGOPSize;                                       ///< GOP size of hierarchical structure
-#if H_MV
+#if NH_MV
   Int       m_extraRPSsMvc[MAX_NUM_LAYERS];                       ///< extra RPSs added to handle CRA for each layer
   std::vector< GOPEntry* >  m_GOPListMvc;                            ///< the coding structure entries from the config file for each layer 
@@ -194,9 +212,23 @@
   Int       m_maxDecPicBuffering[MAX_TLAYER];                 ///< total number of pictures in the decoded picture buffer
   #endif
+  Bool      m_crossComponentPredictionEnabledFlag;                          ///< flag enabling the use of cross-component prediction
+  Bool      m_reconBasedCrossCPredictionEstimate;             ///< causes the alpha calculation in encoder search to be based on the decoded residual rather than the pre-transform encoder-side residual
+#if NH_MV
+  UInt      m_log2SaoOffsetScale[MAX_NUM_LAYERS][MAX_NUM_CHANNEL_TYPE];        ///< number of bits for the upward bit shift operation on the decoded SAO offsets
+#else
+  UInt      m_log2SaoOffsetScale[MAX_NUM_CHANNEL_TYPE];       ///< number of bits for the upward bit shift operation on the decoded SAO offsets
+#endif
   Bool      m_useTransformSkip;                               ///< flag for enabling intra transform skipping
   Bool      m_useTransformSkipFast;                           ///< flag for enabling fast intra transform skipping
+  UInt      m_log2MaxTransformSkipBlockSize;                  ///< transform-skip maximum size (minimum of 2)
+  Bool      m_transformSkipRotationEnabledFlag;               ///< control flag for transform-skip/transquant-bypass residual rotation
+  Bool      m_transformSkipContextEnabledFlag;                ///< control flag for transform-skip/transquant-bypass single significance map context
+  Bool      m_rdpcmEnabledFlag[NUMBER_OF_RDPCM_SIGNALLING_MODES];///< control flags for residual DPCM
   Bool      m_enableAMP;
+  Bool      m_persistentRiceAdaptationEnabledFlag;            ///< control flag for Golomb-Rice parameter adaptation over each slice
+  Bool      m_cabacBypassAlignmentEnabledFlag;
+
   // coding quality
-#if H_MV
+#if NH_MV
   std::vector<Double>  m_fQP;                                 ///< QP value of key-picture (floating point) for each layer
   std::vector<Int>     m_iQP;                                 ///< QP value of key-picture (integer) for each layer
@@ -206,5 +238,5 @@
 #endif
   Char*     m_pchdQPFile;                                     ///< QP offset for each slice (initialized from external file)
-#if H_MV
+#if NH_MV
   std::vector<Int*> m_aidQP;                                    ///< array of slice QP values for each layer
 #else
@@ -214,6 +246,7 @@
   UInt      m_uiDeltaQpRD;                                    ///< dQP range for multi-pass slice QP optimization
   Int       m_iMaxCuDQPDepth;                                 ///< Max. depth for a minimum CuDQPSize (0:default)
-
-  Int       m_cbQpOffset;                                     ///< Chroma Cb QP Offset (0:default) 
+  Int       m_diffCuChromaQpOffsetDepth;                      ///< If negative, then do not apply chroma qp offsets.
+
+  Int       m_cbQpOffset;                                     ///< Chroma Cb QP Offset (0:default)
   Int       m_crQpOffset;                                     ///< Chroma Cr QP Offset (0:default)
 
@@ -221,9 +254,10 @@
   Bool      m_bUseAdaptQpSelect;
 #endif
+  TComSEIMasteringDisplay m_masteringDisplay;
 
   Bool      m_bUseAdaptiveQP;                                 ///< Flag for enabling QP adaptation based on a psycho-visual model
   Int       m_iQPAdaptationRange;                             ///< dQP range by QP adaptation
-  
-#if H_MV
+
+#if NH_MV
   Int       m_maxTempLayerMvc[MAX_NUM_LAYER_IDS];             ///< Max temporal layer for each layer
 #else
@@ -232,22 +266,28 @@
 
   // coding unit (CU) definition
+  // TODO: Remove MaxCUWidth/MaxCUHeight and replace with MaxCUSize.
   UInt      m_uiMaxCUWidth;                                   ///< max. CU width in pixel
   UInt      m_uiMaxCUHeight;                                  ///< max. CU height in pixel
-  UInt      m_uiMaxCUDepth;                                   ///< max. CU depth
-  
+  UInt      m_uiMaxCUDepth;                                   ///< max. CU depth (as specified by command line)
+  UInt      m_uiMaxTotalCUDepth;                              ///< max. total CU depth - includes depth of transform-block structure
+  UInt      m_uiLog2DiffMaxMinCodingBlockSize;                ///< difference between largest and smallest CU depth
+
   // transfom unit (TU) definition
   UInt      m_uiQuadtreeTULog2MaxSize;
   UInt      m_uiQuadtreeTULog2MinSize;
-  
+
   UInt      m_uiQuadtreeTUMaxDepthInter;
   UInt      m_uiQuadtreeTUMaxDepthIntra;
-  
+
   // coding tools (bit-depth)
-  Int       m_inputBitDepthY;                               ///< bit-depth of input file (luma component)
-  Int       m_inputBitDepthC;                               ///< bit-depth of input file (chroma component)
-  Int       m_outputBitDepthY;                              ///< bit-depth of output file (luma component)
-  Int       m_outputBitDepthC;                              ///< bit-depth of output file (chroma component)
-  Int       m_internalBitDepthY;                            ///< bit-depth codec operates at in luma (input/output files will be converted)
-  Int       m_internalBitDepthC;                            ///< bit-depth codec operates at in chroma (input/output files will be converted)
+  Int       m_inputBitDepth   [MAX_NUM_CHANNEL_TYPE];         ///< bit-depth of input file
+  Int       m_outputBitDepth  [MAX_NUM_CHANNEL_TYPE];         ///< bit-depth of output file
+  Int       m_MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE];      ///< bit-depth of input samples after MSB extension
+  Int       m_internalBitDepth[MAX_NUM_CHANNEL_TYPE];         ///< bit-depth codec operates at (input/output files will be converted)
+  Bool      m_extendedPrecisionProcessingFlag;
+  Bool      m_highPrecisionOffsetsEnabledFlag;
+
+  //coding tools (chroma format)
+  ChromaFormat m_chromaFormatIDC;
 
   // coding tools (PCM bit-depth)
@@ -255,13 +295,16 @@
 
   // coding tool (SAO)
-#if H_MV
+#if NH_MV
   std::vector<Bool> m_bUseSAO; 
 #else
-  Bool      m_bUseSAO; 
-#endif
+  Bool      m_bUseSAO;
+#endif
+  Bool      m_bTestSAODisableAtPictureLevel;
+  Double    m_saoEncodingRate;                                ///< When >0 SAO early picture termination is enabled for luma and chroma
+  Double    m_saoEncodingRateChroma;                          ///< The SAO early picture termination rate to use for chroma (when m_SaoEncodingRate is >0). If <=0, use results for luma.
   Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
-  Bool      m_saoLcuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+  Bool      m_saoCtuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for CTU bottom and right boundary areas
   // coding tools (loop filter)
-#if H_MV
+#if NH_MV
   std::vector<Bool> m_bLoopFilterDisable;                     ///< flag for using deblocking filter for each layer
 #else
@@ -271,7 +314,6 @@
   Int       m_loopFilterBetaOffsetDiv2;                     ///< beta offset for deblocking filter
   Int       m_loopFilterTcOffsetDiv2;                       ///< tc offset for deblocking filter
-  Bool      m_DeblockingFilterControlPresent;                 ///< deblocking filter control present flag in PPS
   Bool      m_DeblockingFilterMetric;                         ///< blockiness metric in encoder
- 
+
   // coding tools (PCM)
   Bool      m_usePCM;                                         ///< flag for using IPCM
@@ -279,4 +321,5 @@
   UInt      m_uiPCMLog2MinSize;                               ///< log2 of minimum PCM block size
   Bool      m_bPCMFilterDisableFlag;                          ///< PCM filter disable flag
+  Bool      m_enableIntraReferenceSmoothing;                  ///< flag for enabling(default)/disabling intra reference smoothing/filtering
 
   // coding tools (encoder-only parameters)
@@ -285,9 +328,15 @@
   Bool      m_useRDOQ;                                       ///< flag for using RD optimized quantization
   Bool      m_useRDOQTS;                                     ///< flag for using RD optimized quantization for transform skip
-  Int      m_rdPenalty;                                      ///< RD-penalty for 32x32 TU for intra in non-intra slices (0: no RD-penalty, 1: RD-penalty, 2: maximum RD-penalty) 
+#if T0196_SELECTIVE_RDOQ
+  Bool      m_useSelectiveRDOQ;                               ///< flag for using selective RDOQ
+#endif
+  Int       m_rdPenalty;                                      ///< RD-penalty for 32x32 TU for intra in non-intra slices (0: no RD-penalty, 1: RD-penalty, 2: maximum RD-penalty)
+  Bool      m_bDisableIntraPUsInInterSlices;                  ///< Flag for disabling intra predicted PUs in inter slices.
   Int       m_iFastSearch;                                    ///< ME mode, 0 = full, 1 = diamond, 2 = PMVFAST
   Int       m_iSearchRange;                                   ///< ME search range
   Int       m_bipredSearchRange;                              ///< ME search range for bipred refinement
-#if H_MV
+  Bool      m_bClipForBiPredMeEnabled;                        ///< Enables clipping for Bi-Pred ME.
+  Bool      m_bFastMEAssumingSmootherMVEnabled;               ///< Enables fast ME assuming a smoother MV.
+#if NH_MV
   Bool      m_bUseDisparitySearchRangeRestriction;            ///< restrict vertical search range for inter-view prediction
   Int       m_iVerticalDisparitySearchRange;                  ///< ME vertical search range for inter-view prediction
@@ -295,11 +344,11 @@
   Bool      m_bUseFastEnc;                                    ///< flag for using fast encoder setting
   Bool      m_bUseEarlyCU;                                    ///< flag for using Early CU setting
-  Bool      m_useFastDecisionForMerge;                        ///< flag for using Fast Decision Merge RD-Cost 
+  Bool      m_useFastDecisionForMerge;                        ///< flag for using Fast Decision Merge RD-Cost
   Bool      m_bUseCbfFastMode;                              ///< flag for using Cbf Fast PU Mode Decision
   Bool      m_useEarlySkipDetection;                         ///< flag for using Early SKIP Detection
-  Int       m_sliceMode;                                     ///< 0: no slice limits, 1 : max number of CTBs per slice, 2: max number of bytes per slice, 
+  Int       m_sliceMode;                                     ///< 0: no slice limits, 1 : max number of CTBs per slice, 2: max number of bytes per slice,
                                                              ///< 3: max number of tiles per slice
   Int       m_sliceArgument;                                 ///< argument according to selected slice mode
-  Int       m_sliceSegmentMode;                              ///< 0: no slice segment limits, 1 : max number of CTBs per slice segment, 2: max number of bytes per slice segment, 
+  Int       m_sliceSegmentMode;                              ///< 0: no slice segment limits, 1 : max number of CTBs per slice segment, 2: max number of bytes per slice segment,
                                                              ///< 3: max number of tiles per slice segment
   Int       m_sliceSegmentArgument;                          ///< argument according to selected slice segment mode
@@ -313,8 +362,11 @@
   std::vector<Int> m_tileRowHeight;
   Int       m_iWaveFrontSynchro; //< 0: no WPP. >= 1: WPP is enabled, the "Top right" from which inheritance occurs is this LCU offset in the line above the current.
-  Int       m_iWaveFrontSubstreams; //< If iWaveFrontSynchro, this is the number of substreams per frame (dependent tiles) or per tile (independent tiles).
+  Int       m_iWaveFrontFlush; //< enable(1)/disable(0) the CABAC flush at the end of each line of LCUs.
 
   Bool      m_bUseConstrainedIntraPred;                       ///< flag for using constrained intra prediction
-  
+  Bool      m_bFastUDIUseMPMEnabled;
+  Bool      m_bFastMEForGenBLowDelayEnabled;
+  Bool      m_bUseBLambdaForNonKeyLowDelayPictures;
+
   Int       m_decodedPictureHashSEIEnabled;                    ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
   Int       m_recoveryPointSEIEnabled;
@@ -322,4 +374,7 @@
   Int       m_pictureTimingSEIEnabled;
   Bool      m_toneMappingInfoSEIEnabled;
+  Bool      m_chromaSamplingFilterSEIenabled;
+  Int       m_chromaSamplingHorFilterIdc;
+  Int       m_chromaSamplingVerFilterIdc;
   Int       m_toneMapId;
   Bool      m_toneMapCancelFlag;
@@ -327,5 +382,5 @@
   Int       m_toneMapCodedDataBitDepth;
   Int       m_toneMapTargetBitDepth;
-  Int       m_toneMapModelId; 
+  Int       m_toneMapModelId;
   Int       m_toneMapMinValue;
   Int       m_toneMapMaxValue;
@@ -337,5 +392,5 @@
   Int       m_exposureIndexIdc;
   Int       m_exposureIndexValue;
-  Int       m_exposureCompensationValueSignFlag;
+  Bool      m_exposureCompensationValueSignFlag;
   Int       m_exposureCompensationValueNumerator;
   Int       m_exposureCompensationValueDenomIdc;
@@ -353,27 +408,47 @@
   Int       m_framePackingSEIQuincunx;
   Int       m_framePackingSEIInterpretation;
+  Int       m_segmentedRectFramePackingSEIEnabled;
+  Bool      m_segmentedRectFramePackingSEICancel;
+  Int       m_segmentedRectFramePackingSEIType;
+  Bool      m_segmentedRectFramePackingSEIPersistence;
   Int       m_displayOrientationSEIAngle;
   Int       m_temporalLevel0IndexSEIEnabled;
   Int       m_gradualDecodingRefreshInfoEnabled;
+  Int       m_noDisplaySEITLayer;
   Int       m_decodingUnitInfoSEIEnabled;
   Int       m_SOPDescriptionSEIEnabled;
   Int       m_scalableNestingSEIEnabled;
+  Bool      m_tmctsSEIEnabled;
+  Bool      m_timeCodeSEIEnabled;
+  Int       m_timeCodeSEINumTs;
+  TComSEITimeSet m_timeSetArray[MAX_TIMECODE_SEI_SETS];
+  Bool      m_kneeSEIEnabled;
+  Int       m_kneeSEIId;
+  Bool      m_kneeSEICancelFlag;
+  Bool      m_kneeSEIPersistenceFlag;
+  Int       m_kneeSEIInputDrange;
+  Int       m_kneeSEIInputDispLuminance;
+  Int       m_kneeSEIOutputDrange;
+  Int       m_kneeSEIOutputDispLuminance;
+  Int       m_kneeSEINumKneePointsMinus1;
+  Int*      m_kneeSEIInputKneePoint;
+  Int*      m_kneeSEIOutputKneePoint;
   // weighted prediction
   Bool      m_useWeightedPred;                    ///< Use of weighted prediction in P slices
   Bool      m_useWeightedBiPred;                  ///< Use of bi-directional weighted prediction in B slices
-  
+
   UInt      m_log2ParallelMergeLevel;                         ///< Parallel merge estimation region
   UInt      m_maxNumMergeCand;                                ///< Max number of merge candidates
 
   Int       m_TMVPModeId;
-  Int       m_signHideFlag;
+  Bool      m_signHideFlag;
   Bool      m_RCEnableRateControl;                ///< enable rate control or not
   Int       m_RCTargetBitrate;                    ///< target bitrate when rate control is enabled
   Int       m_RCKeepHierarchicalBit;              ///< 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
-  Bool      m_RCLCULevelRC;                       ///< true: LCU level rate control; false: picture level rate control
-  Bool      m_RCUseLCUSeparateModel;              ///< use separate R-lambda model at LCU level
+  Bool      m_RCLCULevelRC;                       ///< true: LCU level rate control; false: picture level rate control NOTE: code-tidy - rename to m_RCCtuLevelRC
+  Bool      m_RCUseLCUSeparateModel;              ///< use separate R-lambda model at LCU level                        NOTE: code-tidy - rename to m_RCUseCtuSeparateModel
   Int       m_RCInitialQP;                        ///< inital QP for rate control
   Bool      m_RCForceIntraQP;                     ///< force all intra picture to use initial QP or not
-
+  
 #if KWU_RC_VIEWRC_E0227
   vector<Int>     m_viewTargetBits;
@@ -383,9 +458,11 @@
   UInt       m_depthMADPred;
 #endif
-  Int       m_useScalingListId;                               ///< using quantization matrix
+
+ScalingListMode m_useScalingListId;                         ///< using quantization matrix
   Char*     m_scalingListFile;                                ///< quantization matrix file name
 
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
   Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
+  CostMode  m_costMode;                                       ///< Cost mode to use
 
   Bool      m_recalculateQPAccordingToLambda;                 ///< recalculate QP value according to the lambda value
@@ -427,5 +504,8 @@
   Int       m_log2MaxMvLengthHorizontal;                      ///< Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units
   Int       m_log2MaxMvLengthVertical;                        ///< Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units
-#if H_MV
+  std::string m_summaryOutFilename;                           ///< filename to use for producing summary output file.
+  std::string m_summaryPicFilenameBase;                       ///< Base filename to use for producing summary picture output files. The actual filenames used will have I.txt, P.txt and B.txt appended.
+  UInt        m_summaryVerboseness;                           ///< Specifies the level of the verboseness of the text output.
+#if NH_MV
   Bool              m_subBistreamPropSEIEnabled;
   Int               m_sbPropNumAdditionalSubStreams;
@@ -437,5 +517,7 @@
   Bool              m_outputVpsInfo;
 #endif
-#if H_3D
+#if NH_3D
+  // Output Format
+  Bool      m_depth420OutputFlag;                             ///< Output depth layers in 4:2:0 format
   // Camera parameters
   Char*     m_pchCameraParameterFile;                         ///< camera parameter file
@@ -443,21 +525,21 @@
   TAppComCamPara m_cCameraData;
   Int       m_iCodedCamParPrecision;                          ///< precision for coding of camera parameters
-#if H_3D_VSO
+#if NH_3D_VSO
   Char*     m_pchVSOConfig;
-  Bool      m_bUseVSO;                                    ///< flag for using View Synthesis Optimization
-  Bool      m_bVSOLSTable;                                ///< Depth QP dependent Lagrange parameter optimization (m23714)
-  Bool      m_bVSOEarlySkip;                              ///< Early skip of VSO computation (JCT3V-A0093 modification 4)
-
-  //// Used for development by GT, might be removed later
-  Double    m_dLambdaScaleVSO;                            ///< Scaling factor for Lambda in VSO mode
-  Bool      m_bForceLambdaScaleVSO;                       ///< Use Lambda Scale for depth even if VSO is turned off
-  Bool      m_bAllowNegDist;                              ///< Allow negative distortion in VSO
-  UInt      m_uiVSOMode;                                  ///< Number of VSO Mode, 1 = , 2 = simple, org vs. ren, 3 = simple, ren vs. ren, 4 = full  
-
-  // SAIT_VSO_EST_A0033
-  Bool      m_bUseEstimatedVSD;                           ///< Flag for using model based VSD estimation instead of VSO for some encoder decisions (JCT3V-A0033 modification 3)  
-
-  // LGE_WVSO_A0119
-  Bool      m_bUseWVSO;                                    ///< flag for using View Synthesis Optimization  
+  Bool      m_bUseVSO;                                        ///< flag for using View Synthesis Optimization
+  Bool      m_bVSOLSTable;                                    ///< Depth QP dependent Lagrange parameter optimization (m23714)
+  Bool      m_bVSOEarlySkip;                                  ///< Early skip of VSO computation (JCT3V-A0093 modification 4)
+                                                              
+  //// Used for development by GT, might be removed later     
+  Double    m_dLambdaScaleVSO;                                ///< Scaling factor for Lambda in VSO mode
+  Bool      m_bForceLambdaScaleVSO;                           ///< Use Lambda Scale for depth even if VSO is turned off
+  Bool      m_bAllowNegDist;                                  ///< Allow negative distortion in VSO
+  UInt      m_uiVSOMode;                                      ///< Number of VSO Mode, 1 = , 2 = simple, org vs. ren, 3 = simple, ren vs. ren, 4 = full  
+                                                              
+  // SAIT_VSO_EST_A0033                                       
+  Bool      m_bUseEstimatedVSD;                               ///< Flag for using model based VSD estimation instead of VSO for some encoder decisions (JCT3V-A0033 modification 3)  
+                                                              
+  // LGE_WVSO_A0119                                           
+  Bool      m_bUseWVSO;                                       ///< flag for using View Synthesis Optimization  
   Int       m_iVSOWeight;
   Int       m_iVSDWeight;
@@ -467,33 +549,28 @@
   TRenModSetupStrParser       m_cRenModStrParser;
 #endif
-#if H_3D_DIM
-  Bool      m_useDLT;                                        ///< flag for using DLT
-#endif
-#if H_3D_QTLPC
-  Bool      m_bUseQTL;                                        ///< flag for using depth QuadTree Limitation
-#endif
-
-  std::vector< Bool >    m_ivMvPredFlag;
-  std::vector< Bool >    m_ivMvScalingFlag;
-  Int                    m_log2SubPbSizeMinus3;
-  Bool                   m_ivResPredFlag;
-  Bool                   m_depthRefinementFlag;
-  Bool                   m_viewSynthesisPredFlag;
-  Bool                   m_depthBasedBlkPartFlag;
-  Bool                   m_mpiFlag;
-  Int                    m_log2MpiSubPbSizeMinus3;
-  Bool                   m_intraContourFlag;
-  Bool                   m_intraWedgeFlag;
-  Bool                   m_intraSdcFlag;
-  Bool                   m_qtPredFlag;
-  Bool                   m_interSdcFlag;
-  Bool                   m_depthIntraSkipFlag; 
+
+  Bool       m_useDLT;                                        ///< flag for using DLT
+  Bool       m_bUseQTL;                                        ///< flag for using depth QuadTree Limitation
+  BoolAry1d  m_ivMvPredFlag;
+  BoolAry1d  m_ivMvScalingFlag;
+  Int        m_log2SubPbSizeMinus3;
+  Bool       m_ivResPredFlag;
+  Bool       m_depthRefinementFlag;
+  Bool       m_viewSynthesisPredFlag;
+  Bool       m_depthBasedBlkPartFlag;
+  Bool       m_mpiFlag;
+  Int        m_log2MpiSubPbSizeMinus3;
+  Bool       m_intraContourFlag;
+  Bool       m_intraWedgeFlag;
+  Bool       m_intraSdcFlag;
+  Bool       m_qtPredFlag;
+  Bool       m_interSdcFlag;
+  Bool       m_depthIntraSkipFlag; 
 #endif
   // internal member functions
-  Void  xSetGlobal      ();                                   ///< set global variables
   Void  xCheckParameter ();                                   ///< check validity of configuration values
   Void  xPrintParameter ();                                   ///< print configuration values
   Void  xPrintUsage     ();                                   ///< print usage
-#if H_MV
+#if NH_MV
 
   template<typename T>
@@ -533,4 +610,20 @@
     }
   }
+
+  template <typename T>
+  Void xResizeVector(  std::vector<T> & rpcVector, UInt n )
+  {
+    for( Int layer = 0; rpcVector.size() < n; layer++ )
+    {
+      assert( rpcVector.size() > 0 );
+      rpcVector.push_back( rpcVector[layer] );      
+    }
+
+    for( ; rpcVector.size() > n; )
+    {      
+      rpcVector.pop_back( );      
+    }
+  }
+
 
   template <typename T>
@@ -561,5 +654,5 @@
   Void xPrintVectorElem( Bool   elem ) { printf(" %d"   , ( elem ? 1 : 0 ));};
 #endif
-#if H_MV
+#if NH_MV
   Int   getGOPSize() { return m_iGOPSize; }
 #endif
@@ -567,10 +660,10 @@
   TAppEncCfg();
   virtual ~TAppEncCfg();
-  
+
 public:
   Void  create    ();                                         ///< create option handling class
   Void  destroy   ();                                         ///< destroy option handling class
   Bool  parseCfg  ( Int argc, Char* argv[] );                 ///< parse configuration file to fill member variables
-  
+
 };// END CLASS DEFINITION TAppEncCfg
 
Index: branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -42,4 +42,5 @@
 #include <fcntl.h>
 #include <assert.h>
+#include <iomanip>
 
 #include "TAppEncTop.h"
@@ -58,5 +59,5 @@
 {
 
-#if H_MV
+#if NH_MV
   m_vps = new TComVPS; 
 #else
@@ -69,5 +70,5 @@
 TAppEncTop::~TAppEncTop()
 {
-#if H_MV
+#if NH_MV
   if (m_vps)
   {
@@ -80,5 +81,5 @@
 Void TAppEncTop::xInitLibCfg()
 {
-#if H_MV
+#if NH_MV
   TComVPS& vps = (*m_vps);   
 #else
@@ -86,10 +87,13 @@
 #endif
   
+#if NH_3D
+  vps.createCamPars(m_iNumberOfViews);  
+#endif
+
 #if H_3D
-  vps.createCamPars(m_iNumberOfViews);
   TComDLT& dlt = m_dlt;
 #endif
 
-#if H_MV
+#if NH_MV
   Int maxTempLayer = -1; 
   for (Int j = 0; j < m_numberOfLayers; j++)
@@ -118,17 +122,19 @@
   }
 #else
-  vps.setMaxTLayers                       ( m_maxTempLayer );
+  vps.setMaxTLayers                                               ( m_maxTempLayer );
   if (m_maxTempLayer == 1)
   {
     vps.setTemporalNestingFlag(true);
   }
-  vps.setMaxLayers                        ( 1 );
+  vps.setMaxLayers                                                ( 1 );
   for(Int i = 0; i < MAX_TLAYER; i++)
   {
-    vps.setNumReorderPics                 ( m_numReorderPics[i], i );
-    vps.setMaxDecPicBuffering             ( m_maxDecPicBuffering[i], i );
-  }
-#endif
-#if H_MV
+    vps.setNumReorderPics                                         ( m_numReorderPics[i], i );
+    vps.setMaxDecPicBuffering                                     ( m_maxDecPicBuffering[i], i );
+  }
+#endif
+#if NH_MV
+  xSetTimingInfo           ( vps );
+  xSetHrdParameters        ( vps ); 
   xSetLayerIds             ( vps );   
   xSetDimensionIdAndLength ( vps );
@@ -139,7 +145,9 @@
   xSetDpbSize              ( vps ); 
   xSetVPSVUI               ( vps ); 
-#if H_3D
+#if NH_3D
   xSetCamPara              ( vps ); 
   m_ivPicLists.setVPS      ( &vps );
+#endif
+#if H_3D
   xDeriveDltArray          ( vps, dlt );
 #endif
@@ -174,7 +182,6 @@
   }
 
-#if H_3D
+#if NH_3D
   // Set 3d tool parameters
-
   for (Int d = 0; d < 2; d++)
   {  
@@ -201,4 +208,7 @@
   }
 #endif
+
+
+  /// Create encoders and set profiles profiles
   for(Int layerIdInVps = 0; layerIdInVps < m_numberOfLayers; layerIdInVps++)
   {
@@ -207,5 +217,47 @@
     m_acTVideoIOYuvInputFileList.push_back(new TVideoIOYuv);
     m_acTVideoIOYuvReconFileList.push_back(new TVideoIOYuv);
-    m_picYuvRec                 .push_back(new TComList<TComPicYuv*>) ;
+#if NH_3D    
+    Int profileIdc = -1; 
+    for (Int olsIdx = 0; olsIdx < vps.getNumOutputLayerSets(); olsIdx++ )
+    {   
+      Int lsIdx = vps.olsIdxToLsIdx( olsIdx );
+      for(Int i = 0; i < vps.getNumLayersInIdList( lsIdx ); i++ )
+      {
+        if( vps.getLayerIdInNuh( layerIdInVps) == vps.getLayerSetLayerIdList(lsIdx, i) )
+        {
+          Int ptlIdx = vps.getProfileTierLevelIdx( olsIdx, i );
+          if ( ptlIdx != -1 )
+          {
+            Int curProfileIdc = vps.getPTL(ptlIdx)->getGeneralPTL()->getProfileIdc(); 
+            if (profileIdc == -1)   
+            {
+              profileIdc = curProfileIdc; 
+            }
+            else
+            {   
+              if ( profileIdc != curProfileIdc )
+              {              
+                fprintf(stderr, "Error: ProfileIdc for layer with index %d in VPS not equal in all OLSs. \n", layerIdInVps );
+                exit(EXIT_FAILURE);
+              }
+            }
+          }
+        }
+      }
+    }
+
+    if (profileIdc == -1 )
+    {
+      fprintf(stderr, "Error: No profile given for layer with index %d in VPS not equal in all OLS. \n", layerIdInVps );
+      exit(EXIT_FAILURE);
+    }
+    m_acTEncTopList[ layerIdInVps ]->setProfileIdc( profileIdc ); 
+#endif
+  }
+
+
+  for(Int layerIdInVps = 0; layerIdInVps < m_numberOfLayers; layerIdInVps++)
+  {
+    m_cListPicYuvRec            .push_back(new TComList<TComPicYuv*>) ;
     m_ivPicLists.push_back( m_acTEncTopList[ layerIdInVps ]->getListPic()  ); 
     TEncTop& m_cTEncTop = *m_acTEncTopList[ layerIdInVps ];  // It is not a member, but this name helps avoiding code duplication !!!
@@ -216,10 +268,10 @@
     m_cTEncTop.setViewId                       ( vps.getViewId      (  layerId ) );
     m_cTEncTop.setViewIndex                    ( vps.getViewIndex   (  layerId ) );
-#if H_3D
+#if NH_3D
     Bool isDepth = ( vps.getDepthId     ( layerId ) != 0 ) ;
     m_cTEncTop.setIsDepth                      ( isDepth );
     //====== Camera Parameters =========
     m_cTEncTop.setCameraParameters             ( &m_cCameraData );     
-#if H_3D_VSO
+#if NH_3D_VSO
     //====== VSO =========
     m_cTEncTop.setRenderModelParameters        ( &m_cRenModStrParser ); 
@@ -249,11 +301,9 @@
     m_cTEncTop.setUseDLT                       ( isDepth ? m_useDLT   : false );
     m_cTEncTop.setUseQTL                       ( isDepth ? m_bUseQTL  : false );
-
-
-  m_cTEncTop.setSps3dExtension                 ( m_sps3dExtension );
+    m_cTEncTop.setSps3dExtension               ( m_sps3dExtension );
 #endif // H_3D
 
     m_cTEncTop.setIvPicLists                   ( &m_ivPicLists ); 
-#endif  // H_MV
+#endif  // NH_MV
   m_cTEncTop.setVPS(&vps);
 
@@ -262,273 +312,346 @@
 #endif
 
-#if H_MV
-  m_cTEncTop.setProfile(m_profile[0]);
-  m_cTEncTop.setLevel  (m_levelTier[0], m_level[0]);
-#else
-  m_cTEncTop.setProfile(m_profile);
-  m_cTEncTop.setLevel(m_levelTier, m_level);
-#endif
-  m_cTEncTop.setProgressiveSourceFlag(m_progressiveSourceFlag);
-  m_cTEncTop.setInterlacedSourceFlag(m_interlacedSourceFlag);
-  m_cTEncTop.setNonPackedConstraintFlag(m_nonPackedConstraintFlag);
-  m_cTEncTop.setFrameOnlyConstraintFlag(m_frameOnlyConstraintFlag);
-  
-  m_cTEncTop.setFrameRate                    ( m_iFrameRate );
-  m_cTEncTop.setFrameSkip                    ( m_FrameSkip );
-  m_cTEncTop.setSourceWidth                  ( m_iSourceWidth );
-  m_cTEncTop.setSourceHeight                 ( m_iSourceHeight );
-  m_cTEncTop.setConformanceWindow            ( m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
-  m_cTEncTop.setFramesToBeEncoded            ( m_framesToBeEncoded );
-  
+#if NH_MV
+  m_cTEncTop.setProfile                                           ( m_profiles[0]);
+  m_cTEncTop.setLevel                                             ( m_levelTier[0], m_level[0] );
+#else
+  m_cTEncTop.setProfile                                           ( m_profile);
+  m_cTEncTop.setLevel                                             ( m_levelTier, m_level);
+#endif
+  m_cTEncTop.setProgressiveSourceFlag                             ( m_progressiveSourceFlag);
+  m_cTEncTop.setInterlacedSourceFlag                              ( m_interlacedSourceFlag);
+  m_cTEncTop.setNonPackedConstraintFlag                           ( m_nonPackedConstraintFlag);
+  m_cTEncTop.setFrameOnlyConstraintFlag                           ( m_frameOnlyConstraintFlag);
+  m_cTEncTop.setBitDepthConstraintValue                           ( m_bitDepthConstraint );
+  m_cTEncTop.setChromaFormatConstraintValue                       ( m_chromaFormatConstraint );
+  m_cTEncTop.setIntraConstraintFlag                               ( m_intraConstraintFlag );
+  m_cTEncTop.setOnePictureOnlyConstraintFlag                      ( m_onePictureOnlyConstraintFlag );
+  m_cTEncTop.setLowerBitRateConstraintFlag                        ( m_lowerBitRateConstraintFlag );
+
+  m_cTEncTop.setPrintMSEBasedSequencePSNR                         ( m_printMSEBasedSequencePSNR);
+  m_cTEncTop.setPrintFrameMSE                                     ( m_printFrameMSE);
+  m_cTEncTop.setPrintSequenceMSE                                  ( m_printSequenceMSE);
+  m_cTEncTop.setCabacZeroWordPaddingEnabled                       ( m_cabacZeroWordPaddingEnabled );
+
+  m_cTEncTop.setFrameRate                                         ( m_iFrameRate );
+  m_cTEncTop.setFrameSkip                                         ( m_FrameSkip );
+  m_cTEncTop.setSourceWidth                                       ( m_iSourceWidth );
+  m_cTEncTop.setSourceHeight                                      ( m_iSourceHeight );
+  m_cTEncTop.setConformanceWindow                                 ( m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+  m_cTEncTop.setFramesToBeEncoded                                 ( m_framesToBeEncoded );
+
   //====== Coding Structure ========
-#if H_MV
-  m_cTEncTop.setIntraPeriod                  ( m_iIntraPeriod[ layerIdInVps ] );
-#else
-  m_cTEncTop.setIntraPeriod                  ( m_iIntraPeriod );
-#endif
-  m_cTEncTop.setDecodingRefreshType          ( m_iDecodingRefreshType );
-  m_cTEncTop.setGOPSize                      ( m_iGOPSize );
-#if H_MV
-m_cTEncTop.setGopList                      ( m_GOPListMvc[layerIdInVps] );
-  m_cTEncTop.setExtraRPSs                    ( m_extraRPSsMvc[layerIdInVps] );
+#if NH_MV
+  m_cTEncTop.setIntraPeriod                                       ( m_iIntraPeriod[ layerIdInVps ] );
+#else
+  m_cTEncTop.setIntraPeriod                                       ( m_iIntraPeriod );
+#endif
+  m_cTEncTop.setDecodingRefreshType                               ( m_iDecodingRefreshType );
+  m_cTEncTop.setGOPSize                                           ( m_iGOPSize );
+#if NH_MV
+  m_cTEncTop.setGopList                                           ( m_GOPListMvc[layerIdInVps] );
+  m_cTEncTop.setExtraRPSs                                         ( m_extraRPSsMvc[layerIdInVps] );
   for(Int i = 0; i < MAX_TLAYER; i++)
   {
-    m_cTEncTop.setNumReorderPics             ( m_numReorderPicsMvc[layerIdInVps][i], i );
-    m_cTEncTop.setMaxDecPicBuffering         ( m_maxDecPicBufferingMvc[layerIdInVps][i], i );
-  }
-#else
-  m_cTEncTop.setGopList                      ( m_GOPList );
-  m_cTEncTop.setExtraRPSs                    ( m_extraRPSs );
+    m_cTEncTop.setNumReorderPics                                  ( m_numReorderPicsMvc[layerIdInVps][i], i );
+    m_cTEncTop.setMaxDecPicBuffering                              ( m_maxDecPicBufferingMvc[layerIdInVps][i], i );
+  }
+#else
+  m_cTEncTop.setGopList                                           ( m_GOPList );
+  m_cTEncTop.setExtraRPSs                                         ( m_extraRPSs );
   for(Int i = 0; i < MAX_TLAYER; i++)
   {
-    m_cTEncTop.setNumReorderPics             ( m_numReorderPics[i], i );
-    m_cTEncTop.setMaxDecPicBuffering         ( m_maxDecPicBuffering[i], i );
+    m_cTEncTop.setNumReorderPics                                  ( m_numReorderPics[i], i );
+    m_cTEncTop.setMaxDecPicBuffering                              ( m_maxDecPicBuffering[i], i );
   }
 #endif
   for( UInt uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
   {
-    m_cTEncTop.setLambdaModifier( uiLoop, m_adLambdaModifier[ uiLoop ] );
-  }
-#if H_MV
-  m_cTEncTop.setQP                           ( m_iQP[layerIdInVps] );
-#else
-  m_cTEncTop.setQP                           ( m_iQP );
-#endif
-
-  m_cTEncTop.setPad                          ( m_aiPad );
-
-#if H_MV
-  m_cTEncTop.setMaxTempLayer                 ( m_maxTempLayerMvc[layerIdInVps] );
-#else
-  m_cTEncTop.setMaxTempLayer                 ( m_maxTempLayer );
+    m_cTEncTop.setLambdaModifier                                  ( uiLoop, m_adLambdaModifier[ uiLoop ] );
+  }
+#if NH_MV
+  m_cTEncTop.setQP                                                ( m_iQP[layerIdInVps] );
+#else
+  m_cTEncTop.setQP                                                ( m_iQP );
+#endif
+
+  m_cTEncTop.setPad                                               ( m_aiPad );
+
+#if NH_MV
+  m_cTEncTop.setMaxTempLayer                                      ( m_maxTempLayerMvc[layerIdInVps] );
+#else
+  m_cTEncTop.setMaxTempLayer                                      ( m_maxTempLayer );
 #endif
   m_cTEncTop.setUseAMP( m_enableAMP );
-  
+
   //===== Slice ========
-  
+
   //====== Loop/Deblock Filter ========
-#if H_MV
-  m_cTEncTop.setLoopFilterDisable            ( m_bLoopFilterDisable[layerIdInVps]);
-#else
-  m_cTEncTop.setLoopFilterDisable            ( m_bLoopFilterDisable       );
-#endif
-  m_cTEncTop.setLoopFilterOffsetInPPS        ( m_loopFilterOffsetInPPS );
-  m_cTEncTop.setLoopFilterBetaOffset         ( m_loopFilterBetaOffsetDiv2  );
-  m_cTEncTop.setLoopFilterTcOffset           ( m_loopFilterTcOffsetDiv2    );
-  m_cTEncTop.setDeblockingFilterControlPresent( m_DeblockingFilterControlPresent);
-  m_cTEncTop.setDeblockingFilterMetric       ( m_DeblockingFilterMetric );
+#if NH_MV
+  m_cTEncTop.setLoopFilterDisable                                 ( m_bLoopFilterDisable[layerIdInVps]);
+#else
+  m_cTEncTop.setLoopFilterDisable                                 ( m_bLoopFilterDisable       );
+#endif
+  m_cTEncTop.setLoopFilterOffsetInPPS                             ( m_loopFilterOffsetInPPS );
+  m_cTEncTop.setLoopFilterBetaOffset                              ( m_loopFilterBetaOffsetDiv2  );
+  m_cTEncTop.setLoopFilterTcOffset                                ( m_loopFilterTcOffsetDiv2    );
+  m_cTEncTop.setDeblockingFilterMetric                            ( m_DeblockingFilterMetric );
 
   //====== Motion search ========
-  m_cTEncTop.setFastSearch                   ( m_iFastSearch  );
-  m_cTEncTop.setSearchRange                  ( m_iSearchRange );
-  m_cTEncTop.setBipredSearchRange            ( m_bipredSearchRange );
-
-#if H_MV
-  m_cTEncTop.setUseDisparitySearchRangeRestriction ( m_bUseDisparitySearchRangeRestriction );
-  m_cTEncTop.setVerticalDisparitySearchRange ( m_iVerticalDisparitySearchRange );
+  m_cTEncTop.setDisableIntraPUsInInterSlices                      ( m_bDisableIntraPUsInInterSlices );
+  m_cTEncTop.setFastSearch                                        ( m_iFastSearch  );
+  m_cTEncTop.setSearchRange                                       ( m_iSearchRange );
+  m_cTEncTop.setBipredSearchRange                                 ( m_bipredSearchRange );
+  m_cTEncTop.setClipForBiPredMeEnabled                            ( m_bClipForBiPredMeEnabled );
+  m_cTEncTop.setFastMEAssumingSmootherMVEnabled                   ( m_bFastMEAssumingSmootherMVEnabled );
+
+#if NH_MV
+  m_cTEncTop.setUseDisparitySearchRangeRestriction                ( m_bUseDisparitySearchRangeRestriction );
+  m_cTEncTop.setVerticalDisparitySearchRange                      ( m_iVerticalDisparitySearchRange );
 #endif
   //====== Quality control ========
-  m_cTEncTop.setMaxDeltaQP                   ( m_iMaxDeltaQP  );
-  m_cTEncTop.setMaxCuDQPDepth                ( m_iMaxCuDQPDepth  );
-
-  m_cTEncTop.setChromaCbQpOffset               ( m_cbQpOffset     );
-  m_cTEncTop.setChromaCrQpOffset            ( m_crQpOffset  );
+  m_cTEncTop.setMaxDeltaQP                                        ( m_iMaxDeltaQP  );
+  m_cTEncTop.setMaxCuDQPDepth                                     ( m_iMaxCuDQPDepth  );
+  m_cTEncTop.setDiffCuChromaQpOffsetDepth                         ( m_diffCuChromaQpOffsetDepth );
+  m_cTEncTop.setChromaCbQpOffset                                  ( m_cbQpOffset     );
+  m_cTEncTop.setChromaCrQpOffset                                  ( m_crQpOffset  );
+
+#if NH_3D
+  m_cTEncTop.setChromaFormatIdc                                   ( isDepth ? CHROMA_400 : m_chromaFormatIDC );
+#else
+  m_cTEncTop.setChromaFormatIdc                                   ( m_chromaFormatIDC  );
+#endif
 
 #if ADAPTIVE_QP_SELECTION
-  m_cTEncTop.setUseAdaptQpSelect             ( m_bUseAdaptQpSelect   );
-#endif
-
-  m_cTEncTop.setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
-  m_cTEncTop.setQPAdaptationRange            ( m_iQPAdaptationRange );
-  
+  m_cTEncTop.setUseAdaptQpSelect                                  ( m_bUseAdaptQpSelect   );
+#endif
+
+  m_cTEncTop.setUseAdaptiveQP                                     ( m_bUseAdaptiveQP  );
+  m_cTEncTop.setQPAdaptationRange                                 ( m_iQPAdaptationRange );
+  m_cTEncTop.setExtendedPrecisionProcessingFlag                   ( m_extendedPrecisionProcessingFlag );
+  m_cTEncTop.setHighPrecisionOffsetsEnabledFlag                   ( m_highPrecisionOffsetsEnabledFlag );
   //====== Tool list ========
-  m_cTEncTop.setDeltaQpRD                    ( m_uiDeltaQpRD  );
-  m_cTEncTop.setUseASR                       ( m_bUseASR      );
-  m_cTEncTop.setUseHADME                     ( m_bUseHADME    );
-#if H_MV
-  m_cTEncTop.setdQPs                         ( m_aidQP[layerIdInVps]   );
-#else
-  m_cTEncTop.setdQPs                         ( m_aidQP        );
-#endif
-  m_cTEncTop.setUseRDOQ                      ( m_useRDOQ     );
-  m_cTEncTop.setUseRDOQTS                    ( m_useRDOQTS   );
-  m_cTEncTop.setRDpenalty                 ( m_rdPenalty );
-  m_cTEncTop.setQuadtreeTULog2MaxSize        ( m_uiQuadtreeTULog2MaxSize );
-  m_cTEncTop.setQuadtreeTULog2MinSize        ( m_uiQuadtreeTULog2MinSize );
-  m_cTEncTop.setQuadtreeTUMaxDepthInter      ( m_uiQuadtreeTUMaxDepthInter );
-  m_cTEncTop.setQuadtreeTUMaxDepthIntra      ( m_uiQuadtreeTUMaxDepthIntra );
-  m_cTEncTop.setUseFastEnc                   ( m_bUseFastEnc  );
-  m_cTEncTop.setUseEarlyCU                   ( m_bUseEarlyCU  ); 
-  m_cTEncTop.setUseFastDecisionForMerge      ( m_useFastDecisionForMerge  );
-  m_cTEncTop.setUseCbfFastMode            ( m_bUseCbfFastMode  );
-  m_cTEncTop.setUseEarlySkipDetection            ( m_useEarlySkipDetection );
-
-  m_cTEncTop.setUseTransformSkip             ( m_useTransformSkip      );
-  m_cTEncTop.setUseTransformSkipFast         ( m_useTransformSkipFast  );
-  m_cTEncTop.setUseConstrainedIntraPred      ( m_bUseConstrainedIntraPred );
-  m_cTEncTop.setPCMLog2MinSize          ( m_uiPCMLog2MinSize);
-  m_cTEncTop.setUsePCM                       ( m_usePCM );
-  m_cTEncTop.setPCMLog2MaxSize               ( m_pcmLog2MaxSize);
-  m_cTEncTop.setMaxNumMergeCand              ( m_maxNumMergeCand );
-  
+  m_cTEncTop.setDeltaQpRD                                         ( m_uiDeltaQpRD  );
+  m_cTEncTop.setUseASR                                            ( m_bUseASR      );
+  m_cTEncTop.setUseHADME                                          ( m_bUseHADME    );
+#if NH_MV
+  m_cTEncTop.setdQPs                                              ( m_aidQP[layerIdInVps]   );
+#else
+  m_cTEncTop.setdQPs                                              ( m_aidQP        );
+#endif
+  m_cTEncTop.setUseRDOQ                                           ( m_useRDOQ     );
+  m_cTEncTop.setUseRDOQTS                                         ( m_useRDOQTS   );
+#if T0196_SELECTIVE_RDOQ
+  m_cTEncTop.setUseSelectiveRDOQ                                  ( m_useSelectiveRDOQ );
+#endif
+  m_cTEncTop.setRDpenalty                                         ( m_rdPenalty );
+  m_cTEncTop.setMaxCUWidth                                        ( m_uiMaxCUWidth );
+  m_cTEncTop.setMaxCUHeight                                       ( m_uiMaxCUHeight );
+  m_cTEncTop.setMaxTotalCUDepth                                   ( m_uiMaxTotalCUDepth );
+  m_cTEncTop.setLog2DiffMaxMinCodingBlockSize                     ( m_uiLog2DiffMaxMinCodingBlockSize );
+  m_cTEncTop.setQuadtreeTULog2MaxSize                             ( m_uiQuadtreeTULog2MaxSize );
+  m_cTEncTop.setQuadtreeTULog2MinSize                             ( m_uiQuadtreeTULog2MinSize );
+  m_cTEncTop.setQuadtreeTUMaxDepthInter                           ( m_uiQuadtreeTUMaxDepthInter );
+  m_cTEncTop.setQuadtreeTUMaxDepthIntra                           ( m_uiQuadtreeTUMaxDepthIntra );
+  m_cTEncTop.setUseFastEnc                                        ( m_bUseFastEnc  );
+  m_cTEncTop.setUseEarlyCU                                        ( m_bUseEarlyCU  );
+  m_cTEncTop.setUseFastDecisionForMerge                           ( m_useFastDecisionForMerge  );
+  m_cTEncTop.setUseCbfFastMode                                    ( m_bUseCbfFastMode  );
+  m_cTEncTop.setUseEarlySkipDetection                             ( m_useEarlySkipDetection );
+  m_cTEncTop.setCrossComponentPredictionEnabledFlag               ( m_crossComponentPredictionEnabledFlag );
+  m_cTEncTop.setUseReconBasedCrossCPredictionEstimate             ( m_reconBasedCrossCPredictionEstimate );
+#if NH_MV
+  m_cTEncTop.setLog2SaoOffsetScale                                ( CHANNEL_TYPE_LUMA  , m_log2SaoOffsetScale[layerIdInVps][CHANNEL_TYPE_LUMA]   );
+  m_cTEncTop.setLog2SaoOffsetScale                                ( CHANNEL_TYPE_CHROMA, m_log2SaoOffsetScale[layerIdInVps][CHANNEL_TYPE_CHROMA] );
+#else
+  m_cTEncTop.setLog2SaoOffsetScale                                ( CHANNEL_TYPE_LUMA  , m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA]   );
+  m_cTEncTop.setLog2SaoOffsetScale                                ( CHANNEL_TYPE_CHROMA, m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA] );
+#endif
+  m_cTEncTop.setUseTransformSkip                                  ( m_useTransformSkip      );
+  m_cTEncTop.setUseTransformSkipFast                              ( m_useTransformSkipFast  );
+  m_cTEncTop.setTransformSkipRotationEnabledFlag                  ( m_transformSkipRotationEnabledFlag );
+  m_cTEncTop.setTransformSkipContextEnabledFlag                   ( m_transformSkipContextEnabledFlag   );
+  m_cTEncTop.setPersistentRiceAdaptationEnabledFlag               ( m_persistentRiceAdaptationEnabledFlag );
+  m_cTEncTop.setCabacBypassAlignmentEnabledFlag                   ( m_cabacBypassAlignmentEnabledFlag );
+  m_cTEncTop.setLog2MaxTransformSkipBlockSize                     ( m_log2MaxTransformSkipBlockSize  );
+  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
+  {
+    m_cTEncTop.setRdpcmEnabledFlag                                ( RDPCMSignallingMode(signallingModeIndex), m_rdpcmEnabledFlag[signallingModeIndex]);
+  }
+  m_cTEncTop.setUseConstrainedIntraPred                           ( m_bUseConstrainedIntraPred );
+  m_cTEncTop.setFastUDIUseMPMEnabled                              ( m_bFastUDIUseMPMEnabled );
+  m_cTEncTop.setFastMEForGenBLowDelayEnabled                      ( m_bFastMEForGenBLowDelayEnabled );
+  m_cTEncTop.setUseBLambdaForNonKeyLowDelayPictures               ( m_bUseBLambdaForNonKeyLowDelayPictures );
+  m_cTEncTop.setPCMLog2MinSize                                    ( m_uiPCMLog2MinSize);
+  m_cTEncTop.setUsePCM                                            ( m_usePCM );
+
+  // set internal bit-depth and constants
+  for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+  {
+    m_cTEncTop.setBitDepth((ChannelType)channelType, m_internalBitDepth[channelType]);
+    m_cTEncTop.setPCMBitDepth((ChannelType)channelType, m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[channelType] : m_internalBitDepth[channelType]);
+  }
+
+  m_cTEncTop.setPCMLog2MaxSize                                    ( m_pcmLog2MaxSize);
+  m_cTEncTop.setMaxNumMergeCand                                   ( m_maxNumMergeCand );
+
 
   //====== Weighted Prediction ========
-  m_cTEncTop.setUseWP                   ( m_useWeightedPred      );
-  m_cTEncTop.setWPBiPred                ( m_useWeightedBiPred   );
+  m_cTEncTop.setUseWP                                             ( m_useWeightedPred      );
+  m_cTEncTop.setWPBiPred                                          ( m_useWeightedBiPred   );
   //====== Parallel Merge Estimation ========
-  m_cTEncTop.setLog2ParallelMergeLevelMinus2 ( m_log2ParallelMergeLevel - 2 );
+  m_cTEncTop.setLog2ParallelMergeLevelMinus2                      ( m_log2ParallelMergeLevel - 2 );
 
   //====== Slice ========
-  m_cTEncTop.setSliceMode               ( m_sliceMode                );
-  m_cTEncTop.setSliceArgument           ( m_sliceArgument            );
+  m_cTEncTop.setSliceMode                                         ( (SliceConstraint) m_sliceMode );
+  m_cTEncTop.setSliceArgument                                     ( m_sliceArgument            );
 
   //====== Dependent Slice ========
-  m_cTEncTop.setSliceSegmentMode        ( m_sliceSegmentMode         );
-  m_cTEncTop.setSliceSegmentArgument    ( m_sliceSegmentArgument     );
-  Int iNumPartInCU = 1<<(m_uiMaxCUDepth<<1);
-  if(m_sliceSegmentMode==FIXED_NUMBER_OF_LCU)
-  {
-    m_cTEncTop.setSliceSegmentArgument ( m_sliceSegmentArgument * iNumPartInCU );
-  }
-  if(m_sliceMode==FIXED_NUMBER_OF_LCU)
-  {
-    m_cTEncTop.setSliceArgument ( m_sliceArgument * iNumPartInCU );
-  }
-  if(m_sliceMode==FIXED_NUMBER_OF_TILES)
-  {
-    m_cTEncTop.setSliceArgument ( m_sliceArgument );
-  }
-  
-  if(m_sliceMode == 0 )
+  m_cTEncTop.setSliceSegmentMode                                  (  (SliceConstraint) m_sliceSegmentMode );
+  m_cTEncTop.setSliceSegmentArgument                              ( m_sliceSegmentArgument     );
+
+  if(m_sliceMode == NO_SLICES )
   {
     m_bLFCrossSliceBoundaryFlag = true;
   }
-  m_cTEncTop.setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
-#if H_MV
+  m_cTEncTop.setLFCrossSliceBoundaryFlag                          ( m_bLFCrossSliceBoundaryFlag );
+#if NH_MV
   m_cTEncTop.setUseSAO ( m_bUseSAO[layerIdInVps] );
 #else
-  m_cTEncTop.setUseSAO ( m_bUseSAO );
-#endif
-  m_cTEncTop.setMaxNumOffsetsPerPic (m_maxNumOffsetsPerPic);
-
-  m_cTEncTop.setSaoLcuBoundary (m_saoLcuBoundary);
-  m_cTEncTop.setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag); 
-  m_cTEncTop.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag); 
-
-  m_cTEncTop.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
-  m_cTEncTop.setRecoveryPointSEIEnabled( m_recoveryPointSEIEnabled );
-  m_cTEncTop.setBufferingPeriodSEIEnabled( m_bufferingPeriodSEIEnabled );
-  m_cTEncTop.setPictureTimingSEIEnabled( m_pictureTimingSEIEnabled );
-  m_cTEncTop.setToneMappingInfoSEIEnabled                 ( m_toneMappingInfoSEIEnabled );
-  m_cTEncTop.setTMISEIToneMapId                           ( m_toneMapId );
-  m_cTEncTop.setTMISEIToneMapCancelFlag                   ( m_toneMapCancelFlag );
-  m_cTEncTop.setTMISEIToneMapPersistenceFlag              ( m_toneMapPersistenceFlag );
-  m_cTEncTop.setTMISEICodedDataBitDepth                   ( m_toneMapCodedDataBitDepth );
-  m_cTEncTop.setTMISEITargetBitDepth                      ( m_toneMapTargetBitDepth );
-  m_cTEncTop.setTMISEIModelID                             ( m_toneMapModelId );
-  m_cTEncTop.setTMISEIMinValue                            ( m_toneMapMinValue );
-  m_cTEncTop.setTMISEIMaxValue                            ( m_toneMapMaxValue );
-  m_cTEncTop.setTMISEISigmoidMidpoint                     ( m_sigmoidMidpoint );
-  m_cTEncTop.setTMISEISigmoidWidth                        ( m_sigmoidWidth );
-  m_cTEncTop.setTMISEIStartOfCodedInterva                 ( m_startOfCodedInterval );
-  m_cTEncTop.setTMISEINumPivots                           ( m_numPivots );
-  m_cTEncTop.setTMISEICodedPivotValue                     ( m_codedPivotValue );
-  m_cTEncTop.setTMISEITargetPivotValue                    ( m_targetPivotValue );
-  m_cTEncTop.setTMISEICameraIsoSpeedIdc                   ( m_cameraIsoSpeedIdc );
-  m_cTEncTop.setTMISEICameraIsoSpeedValue                 ( m_cameraIsoSpeedValue );
-  m_cTEncTop.setTMISEIExposureIndexIdc                    ( m_exposureIndexIdc );
-  m_cTEncTop.setTMISEIExposureIndexValue                  ( m_exposureIndexValue );
-  m_cTEncTop.setTMISEIExposureCompensationValueSignFlag   ( m_exposureCompensationValueSignFlag );
-  m_cTEncTop.setTMISEIExposureCompensationValueNumerator  ( m_exposureCompensationValueNumerator );
-  m_cTEncTop.setTMISEIExposureCompensationValueDenomIdc   ( m_exposureCompensationValueDenomIdc );
-  m_cTEncTop.setTMISEIRefScreenLuminanceWhite             ( m_refScreenLuminanceWhite );
-  m_cTEncTop.setTMISEIExtendedRangeWhiteLevel             ( m_extendedRangeWhiteLevel );
-  m_cTEncTop.setTMISEINominalBlackLevelLumaCodeValue      ( m_nominalBlackLevelLumaCodeValue );
-  m_cTEncTop.setTMISEINominalWhiteLevelLumaCodeValue      ( m_nominalWhiteLevelLumaCodeValue );
-  m_cTEncTop.setTMISEIExtendedWhiteLevelLumaCodeValue     ( m_extendedWhiteLevelLumaCodeValue );
-  m_cTEncTop.setFramePackingArrangementSEIEnabled( m_framePackingSEIEnabled );
-  m_cTEncTop.setFramePackingArrangementSEIType( m_framePackingSEIType );
-  m_cTEncTop.setFramePackingArrangementSEIId( m_framePackingSEIId );
-  m_cTEncTop.setFramePackingArrangementSEIQuincunx( m_framePackingSEIQuincunx );
-  m_cTEncTop.setFramePackingArrangementSEIInterpretation( m_framePackingSEIInterpretation );
-  m_cTEncTop.setDisplayOrientationSEIAngle( m_displayOrientationSEIAngle );
-  m_cTEncTop.setTemporalLevel0IndexSEIEnabled( m_temporalLevel0IndexSEIEnabled );
-  m_cTEncTop.setGradualDecodingRefreshInfoEnabled( m_gradualDecodingRefreshInfoEnabled );
-  m_cTEncTop.setDecodingUnitInfoSEIEnabled( m_decodingUnitInfoSEIEnabled );
-  m_cTEncTop.setSOPDescriptionSEIEnabled( m_SOPDescriptionSEIEnabled );
-  m_cTEncTop.setScalableNestingSEIEnabled( m_scalableNestingSEIEnabled );
-#if H_MV
-  m_cTEncTop.setSubBitstreamPropSEIEnabled( m_subBistreamPropSEIEnabled );
-  if( m_subBistreamPropSEIEnabled )
-  {
-    m_cTEncTop.setNumAdditionalSubStreams ( m_sbPropNumAdditionalSubStreams );
-    m_cTEncTop.setSubBitstreamMode        ( m_sbPropSubBitstreamMode );
-    m_cTEncTop.setOutputLayerSetIdxToVps  ( m_sbPropOutputLayerSetIdxToVps );
-    m_cTEncTop.setHighestSublayerId       ( m_sbPropHighestSublayerId );
-    m_cTEncTop.setAvgBitRate              ( m_sbPropAvgBitRate );
-    m_cTEncTop.setMaxBitRate              ( m_sbPropMaxBitRate );
-  }
-#endif
-  m_cTEncTop.setTileUniformSpacingFlag     ( m_tileUniformSpacingFlag );
-  m_cTEncTop.setNumColumnsMinus1           ( m_numTileColumnsMinus1 );
-  m_cTEncTop.setNumRowsMinus1              ( m_numTileRowsMinus1 );
+  m_cTEncTop.setUseSAO                                            ( m_bUseSAO );
+#endif
+  m_cTEncTop.setTestSAODisableAtPictureLevel                      ( m_bTestSAODisableAtPictureLevel );
+  m_cTEncTop.setSaoEncodingRate                                   ( m_saoEncodingRate );
+  m_cTEncTop.setSaoEncodingRateChroma                             ( m_saoEncodingRateChroma );
+  m_cTEncTop.setMaxNumOffsetsPerPic                               ( m_maxNumOffsetsPerPic);
+
+  m_cTEncTop.setSaoCtuBoundary                                    ( m_saoCtuBoundary);
+  m_cTEncTop.setPCMInputBitDepthFlag                              ( m_bPCMInputBitDepthFlag);
+  m_cTEncTop.setPCMFilterDisableFlag                              ( m_bPCMFilterDisableFlag);
+
+  m_cTEncTop.setIntraSmoothingDisabledFlag                        (!m_enableIntraReferenceSmoothing );
+  m_cTEncTop.setDecodedPictureHashSEIEnabled                      ( m_decodedPictureHashSEIEnabled );
+  m_cTEncTop.setRecoveryPointSEIEnabled                           ( m_recoveryPointSEIEnabled );
+  m_cTEncTop.setBufferingPeriodSEIEnabled                         ( m_bufferingPeriodSEIEnabled );
+  m_cTEncTop.setPictureTimingSEIEnabled                           ( m_pictureTimingSEIEnabled );
+  m_cTEncTop.setToneMappingInfoSEIEnabled                         ( m_toneMappingInfoSEIEnabled );
+  m_cTEncTop.setTMISEIToneMapId                                   ( m_toneMapId );
+  m_cTEncTop.setTMISEIToneMapCancelFlag                           ( m_toneMapCancelFlag );
+  m_cTEncTop.setTMISEIToneMapPersistenceFlag                      ( m_toneMapPersistenceFlag );
+  m_cTEncTop.setTMISEICodedDataBitDepth                           ( m_toneMapCodedDataBitDepth );
+  m_cTEncTop.setTMISEITargetBitDepth                              ( m_toneMapTargetBitDepth );
+  m_cTEncTop.setTMISEIModelID                                     ( m_toneMapModelId );
+  m_cTEncTop.setTMISEIMinValue                                    ( m_toneMapMinValue );
+  m_cTEncTop.setTMISEIMaxValue                                    ( m_toneMapMaxValue );
+  m_cTEncTop.setTMISEISigmoidMidpoint                             ( m_sigmoidMidpoint );
+  m_cTEncTop.setTMISEISigmoidWidth                                ( m_sigmoidWidth );
+  m_cTEncTop.setTMISEIStartOfCodedInterva                         ( m_startOfCodedInterval );
+  m_cTEncTop.setTMISEINumPivots                                   ( m_numPivots );
+  m_cTEncTop.setTMISEICodedPivotValue                             ( m_codedPivotValue );
+  m_cTEncTop.setTMISEITargetPivotValue                            ( m_targetPivotValue );
+  m_cTEncTop.setTMISEICameraIsoSpeedIdc                           ( m_cameraIsoSpeedIdc );
+  m_cTEncTop.setTMISEICameraIsoSpeedValue                         ( m_cameraIsoSpeedValue );
+  m_cTEncTop.setTMISEIExposureIndexIdc                            ( m_exposureIndexIdc );
+  m_cTEncTop.setTMISEIExposureIndexValue                          ( m_exposureIndexValue );
+  m_cTEncTop.setTMISEIExposureCompensationValueSignFlag           ( m_exposureCompensationValueSignFlag );
+  m_cTEncTop.setTMISEIExposureCompensationValueNumerator          ( m_exposureCompensationValueNumerator );
+  m_cTEncTop.setTMISEIExposureCompensationValueDenomIdc           ( m_exposureCompensationValueDenomIdc );
+  m_cTEncTop.setTMISEIRefScreenLuminanceWhite                     ( m_refScreenLuminanceWhite );
+  m_cTEncTop.setTMISEIExtendedRangeWhiteLevel                     ( m_extendedRangeWhiteLevel );
+  m_cTEncTop.setTMISEINominalBlackLevelLumaCodeValue              ( m_nominalBlackLevelLumaCodeValue );
+  m_cTEncTop.setTMISEINominalWhiteLevelLumaCodeValue              ( m_nominalWhiteLevelLumaCodeValue );
+  m_cTEncTop.setTMISEIExtendedWhiteLevelLumaCodeValue             ( m_extendedWhiteLevelLumaCodeValue );
+  m_cTEncTop.setChromaSamplingFilterHintEnabled                   ( m_chromaSamplingFilterSEIenabled );
+  m_cTEncTop.setChromaSamplingHorFilterIdc                        ( m_chromaSamplingHorFilterIdc );
+  m_cTEncTop.setChromaSamplingVerFilterIdc                        ( m_chromaSamplingVerFilterIdc );
+  m_cTEncTop.setFramePackingArrangementSEIEnabled                 ( m_framePackingSEIEnabled );
+  m_cTEncTop.setFramePackingArrangementSEIType                    ( m_framePackingSEIType );
+  m_cTEncTop.setFramePackingArrangementSEIId                      ( m_framePackingSEIId );
+  m_cTEncTop.setFramePackingArrangementSEIQuincunx                ( m_framePackingSEIQuincunx );
+  m_cTEncTop.setFramePackingArrangementSEIInterpretation          ( m_framePackingSEIInterpretation );
+  m_cTEncTop.setSegmentedRectFramePackingArrangementSEIEnabled    ( m_segmentedRectFramePackingSEIEnabled );
+  m_cTEncTop.setSegmentedRectFramePackingArrangementSEICancel     ( m_segmentedRectFramePackingSEICancel );
+  m_cTEncTop.setSegmentedRectFramePackingArrangementSEIType       ( m_segmentedRectFramePackingSEIType );
+  m_cTEncTop.setSegmentedRectFramePackingArrangementSEIPersistence( m_segmentedRectFramePackingSEIPersistence );
+  m_cTEncTop.setDisplayOrientationSEIAngle                        ( m_displayOrientationSEIAngle );
+  m_cTEncTop.setTemporalLevel0IndexSEIEnabled                     ( m_temporalLevel0IndexSEIEnabled );
+  m_cTEncTop.setGradualDecodingRefreshInfoEnabled                 ( m_gradualDecodingRefreshInfoEnabled );
+  m_cTEncTop.setNoDisplaySEITLayer                                ( m_noDisplaySEITLayer );
+  m_cTEncTop.setDecodingUnitInfoSEIEnabled                        ( m_decodingUnitInfoSEIEnabled );
+  m_cTEncTop.setSOPDescriptionSEIEnabled                          ( m_SOPDescriptionSEIEnabled );
+  m_cTEncTop.setScalableNestingSEIEnabled                         ( m_scalableNestingSEIEnabled );
+#if NH_MV
+  m_cTEncTop.setSubBitstreamPropSEIEnabled                        ( m_subBistreamPropSEIEnabled );
+  if( m_subBistreamPropSEIEnabled )                               
+  {                                                               
+    m_cTEncTop.setNumAdditionalSubStreams                         ( m_sbPropNumAdditionalSubStreams );
+    m_cTEncTop.setSubBitstreamMode                                ( m_sbPropSubBitstreamMode );
+    m_cTEncTop.setOutputLayerSetIdxToVps                          ( m_sbPropOutputLayerSetIdxToVps );
+    m_cTEncTop.setHighestSublayerId                               ( m_sbPropHighestSublayerId );
+    m_cTEncTop.setAvgBitRate                                      ( m_sbPropAvgBitRate );
+    m_cTEncTop.setMaxBitRate                                      ( m_sbPropMaxBitRate );
+  }
+#endif
+
+  m_cTEncTop.setTMCTSSEIEnabled                                   ( m_tmctsSEIEnabled );
+  m_cTEncTop.setTimeCodeSEIEnabled                                ( m_timeCodeSEIEnabled );
+  m_cTEncTop.setNumberOfTimeSets                                  ( m_timeCodeSEINumTs );
+  for(Int i = 0; i < m_timeCodeSEINumTs; i++)
+  {
+    m_cTEncTop.setTimeSet(m_timeSetArray[i], i);
+  }
+  m_cTEncTop.setKneeSEIEnabled                                    ( m_kneeSEIEnabled );
+  m_cTEncTop.setKneeSEIId                                         ( m_kneeSEIId );
+  m_cTEncTop.setKneeSEICancelFlag                                 ( m_kneeSEICancelFlag );
+  m_cTEncTop.setKneeSEIPersistenceFlag                            ( m_kneeSEIPersistenceFlag );
+  m_cTEncTop.setKneeSEIInputDrange                                ( m_kneeSEIInputDrange );
+  m_cTEncTop.setKneeSEIInputDispLuminance                         ( m_kneeSEIInputDispLuminance );
+  m_cTEncTop.setKneeSEIOutputDrange                               ( m_kneeSEIOutputDrange );
+  m_cTEncTop.setKneeSEIOutputDispLuminance                        ( m_kneeSEIOutputDispLuminance );
+  m_cTEncTop.setKneeSEINumKneePointsMinus1                        ( m_kneeSEINumKneePointsMinus1 );
+  m_cTEncTop.setKneeSEIInputKneePoint                             ( m_kneeSEIInputKneePoint );
+  m_cTEncTop.setKneeSEIOutputKneePoint                            ( m_kneeSEIOutputKneePoint );
+  m_cTEncTop.setMasteringDisplaySEI                               ( m_masteringDisplay );
+
+  m_cTEncTop.setTileUniformSpacingFlag                            ( m_tileUniformSpacingFlag );
+  m_cTEncTop.setNumColumnsMinus1                                  ( m_numTileColumnsMinus1 );
+  m_cTEncTop.setNumRowsMinus1                                     ( m_numTileRowsMinus1 );
   if(!m_tileUniformSpacingFlag)
   {
-    m_cTEncTop.setColumnWidth              ( m_tileColumnWidth );
-    m_cTEncTop.setRowHeight                ( m_tileRowHeight );
+    m_cTEncTop.setColumnWidth                                     ( m_tileColumnWidth );
+    m_cTEncTop.setRowHeight                                       ( m_tileRowHeight );
   }
   m_cTEncTop.xCheckGSParameters();
-  Int uiTilesCount          = (m_numTileRowsMinus1+1) * (m_numTileColumnsMinus1+1);
+  Int uiTilesCount = (m_numTileRowsMinus1+1) * (m_numTileColumnsMinus1+1);
   if(uiTilesCount == 1)
   {
-    m_bLFCrossTileBoundaryFlag = true; 
-  }
-  m_cTEncTop.setLFCrossTileBoundaryFlag( m_bLFCrossTileBoundaryFlag );
-  m_cTEncTop.setWaveFrontSynchro           ( m_iWaveFrontSynchro );
-  m_cTEncTop.setWaveFrontSubstreams        ( m_iWaveFrontSubstreams );
-  m_cTEncTop.setTMVPModeId ( m_TMVPModeId );
-  m_cTEncTop.setUseScalingListId           ( m_useScalingListId  );
-  m_cTEncTop.setScalingListFile            ( m_scalingListFile   );
-  m_cTEncTop.setSignHideFlag(m_signHideFlag);
+    m_bLFCrossTileBoundaryFlag = true;
+  }
+  m_cTEncTop.setLFCrossTileBoundaryFlag                           ( m_bLFCrossTileBoundaryFlag );
+  m_cTEncTop.setWaveFrontSynchro                                  ( m_iWaveFrontSynchro );
+  m_cTEncTop.setTMVPModeId                                        ( m_TMVPModeId );
+  m_cTEncTop.setUseScalingListId                                  ( m_useScalingListId  );
+  m_cTEncTop.setScalingListFile                                   ( m_scalingListFile   );
+  m_cTEncTop.setSignHideFlag                                      ( m_signHideFlag);
 #if KWU_RC_VIEWRC_E0227 || KWU_RC_MADPRED_E0227
   if(!m_cTEncTop.getIsDepth())    //only for texture
   {
-    m_cTEncTop.setUseRateCtrl         ( m_RCEnableRateControl );
-  }
-  else
-  {
-    m_cTEncTop.setUseRateCtrl         ( 0 );
-  }
-#else
-    m_cTEncTop.setUseRateCtrl         ( m_RCEnableRateControl );
+    m_cTEncTop.setUseRateCtrl                                     ( m_RCEnableRateControl );
+  }                                                          
+  else                                                       
+  {                                                          
+    m_cTEncTop.setUseRateCtrl                                     ( 0 );
+  }
+#else
+  m_cTEncTop.setUseRateCtrl                                       ( m_RCEnableRateControl );
 #endif
 #if !KWU_RC_VIEWRC_E0227
-  m_cTEncTop.setTargetBitrate       ( m_RCTargetBitrate );
-#endif
-  m_cTEncTop.setKeepHierBit         ( m_RCKeepHierarchicalBit );
-  m_cTEncTop.setLCULevelRC          ( m_RCLCULevelRC );
-  m_cTEncTop.setUseLCUSeparateModel ( m_RCUseLCUSeparateModel );
-  m_cTEncTop.setInitialQP           ( m_RCInitialQP );
-  m_cTEncTop.setForceIntraQP        ( m_RCForceIntraQP );
+  m_cTEncTop.setTargetBitrate                                     ( m_RCTargetBitrate );
+#endif
+  m_cTEncTop.setKeepHierBit                                       ( m_RCKeepHierarchicalBit );
+  m_cTEncTop.setLCULevelRC                                        ( m_RCLCULevelRC );
+  m_cTEncTop.setUseLCUSeparateModel                               ( m_RCUseLCUSeparateModel );
+  m_cTEncTop.setInitialQP                                         ( m_RCInitialQP );
+  m_cTEncTop.setForceIntraQP                                      ( m_RCForceIntraQP );
 #if KWU_RC_MADPRED_E0227
   if(m_cTEncTop.getUseRateCtrl() && !m_cTEncTop.getIsDepth())
@@ -598,83 +721,51 @@
   }
 #endif
-  m_cTEncTop.setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
-  m_cTEncTop.setCUTransquantBypassFlagForceValue(m_CUTransquantBypassFlagForce);
-  m_cTEncTop.setUseRecalculateQPAccordingToLambda( m_recalculateQPAccordingToLambda );
-  m_cTEncTop.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
-  m_cTEncTop.setActiveParameterSetsSEIEnabled ( m_activeParameterSetsSEIEnabled ); 
-  m_cTEncTop.setVuiParametersPresentFlag( m_vuiParametersPresentFlag );
-  m_cTEncTop.setAspectRatioInfoPresentFlag( m_aspectRatioInfoPresentFlag);
-  m_cTEncTop.setAspectRatioIdc( m_aspectRatioIdc );
-  m_cTEncTop.setSarWidth( m_sarWidth );
-  m_cTEncTop.setSarHeight( m_sarHeight );
-  m_cTEncTop.setOverscanInfoPresentFlag( m_overscanInfoPresentFlag );
-  m_cTEncTop.setOverscanAppropriateFlag( m_overscanAppropriateFlag );
-  m_cTEncTop.setVideoSignalTypePresentFlag( m_videoSignalTypePresentFlag );
-  m_cTEncTop.setVideoFormat( m_videoFormat );
-  m_cTEncTop.setVideoFullRangeFlag( m_videoFullRangeFlag );
-  m_cTEncTop.setColourDescriptionPresentFlag( m_colourDescriptionPresentFlag );
-  m_cTEncTop.setColourPrimaries( m_colourPrimaries );
-  m_cTEncTop.setTransferCharacteristics( m_transferCharacteristics );
-  m_cTEncTop.setMatrixCoefficients( m_matrixCoefficients );
-  m_cTEncTop.setChromaLocInfoPresentFlag( m_chromaLocInfoPresentFlag );
-  m_cTEncTop.setChromaSampleLocTypeTopField( m_chromaSampleLocTypeTopField );
-  m_cTEncTop.setChromaSampleLocTypeBottomField( m_chromaSampleLocTypeBottomField );
-  m_cTEncTop.setNeutralChromaIndicationFlag( m_neutralChromaIndicationFlag );
-  m_cTEncTop.setDefaultDisplayWindow( m_defDispWinLeftOffset, m_defDispWinRightOffset, m_defDispWinTopOffset, m_defDispWinBottomOffset );
-  m_cTEncTop.setFrameFieldInfoPresentFlag( m_frameFieldInfoPresentFlag );
-  m_cTEncTop.setPocProportionalToTimingFlag( m_pocProportionalToTimingFlag );
-  m_cTEncTop.setNumTicksPocDiffOneMinus1   ( m_numTicksPocDiffOneMinus1    );
-  m_cTEncTop.setBitstreamRestrictionFlag( m_bitstreamRestrictionFlag );
-  m_cTEncTop.setTilesFixedStructureFlag( m_tilesFixedStructureFlag );
-  m_cTEncTop.setMotionVectorsOverPicBoundariesFlag( m_motionVectorsOverPicBoundariesFlag );
-  m_cTEncTop.setMinSpatialSegmentationIdc( m_minSpatialSegmentationIdc );
-  m_cTEncTop.setMaxBytesPerPicDenom( m_maxBytesPerPicDenom );
-  m_cTEncTop.setMaxBitsPerMinCuDenom( m_maxBitsPerMinCuDenom );
-  m_cTEncTop.setLog2MaxMvLengthHorizontal( m_log2MaxMvLengthHorizontal );
-  m_cTEncTop.setLog2MaxMvLengthVertical( m_log2MaxMvLengthVertical );
-#if H_MV
-  }
-#endif
-#if H_3D
- /// SET Profiles
-  for(Int layerIdInVps = 0; layerIdInVps < m_numberOfLayers; layerIdInVps++)
-  {
-    Int profileIdc = -1; 
-    for (Int olsIdx = 0; olsIdx < vps.getNumOutputLayerSets(); olsIdx++ )
-    {   
-      Int lsIdx = vps.olsIdxToLsIdx( olsIdx );
-      for(Int i = 0; i < vps.getNumLayersInIdList( lsIdx ); i++ )
-      {
-        if( vps.getLayerIdInNuh( layerIdInVps) == vps.getLayerSetLayerIdList(lsIdx, i) )
-        {
-          Int ptlIdx = vps.getProfileTierLevelIdx( olsIdx, i );
-          if ( ptlIdx != -1 )
-          {
-            Int curProfileIdc = vps.getPTL(ptlIdx)->getGeneralPTL()->getProfileIdc(); 
-            if (profileIdc == -1)   
-            {
-              profileIdc = curProfileIdc; 
-            }
-            else
-            {   
-              if ( profileIdc != curProfileIdc )
-              {              
-                fprintf(stderr, "Error: ProfileIdc for layer with index %d in VPS not equal in all OLSs. \n", layerIdInVps );
-                exit(EXIT_FAILURE);
-              }
-            }
-          }
-        }
-      }
-    }
-    if (profileIdc == -1 )
-    {
-      fprintf(stderr, "Error: No profile given for layer with index %d in VPS not equal in all OLS. \n", layerIdInVps );
-      exit(EXIT_FAILURE);
-    }
-    m_acTEncTopList[ layerIdInVps ]->setProfileIdc( profileIdc ); 
-  }
-#endif
-#if H_3D_VSO
+  m_cTEncTop.setTransquantBypassEnableFlag                        ( m_TransquantBypassEnableFlag );
+  m_cTEncTop.setCUTransquantBypassFlagForceValue                  ( m_CUTransquantBypassFlagForce );
+  m_cTEncTop.setCostMode                                          ( m_costMode );
+  m_cTEncTop.setUseRecalculateQPAccordingToLambda                 ( m_recalculateQPAccordingToLambda );
+  m_cTEncTop.setUseStrongIntraSmoothing                           ( m_useStrongIntraSmoothing );
+  m_cTEncTop.setActiveParameterSetsSEIEnabled                     ( m_activeParameterSetsSEIEnabled );
+  m_cTEncTop.setVuiParametersPresentFlag                          ( m_vuiParametersPresentFlag );
+  m_cTEncTop.setAspectRatioInfoPresentFlag                        ( m_aspectRatioInfoPresentFlag);
+  m_cTEncTop.setAspectRatioIdc                                    ( m_aspectRatioIdc );
+  m_cTEncTop.setSarWidth                                          ( m_sarWidth );
+  m_cTEncTop.setSarHeight                                         ( m_sarHeight );
+  m_cTEncTop.setOverscanInfoPresentFlag                           ( m_overscanInfoPresentFlag );
+  m_cTEncTop.setOverscanAppropriateFlag                           ( m_overscanAppropriateFlag );
+  m_cTEncTop.setVideoSignalTypePresentFlag                        ( m_videoSignalTypePresentFlag );
+  m_cTEncTop.setVideoFormat                                       ( m_videoFormat );
+  m_cTEncTop.setVideoFullRangeFlag                                ( m_videoFullRangeFlag );
+  m_cTEncTop.setColourDescriptionPresentFlag                      ( m_colourDescriptionPresentFlag );
+  m_cTEncTop.setColourPrimaries                                   ( m_colourPrimaries );
+  m_cTEncTop.setTransferCharacteristics                           ( m_transferCharacteristics );
+  m_cTEncTop.setMatrixCoefficients                                ( m_matrixCoefficients );
+  m_cTEncTop.setChromaLocInfoPresentFlag                          ( m_chromaLocInfoPresentFlag );
+  m_cTEncTop.setChromaSampleLocTypeTopField                       ( m_chromaSampleLocTypeTopField );
+  m_cTEncTop.setChromaSampleLocTypeBottomField                    ( m_chromaSampleLocTypeBottomField );
+  m_cTEncTop.setNeutralChromaIndicationFlag                       ( m_neutralChromaIndicationFlag );
+  m_cTEncTop.setDefaultDisplayWindow                              ( m_defDispWinLeftOffset, m_defDispWinRightOffset, m_defDispWinTopOffset, m_defDispWinBottomOffset );
+  m_cTEncTop.setFrameFieldInfoPresentFlag                         ( m_frameFieldInfoPresentFlag );
+  m_cTEncTop.setPocProportionalToTimingFlag                       ( m_pocProportionalToTimingFlag );
+  m_cTEncTop.setNumTicksPocDiffOneMinus1                          ( m_numTicksPocDiffOneMinus1    );
+  m_cTEncTop.setBitstreamRestrictionFlag                          ( m_bitstreamRestrictionFlag );
+  m_cTEncTop.setTilesFixedStructureFlag                           ( m_tilesFixedStructureFlag );
+  m_cTEncTop.setMotionVectorsOverPicBoundariesFlag                ( m_motionVectorsOverPicBoundariesFlag );
+  m_cTEncTop.setMinSpatialSegmentationIdc                         ( m_minSpatialSegmentationIdc );
+  m_cTEncTop.setMaxBytesPerPicDenom                               ( m_maxBytesPerPicDenom );
+  m_cTEncTop.setMaxBitsPerMinCuDenom                              ( m_maxBitsPerMinCuDenom );
+  m_cTEncTop.setLog2MaxMvLengthHorizontal                         ( m_log2MaxMvLengthHorizontal );
+  m_cTEncTop.setLog2MaxMvLengthVertical                           ( m_log2MaxMvLengthVertical );
+  m_cTEncTop.setEfficientFieldIRAPEnabled                         ( m_bEfficientFieldIRAPEnabled );
+  m_cTEncTop.setHarmonizeGopFirstFieldCoupleEnabled               ( m_bHarmonizeGopFirstFieldCoupleEnabled );
+
+  m_cTEncTop.setSummaryOutFilename                                ( m_summaryOutFilename );
+  m_cTEncTop.setSummaryPicFilenameBase                            ( m_summaryPicFilenameBase );
+  m_cTEncTop.setSummaryVerboseness                                ( m_summaryVerboseness );
+
+#if NH_MV
+  }
+#endif
+#if NH_3D_VSO
   if ( m_bUseVSO )
   {
@@ -682,7 +773,7 @@
     {
 #if H_3D_VSO_EARLY_SKIP
-      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, g_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0, m_bVSOEarlySkip );
-#else
-      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, g_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0 );
+      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0, m_bVSOEarlySkip );
+#else
+      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0 );
 #endif
       for ( Int layer = 0; layer < m_numberOfLayers ; layer++ )
@@ -717,5 +808,5 @@
 Void TAppEncTop::xCreateLib()
 {
-#if H_MV
+#if NH_MV
   // initialize global variables
   initROM();
@@ -726,10 +817,10 @@
   for( Int layer=0; layer < m_numberOfLayers; layer++)
   {
-    m_acTVideoIOYuvInputFileList[layer]->open( m_pchInputFileList[layer],     false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC );  // read  mode
-    m_acTVideoIOYuvInputFileList[layer]->skipFrames( m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1]);
+    m_acTVideoIOYuvInputFileList[layer]->open( m_pchInputFileList[layer],     false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
+    m_acTVideoIOYuvInputFileList[layer]->skipFrames( m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
 
     if (m_pchReconFileList[layer])
     {
-      m_acTVideoIOYuvReconFileList[layer]->open( m_pchReconFileList[layer], true, m_outputBitDepthY, m_outputBitDepthC, m_internalBitDepthY, m_internalBitDepthC);  // write mode
+      m_acTVideoIOYuvReconFileList[layer]->open( m_pchReconFileList[layer], true, m_outputBitDepth, m_outputBitDepth, m_internalBitDepth);  // write mode
     }
     m_acTEncTopList[layer]->create();
@@ -737,10 +828,12 @@
 #else
   // Video I/O
-  m_cTVideoIOYuvInputFile.open( m_pchInputFile,     false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC );  // read  mode
-  m_cTVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1]);
+  m_cTVideoIOYuvInputFile.open( m_pchInputFile,     false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
+  m_cTVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
 
   if (m_pchReconFile)
-    m_cTVideoIOYuvReconFile.open(m_pchReconFile, true, m_outputBitDepthY, m_outputBitDepthC, m_internalBitDepthY, m_internalBitDepthC);  // write mode
-  
+  {
+    m_cTVideoIOYuvReconFile.open(m_pchReconFile, true, m_outputBitDepth, m_outputBitDepth, m_internalBitDepth);  // write mode
+  }
+
   // Neo Decoder
   m_cTEncTop.create();
@@ -750,5 +843,5 @@
 Void TAppEncTop::xDestroyLib()
 {
-#if H_MV
+#if NH_MV
   // destroy ROM
   destroyROM();
@@ -766,6 +859,6 @@
     delete m_acTEncTopList[layer] ; 
     m_acTEncTopList[layer] = NULL;
-    delete m_picYuvRec[layer] ; 
-    m_picYuvRec[layer] = NULL;
+    delete m_cListPicYuvRec[layer] ; 
+    m_cListPicYuvRec[layer] = NULL;
   }
 #else
@@ -773,5 +866,5 @@
   m_cTVideoIOYuvInputFile.close();
   m_cTVideoIOYuvReconFile.close();
-  
+
   // Neo Decoder
   m_cTEncTop.destroy();
@@ -781,8 +874,5 @@
 Void TAppEncTop::xInitLib(Bool isFieldCoding)
 {
-#if H_3D
-#endif
-
-#if H_MV
+#if NH_MV
   for(Int layer=0; layer<m_numberOfLayers; layer++)
   {
@@ -794,5 +884,5 @@
   }
 #else
-  m_cTEncTop.init( isFieldCoding );
+  m_cTEncTop.init(isFieldCoding);
 #endif
 }
@@ -819,14 +909,18 @@
   }
 
+#if !NH_3D
   TComPicYuv*       pcPicYuvOrg = new TComPicYuv;
+#endif
   TComPicYuv*       pcPicYuvRec = NULL;
-  
+
   // initialize internal class & member variables
   xInitLibCfg();
   xCreateLib();
   xInitLib(m_isField);
-  
+
+  printChromaFormat();
+
   // main encoder loop
-#if H_MV
+#if NH_MV
   Bool  allEos = false;
   std::vector<Bool>  eos ;
@@ -846,22 +940,42 @@
   Bool  bEos = false;
 #endif
- 
+  const InputColourSpaceConversion ipCSC  =  m_inputColourSpaceConvert;
+  const InputColourSpaceConversion snrCSC = (!m_snrInternalColourSpace) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
+
   list<AccessUnit> outputAccessUnits; ///< list of access units to write out.  is populated by the encoding process
+  
+#if NH_3D
+  TComPicYuv* picYuvOrg[2]; 
+  TComPicYuv  picYuvTrueOrg[2]; 
+  for (Int d = 0; d < 2 ; d++)
+  {
+    picYuvOrg[d] = new TComPicYuv;
+    picYuvOrg[d]   ->create( m_iSourceWidth, m_isField ? m_iSourceHeightOrg : m_iSourceHeight, ( d > 0 ) ? CHROMA_400 : m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+    picYuvTrueOrg[d].create( m_iSourceWidth, m_isField ? m_iSourceHeightOrg : m_iSourceHeight, ( d > 0 ) ? CHROMA_400 : m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+  }
+#else
+  TComPicYuv cPicYuvTrueOrg;
 
   // allocate original YUV buffer
   if( m_isField )
   {
-    pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeightOrg, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+    pcPicYuvOrg->create  ( m_iSourceWidth, m_iSourceHeightOrg, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+    cPicYuvTrueOrg.create(m_iSourceWidth, m_iSourceHeightOrg, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true);
   }
   else
   {
-  pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
-  }
-  
-#if H_MV
+    pcPicYuvOrg->create  ( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+    cPicYuvTrueOrg.create(m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+  }
+#endif
+#if NH_MV
   while ( (m_targetEncLayerIdList.size() != 0 ) && !allEos )
   {
     for(Int layer=0; layer < m_numberOfLayers; layer++ )
     {
+#if NH_3D
+      TComPicYuv* pcPicYuvOrg    =  picYuvOrg    [ m_depthFlag[layer] ];
+      TComPicYuv& cPicYuvTrueOrg =  picYuvTrueOrg[ m_depthFlag[layer] ];
+#endif
       if (!xLayerIdInTargetEncLayerIdList( m_vps->getLayerIdInNuh( layer ) ))
       {
@@ -875,6 +989,6 @@
         xGetBuffer(pcPicYuvRec, layer);
 
-        // read input YUV file
-        m_acTVideoIOYuvInputFileList[layer]->read      ( pcPicYuvOrg, m_aiPad );
+        // read input YUV file        
+        m_acTVideoIOYuvInputFileList[layer]->read      ( pcPicYuvOrg, &cPicYuvTrueOrg, ipCSC, m_aiPad, m_InputChromaFormatIDC );
         m_acTEncTopList             [layer]->initNewPic( pcPicYuvOrg );
 
@@ -899,5 +1013,5 @@
     for ( Int gopId=0; gopId < gopSize; gopId++ )
     {
-#if H_3D
+#if NH_3D
       UInt iNextPoc = m_acTEncTopList[0] -> getFrameId( gopId );
       if ( iNextPoc < m_framesToBeEncoded )
@@ -908,4 +1022,8 @@
       for(Int layer=0; layer < m_numberOfLayers; layer++ )
       {
+#if NH_3D
+        TComPicYuv* pcPicYuvOrg    =  picYuvOrg    [ m_depthFlag[layer] ];
+        TComPicYuv& cPicYuvTrueOrg =  picYuvTrueOrg[ m_depthFlag[layer] ];
+#endif
         if (!xLayerIdInTargetEncLayerIdList( m_vps->getLayerIdInNuh( layer ) ))
         {
@@ -913,5 +1031,5 @@
         }
 
-#if H_3D_VSO        
+#if NH_3D_VSO        
           if( m_bUseVSO && m_bUseEstimatedVSD && iNextPoc < m_framesToBeEncoded )
           {
@@ -923,6 +1041,6 @@
         Int   iNumEncoded = 0;
 
-        // call encoding function for one frame          
-        m_acTEncTopList[layer]->encode( eos[layer], flush[layer] ? 0 : pcPicYuvOrg, *m_picYuvRec[layer], outputAccessUnits, iNumEncoded, gopId );        
+        // call encoding function for one frame                               
+        m_acTEncTopList[layer]->encode( eos[layer], flush[layer] ? 0 : pcPicYuvOrg, flush[layer] ? 0 : &cPicYuvTrueOrg, snrCSC, *m_cListPicYuvRec[layer], outputAccessUnits, iNumEncoded, gopId );        
         xWriteOutput(bitstreamFile, iNumEncoded, outputAccessUnits, layer);
         outputAccessUnits.clear();
@@ -937,8 +1055,9 @@
     {
       continue; 
-    }
-    m_acTEncTopList[layer]->printSummary( m_acTEncTopList[layer]->getNumAllPicCoded(), m_isField );
-  }
-#else
+    }    
+    m_acTEncTopList[layer]->printSummary(m_isField);
+  }
+#else
+
   while ( !bEos )
   {
@@ -947,5 +1066,5 @@
 
     // read input YUV file
-    m_cTVideoIOYuvInputFile.read( pcPicYuvOrg, m_aiPad );
+    m_cTVideoIOYuvInputFile.read( pcPicYuvOrg, &cPicYuvTrueOrg, ipCSC, m_aiPad, m_InputChromaFormatIDC, m_bClipInputVideoToRec709Range );
 
     // increase number of received frames
@@ -967,11 +1086,11 @@
     if ( m_isField )
     {
-      m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, m_cListPicYuvRec, outputAccessUnits, iNumEncoded, m_isTopFieldFirst);
+      m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, flush ? 0 : &cPicYuvTrueOrg, snrCSC, m_cListPicYuvRec, outputAccessUnits, iNumEncoded, m_isTopFieldFirst );
     }
     else
     {
-    m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, m_cListPicYuvRec, outputAccessUnits, iNumEncoded );
-    }
-    
+      m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, flush ? 0 : &cPicYuvTrueOrg, snrCSC, m_cListPicYuvRec, outputAccessUnits, iNumEncoded );
+    }
+
     // write bistream to file if necessary
     if ( iNumEncoded > 0 )
@@ -985,12 +1104,27 @@
 #endif
 
+#if NH_3D
+  // delete original YUV buffer
+  for (Int d = 0; d < 2; d++)
+  {
+    picYuvOrg[d]->destroy();
+    delete picYuvOrg[d];
+    picYuvOrg[d] = NULL;
+
+    picYuvTrueOrg[d].destroy();
+  }
+#else
   // delete original YUV buffer
   pcPicYuvOrg->destroy();
   delete pcPicYuvOrg;
   pcPicYuvOrg = NULL;
-  
-#if !H_MV
+#endif
+
+#if !NH_MV
   // delete used buffers in encoder class
   m_cTEncTop.deletePicBuffer();
+#endif
+#if !NH_3D
+  cPicYuvTrueOrg.destroy();
 #endif
 
@@ -998,5 +1132,5 @@
   xDeleteBuffer();
   xDestroyLib();
-  
+
   printRateSummary();
 
@@ -1023,5 +1157,5 @@
  .
  */
-#if H_MV
+#if NH_MV
 Void TAppEncTop::xGetBuffer( TComPicYuv*& rpcPicYuvRec, UInt layer)
 #else
@@ -1030,26 +1164,28 @@
 {
   assert( m_iGOPSize > 0 );
-  
+
   // org. buffer
-#if H_MV
-  if ( m_picYuvRec[layer]->size() == (UInt)m_iGOPSize )
-  {
-    rpcPicYuvRec = m_picYuvRec[layer]->popFront();
-#else
-  if ( m_cListPicYuvRec.size() == (UInt)m_iGOPSize )
+#if NH_MV
+  if ( m_cListPicYuvRec[layer]->size() == (UInt)m_iGOPSize )
+  {
+    rpcPicYuvRec = m_cListPicYuvRec[layer]->popFront();
+#else
+  if ( m_cListPicYuvRec.size() >= (UInt)m_iGOPSize ) // buffer will be 1 element longer when using field coding, to maintain first field whilst processing second.
   {
     rpcPicYuvRec = m_cListPicYuvRec.popFront();
 #endif
-
   }
   else
   {
     rpcPicYuvRec = new TComPicYuv;
-    
-    rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
-
-  }
-#if H_MV
-  m_picYuvRec[layer]->pushBack( rpcPicYuvRec );
+#if NH_3D
+    rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_depthFlag[layer] > 0 ? CHROMA_400 : m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+#else
+    rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+#endif
+
+  }
+#if NH_MV
+  m_cListPicYuvRec[layer]->pushBack( rpcPicYuvRec );
 #else
   m_cListPicYuvRec.pushBack( rpcPicYuvRec );
@@ -1059,14 +1195,14 @@
 Void TAppEncTop::xDeleteBuffer( )
 {
-#if H_MV
-  for(Int layer=0; layer<m_picYuvRec.size(); layer++)
-  {
-    if(m_picYuvRec[layer])
-    {
-      TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_picYuvRec[layer]->begin();
-      Int iSize = Int( m_picYuvRec[layer]->size() );
+#if NH_MV
+  for(Int layer=0; layer<m_cListPicYuvRec.size(); layer++)
+  {
+    if(m_cListPicYuvRec[layer])
+    {
+      TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_cListPicYuvRec[layer]->begin();
+      Int iSize = Int( m_cListPicYuvRec[layer]->size() );
 #else
   TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_cListPicYuvRec.begin();
-  
+
   Int iSize = Int( m_cListPicYuvRec.size() );
 #endif
@@ -1078,27 +1214,33 @@
     delete pcPicYuvRec; pcPicYuvRec = NULL;
   }
-
-#if H_MV
+#if NH_MV
     }
   }
 #endif  
-}
-
-/** \param iNumEncoded  number of encoded frames
+
+}
+
+/** 
+  Write access units to output file.
+  \param bitstreamFile  target bitstream file
+  \param iNumEncoded    number of encoded frames
+  \param accessUnits    list of access units to be written
  */
-#if H_MV
-Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, std::list<AccessUnit>& accessUnits, UInt layerId)
+#if NH_MV
+Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, std::list<AccessUnit>& accessUnits, UInt layerIdx)
 #else
 Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits)
 #endif
 {
+  const InputColourSpaceConversion ipCSC = (!m_outputInternalColourSpace) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
+
   if (m_isField)
   {
     //Reinterlace fields
     Int i;
-#if H_MV
+#if NH_MV
     if( iNumEncoded > 0 )
     {
-      TComList<TComPicYuv*>::iterator iterPicYuvRec = m_picYuvRec[layerId]->end();
+      TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec[layerIdx]->end();
 #else
     TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
@@ -1116,8 +1258,12 @@
       TComPicYuv*  pcPicYuvRecBottom  = *(iterPicYuvRec++);
 
-#if H_MV
-      if (m_pchReconFileList[layerId])
-      {
-        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRecTop, pcPicYuvRecBottom, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, m_isTopFieldFirst );
+#if NH_MV
+      if (m_pchReconFileList[layerIdx])
+      {
+#if NH_3D
+        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, m_depth420OutputFlag && m_depthFlag[layerIdx ] ? CHROMA_420 : NUM_CHROMA_FORMAT, m_isTopFieldFirst );
+#else
+        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_isTopFieldFirst );
+#endif
       }
     }
@@ -1136,5 +1282,5 @@
       if (m_pchReconFile)
       {
-        m_cTVideoIOYuvReconFile.write( pcPicYuvRecTop, pcPicYuvRecBottom, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, m_isTopFieldFirst );
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_isTopFieldFirst );
       }
 
@@ -1152,8 +1298,8 @@
   {
     Int i;
-#if H_MV
+#if NH_MV
     if( iNumEncoded > 0 )
     {
-      TComList<TComPicYuv*>::iterator iterPicYuvRec = m_picYuvRec[layerId]->end();
+      TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec[layerIdx]->end();
 #else
     TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
@@ -1169,8 +1315,13 @@
     {
       TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
-#if H_MV
-      if (m_pchReconFileList[layerId])
-      {
-        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRec, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+#if NH_MV
+      if (m_pchReconFileList[layerIdx])
+      {
+#if NH_3D
+        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRec, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, m_depth420OutputFlag && m_depthFlag[layerIdx ] ? CHROMA_420 : NUM_CHROMA_FORMAT  );
+#else
+        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRec, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+#endif
+
       }    
     }
@@ -1188,19 +1339,20 @@
       if (m_pchReconFile)
       {
-        m_cTVideoIOYuvReconFile.write( pcPicYuvRec, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRec, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom,
+            NUM_CHROMA_FORMAT, m_bClipOutputVideoToRec709Range  );
       }
 
       const AccessUnit& au = *(iterBitstream++);
       const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
-      rateStatsAccum(au, stats);   
-    }
-#endif
-  }
-}
-  
+      rateStatsAccum(au, stats);
+    }
+#endif
+  }
+}
+
 /**
  *
  */
-void TAppEncTop::rateStatsAccum(const AccessUnit& au, const std::vector<UInt>& annexBsizes)
+Void TAppEncTop::rateStatsAccum(const AccessUnit& au, const std::vector<UInt>& annexBsizes)
 {
   AccessUnit::const_iterator it_au = au.begin();
@@ -1240,7 +1392,7 @@
 }
 
-void TAppEncTop::printRateSummary()
-{
-#if H_MV
+Void TAppEncTop::printRateSummary()
+{
+#if NH_MV
   Double time = (Double) m_frameRcvd[0] / m_iFrameRate;
   printf("\n");
@@ -1249,7 +1401,48 @@
 #endif
   printf("Bytes written to file: %u (%.3f kbps)\n", m_totalBytes, 0.008 * m_totalBytes / time);
-#if VERBOSE_RATE
+  if (m_summaryVerboseness > 0)
+  {
   printf("Bytes for SPS/PPS/Slice (Incl. Annex B): %u (%.3f kbps)\n", m_essentialBytes, 0.008 * m_essentialBytes / time);
-#endif
+  }
+}
+
+Void TAppEncTop::printChromaFormat()
+{
+  std::cout << std::setw(43) << "Input ChromaFormatIDC = ";
+  switch (m_InputChromaFormatIDC)
+  {
+  case CHROMA_400:  std::cout << "  4:0:0"; break;
+  case CHROMA_420:  std::cout << "  4:2:0"; break;
+  case CHROMA_422:  std::cout << "  4:2:2"; break;
+  case CHROMA_444:  std::cout << "  4:4:4"; break;
+  default:
+    std::cerr << "Invalid";
+    exit(1);
+  }
+  std::cout << std::endl;
+
+#if NH_MV
+  for (Int i = 0; i < m_numberOfLayers; i++)
+  {
+    std::cout << "Layer " << i << std::setw( 43 - (i > 9 ? 6 : 7) ) << "Internal ChromaFormatIDC = ";
+    switch (m_acTEncTopList[i]->getChromaFormatIdc())
+#else
+    std::cout << std::setw(43) << "Output (internal) ChromaFormatIDC = ";
+    switch (m_cTEncTop.getChromaFormatIdc())
+#endif
+    {
+    case CHROMA_400:  std::cout << "  4:0:0"; break;
+    case CHROMA_420:  std::cout << "  4:2:0"; break;
+    case CHROMA_422:  std::cout << "  4:2:2"; break;
+    case CHROMA_444:  std::cout << "  4:4:4"; break;
+    default:
+      std::cerr << "Invalid";
+      exit(1);
+    }
+#if NH_MV
+    std::cout << std::endl;
+  }
+#endif
+  std::cout << "\n" << std::endl;
 }
 
@@ -1329,5 +1522,5 @@
 #endif
 
-#if H_MV
+#if NH_MV
 Void TAppEncTop::xSetDimensionIdAndLength( TComVPS& vps )
 {   
@@ -1337,5 +1530,4 @@
     vps.setDimensionIdLen( dim, m_dimensionIdLen[ dim ] );
     for( Int layer = 0; layer <= vps.getMaxLayersMinus1(); layer++ )
-
     {        
       vps.setDimensionId( layer, dim, m_dimIds[ dim ][ layer ] );        
@@ -1358,5 +1550,5 @@
 
 
-#if H_3D
+#if NH_3D
   vps.initViewCompLayer( ); 
 #endif
@@ -1437,5 +1629,5 @@
       Int curLayerIdInNuh = vps.getLayerIdInNuh( curLayerIdInVps );      
       Int maxTid = -1; 
-#if H_3D
+#if NH_3D
       if ( vps.getDirectDependencyFlag( curLayerIdInVps, refLayerIdInVps ) )
       {
@@ -1449,5 +1641,5 @@
             for (Int j = 0; j < geCur.m_numActiveRefLayerPics; j++)
             {
-#if H_3D
+#if NH_3D
               if ( vps.getIdRefListLayer( curLayerIdInNuh, geCur.m_interLayerPredLayerIdc[ j ] ) == refLayerIdInNuh )
 #else
@@ -1460,5 +1652,5 @@
             }
           }              
-#if H_3D
+#if NH_3D
         }
         else
@@ -1554,5 +1746,5 @@
       
       // check if all reference layers when allRefLayerActiveFlag is equal to 1 are reference layer pictures specified in the gop entry
-#if H_3D
+#if NH_3D
       for (Int k = 0; k < vps.getNumRefListLayers( layerIdInNuh ) && allRefLayersActiveFlag; k++ )
       {
@@ -1580,5 +1772,5 @@
       {   
         Bool referenceLayerFoundFlag = false; 
-#if H_3D
+#if NH_3D
         for (Int k = 0; k < vps.getNumRefListLayers( layerIdInNuh ); k++ )
         {
@@ -1619,12 +1811,34 @@
 }
 
+
+Void TAppEncTop::xSetTimingInfo( TComVPS& vps )
+{
+  vps.getTimingInfo()->setTimingInfoPresentFlag( false );
+}
+
+Void TAppEncTop::xSetHrdParameters( TComVPS& vps )
+{
+  vps.createHrdParamBuffer();
+  for( Int i = 0; i < vps.getNumHrdParameters(); i++ )
+  {
+    vps.setHrdOpSetIdx( 0, i );
+    vps.setCprmsPresentFlag( false, i );
+  }
+}
+
 Void TAppEncTop::xSetLayerIds( TComVPS& vps )
 {
   vps.setSplittingFlag     ( m_splittingFlag );
 
-  Bool nuhLayerIdPresentFlag = !( m_layerIdInNuh.size() == 1 ); 
-  Int  maxNuhLayerId = nuhLayerIdPresentFlag ? xGetMax( m_layerIdInNuh ) : ( m_numberOfLayers - 1 ) ; 
-
-  vps.setVpsMaxLayerId( maxNuhLayerId ); 
+  Bool nuhLayerIdPresentFlag = false; 
+  
+
+  vps.setVpsMaxLayerId( xGetMax( m_layerIdInNuh ) ); 
+
+  for (Int i = 0; i < m_numberOfLayers; i++)
+  {
+    nuhLayerIdPresentFlag = nuhLayerIdPresentFlag || ( m_layerIdInNuh[i] != i ); 
+  }
+
   vps.setVpsNuhLayerIdPresentFlag( nuhLayerIdPresentFlag ); 
 
@@ -1650,16 +1864,16 @@
 
   // SET PTL
-  assert( m_profile.size() == m_level.size() && m_profile.size() == m_levelTier.size() ); 
-  vps.setVpsNumProfileTierLevelMinus1( (Int) m_profile.size() - 1 );
+  assert( m_profiles.size() == m_level.size() && m_profiles.size() == m_levelTier.size() ); 
+  vps.setVpsNumProfileTierLevelMinus1( (Int) m_profiles.size() - 1 );
   for ( Int ptlIdx = 0; ptlIdx <= vps.getVpsNumProfileTierLevelMinus1(); ptlIdx++ )
   {
     if ( ptlIdx > 1 )
     {
-      Bool vpsProfilePresentFlag = ( m_profile[ptlIdx] != m_profile[ptlIdx - 1] )
+      Bool vpsProfilePresentFlag = ( m_profiles[ptlIdx] != m_profiles[ptlIdx - 1] )
         || ( m_inblFlag[ptlIdx ] != m_inblFlag[ptlIdx - 1] ); 
       vps.setVpsProfilePresentFlag( ptlIdx, vpsProfilePresentFlag ); 
     }
 
-    xSetProfileTierLevel( vps, ptlIdx, -1, m_profile[ptlIdx], m_level[ptlIdx], 
+    xSetProfileTierLevel( vps, ptlIdx, -1, m_profiles[ptlIdx], m_level[ptlIdx], 
       m_levelTier[ ptlIdx ], m_progressiveSourceFlag, m_interlacedSourceFlag,
       m_nonPackedConstraintFlag, m_frameOnlyConstraintFlag,  m_inblFlag[ptlIdx] );     
@@ -1695,5 +1909,5 @@
     break; 
   case Profile::MULTIVIEWMAIN:
-#if H_3D
+#if NH_3D
   case Profile::MAIN3D:
 #endif
@@ -1718,64 +1932,39 @@
 {
 
-#if H_3D_DISABLE_CHROMA
   Bool anyDepth = false; 
+#if NH_3D
   for ( Int i = 0; i < m_numberOfLayers; i++ )
   {
     vps.setVpsRepFormatIdx( i, m_depthFlag[ i ] ? 1 : 0 );
-    anyDepth = anyDepth || m_depthFlag[ i ]; 
-  }  
+    anyDepth = anyDepth || m_depthFlag[ i ];
+  }
+#endif
 
   vps.setRepFormatIdxPresentFlag( anyDepth ); 
-  vps.setVpsNumRepFormatsMinus1 ( anyDepth ? 1 : 0  ); 
-
+  vps.setVpsNumRepFormatsMinus1 ( anyDepth ? 1 : 0     ); 
+
+
+  std::vector<TComRepFormat> repFormat;
+  repFormat.resize( vps.getVpsNumRepFormatsMinus1() + 1 ); 
   for ( Int j = 0; j <= vps.getVpsNumRepFormatsMinus1(); j++ )
-  {
-    TComRepFormat* repFormat = new TComRepFormat; 
-
-    repFormat->setBitDepthVpsChromaMinus8   ( g_bitDepthC - 8 ); 
-    repFormat->setBitDepthVpsLumaMinus8     ( g_bitDepthY - 8 );
-    repFormat->setChromaFormatVpsIdc        ( j == 1 ? CHROMA_400 : CHROMA_420 );
-    repFormat->setPicHeightVpsInLumaSamples ( m_iSourceHeight );
-    repFormat->setPicWidthVpsInLumaSamples  ( m_iSourceWidth  );    
-    repFormat->setChromaAndBitDepthVpsPresentFlag( true );    
+  {           
+    repFormat[j].setBitDepthVpsChromaMinus8   ( m_internalBitDepth[CHANNEL_TYPE_LUMA  ] - 8 ); 
+    repFormat[j].setBitDepthVpsLumaMinus8     ( m_internalBitDepth[CHANNEL_TYPE_CHROMA] - 8 );
+    repFormat[j].setChromaFormatVpsIdc        ( j == 1 ? CHROMA_400 :  CHROMA_420 );
+    repFormat[j].setPicHeightVpsInLumaSamples ( m_iSourceHeight );
+    repFormat[j].setPicWidthVpsInLumaSamples  ( m_iSourceWidth  );    
+    repFormat[j].setChromaAndBitDepthVpsPresentFlag( true );    
     // ToDo not supported yet. 
     //repFormat->setSeparateColourPlaneVpsFlag( );
-    Bool conformanceWindowVpsFlag = ( m_confWinBottom != 0 ) || ( m_confWinRight != 0 ) || ( m_confWinTop != 0 ) || ( m_confWinBottom != 0 ); 
-    repFormat->setConformanceWindowVpsFlag( conformanceWindowVpsFlag );
-    if ( conformanceWindowVpsFlag ) 
-    {   
-      repFormat->setConfWinVpsLeftOffset    ( m_confWinLeft   / TComSPS::getWinUnitX( repFormat->getChromaFormatVpsIdc() ) );
-      repFormat->setConfWinVpsRightOffset   ( m_confWinRight  / TComSPS::getWinUnitX( repFormat->getChromaFormatVpsIdc() )  );
-      repFormat->setConfWinVpsTopOffset     ( m_confWinTop    / TComSPS::getWinUnitY( repFormat->getChromaFormatVpsIdc() )  );
-      repFormat->setConfWinVpsBottomOffset  ( m_confWinBottom / TComSPS::getWinUnitY( repFormat->getChromaFormatVpsIdc() ) ); 
-    }
-    assert( vps.getRepFormat( j ) == NULL ); 
-    vps.setRepFormat( j , repFormat );
-  }; 
-
-
-#else
-  vps.setRepFormatIdxPresentFlag( false ); 
-  vps.setVpsNumRepFormatsMinus1 ( 0    ); 
-
-  TComRepFormat* repFormat = new TComRepFormat; 
-
-  repFormat->setBitDepthVpsChromaMinus8   ( g_bitDepthC - 8 ); 
-  repFormat->setBitDepthVpsLumaMinus8     ( g_bitDepthY - 8 );
-  repFormat->setChromaFormatVpsIdc        ( CHROMA_420      );
-  repFormat->setPicHeightVpsInLumaSamples ( m_iSourceHeight );
-  repFormat->setPicWidthVpsInLumaSamples  ( m_iSourceWidth  );    
-  repFormat->setChromaAndBitDepthVpsPresentFlag( true );    
-  // ToDo not supported yet. 
-  //repFormat->setSeparateColourPlaneVpsFlag( );
-
-  repFormat->setConformanceWindowVpsFlag( true );
-  repFormat->setConfWinVpsLeftOffset    ( m_confWinLeft   / TComSPS::getWinUnitX( repFormat->getChromaFormatVpsIdc() ) );
-  repFormat->setConfWinVpsRightOffset   ( m_confWinRight  / TComSPS::getWinUnitX( repFormat->getChromaFormatVpsIdc() )  );
-  repFormat->setConfWinVpsTopOffset     ( m_confWinTop    / TComSPS::getWinUnitY( repFormat->getChromaFormatVpsIdc() )  );
-  repFormat->setConfWinVpsBottomOffset  ( m_confWinBottom / TComSPS::getWinUnitY( repFormat->getChromaFormatVpsIdc() ) ); 
-  assert( vps.getRepFormat( 0 ) == NULL ); 
-  vps.setRepFormat( 0 , repFormat );
-#endif
+
+    repFormat[j].setConformanceWindowVpsFlag( true );
+    repFormat[j].setConfWinVpsLeftOffset    ( m_confWinLeft   / TComSPS::getWinUnitX( repFormat[j].getChromaFormatVpsIdc() ) );
+    repFormat[j].setConfWinVpsRightOffset   ( m_confWinRight  / TComSPS::getWinUnitX( repFormat[j].getChromaFormatVpsIdc() )  );
+    repFormat[j].setConfWinVpsTopOffset     ( m_confWinTop    / TComSPS::getWinUnitY( repFormat[j].getChromaFormatVpsIdc() )  );
+    repFormat[j].setConfWinVpsBottomOffset  ( m_confWinBottom / TComSPS::getWinUnitY( repFormat[j].getChromaFormatVpsIdc() ) ); 
+  }
+
+  vps.setRepFormat( repFormat );
+
 }
 
@@ -1784,7 +1973,7 @@
   // These settings need to be verified
 
-  TComDpbSize* dpbSize = vps.getDpbSize(); 
-
-  assert ( dpbSize != 0 ); 
+  TComDpbSize dpbSize;   
+  dpbSize.init( vps.getNumOutputLayerSets(), vps.getVpsMaxLayerId() + 1, vps.getMaxSubLayersMinus1() + 1 ) ;
+  
 
   for( Int i = 0; i < vps.getNumOutputLayerSets(); i++ )
@@ -1801,8 +1990,8 @@
         if ( vps.getNecessaryLayerFlag( i,k ) && ( vps.getVpsBaseLayerInternalFlag() || vps.getLayerSetLayerIdList( currLsIdx, k ) != 0 ) )
         {       
-          dpbSize->setMaxVpsDecPicBufferingMinus1( i, k, j, m_maxDecPicBufferingMvc[ layerIdInVps ][ j ] - 1 );
+          dpbSize.setMaxVpsDecPicBufferingMinus1( i, k, j, m_maxDecPicBufferingMvc[ layerIdInVps ][ j ] - 1 );
           if ( j > 0 )
           {
-            subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize->getMaxVpsDecPicBufferingMinus1( i, k, j ) != dpbSize->getMaxVpsDecPicBufferingMinus1( i, k, j - 1 ) );
+            subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize.getMaxVpsDecPicBufferingMinus1( i, k, j ) != dpbSize.getMaxVpsDecPicBufferingMinus1( i, k, j - 1 ) );
           }
         }
@@ -1811,5 +2000,5 @@
           if (vps.getNecessaryLayerFlag(i,k) && j == 0 && k == 0 )
           {          
-            dpbSize->setMaxVpsDecPicBufferingMinus1(i, k ,j, 0 ); 
+            dpbSize.setMaxVpsDecPicBufferingMinus1(i, k ,j, 0 ); 
           }
         }
@@ -1827,25 +2016,26 @@
       assert( maxNumReorderPics != MIN_INT ); 
 
-      dpbSize->setMaxVpsNumReorderPics( i, j, maxNumReorderPics );
+      dpbSize.setMaxVpsNumReorderPics( i, j, maxNumReorderPics );
       if ( j > 0 )
       {
-        subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize->getMaxVpsNumReorderPics( i, j ) != dpbSize->getMaxVpsNumReorderPics( i, j - 1 ) );
+        subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize.getMaxVpsNumReorderPics( i, j ) != dpbSize.getMaxVpsNumReorderPics( i, j - 1 ) );
       }
 
       // To Be Done !
-      // dpbSize->setMaxVpsLatencyIncreasePlus1( i, j, xx );
+      // dpbSize.setMaxVpsLatencyIncreasePlus1( i, j, xx );
       if ( j > 0 )
       {
-        subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize->getMaxVpsLatencyIncreasePlus1( i, j ) != dpbSize->getMaxVpsLatencyIncreasePlus1( i, j - 1  ) );
+        subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize.getMaxVpsLatencyIncreasePlus1( i, j ) != dpbSize.getMaxVpsLatencyIncreasePlus1( i, j - 1  ) );
       }
 
       if( j > 0 )  
       {
-        dpbSize->setSubLayerDpbInfoPresentFlag( i, j, subLayerDpbInfoPresentFlag );
+        dpbSize.setSubLayerDpbInfoPresentFlag( i, j, subLayerDpbInfoPresentFlag );
         subLayerFlagInfoPresentFlag = subLayerFlagInfoPresentFlag || subLayerDpbInfoPresentFlag; 
       }       
     }  
-    dpbSize->setSubLayerFlagInfoPresentFlag( i, subLayerFlagInfoPresentFlag ); 
+    dpbSize.setSubLayerFlagInfoPresentFlag( i, subLayerFlagInfoPresentFlag ); 
   }  
+  vps.setDpbSize( dpbSize ); 
 }
 
@@ -2010,6 +2200,6 @@
   vps.setVpsVuiPresentFlag( m_vpsVuiPresentFlag ); 
 
-  TComVPSVUI* pcVPSVUI = vps.getVPSVUI(  ); 
-  assert( pcVPSVUI ); 
+  TComVPSVUI vpsVui;
+  vpsVui.init(vps.getNumAddLayerSets(),vps.getMaxSubLayersMinus1() + 1, vps.getMaxLayersMinus1() + 1 );
 
   if ( m_vpsVuiPresentFlag )
@@ -2018,11 +2208,11 @@
     // however preliminary setting it from input parameters
 
-    pcVPSVUI->setCrossLayerPicTypeAlignedFlag( m_crossLayerPicTypeAlignedFlag );
-    pcVPSVUI->setCrossLayerIrapAlignedFlag   ( m_crossLayerIrapAlignedFlag    );
-    pcVPSVUI->setAllLayersIdrAlignedFlag     ( m_allLayersIdrAlignedFlag      );
-    pcVPSVUI->setBitRatePresentVpsFlag( m_bitRatePresentVpsFlag );
-    pcVPSVUI->setPicRatePresentVpsFlag( m_picRatePresentVpsFlag );
-
-    if( pcVPSVUI->getBitRatePresentVpsFlag( )  ||  pcVPSVUI->getPicRatePresentVpsFlag( ) )
+    vpsVui.setCrossLayerPicTypeAlignedFlag( m_crossLayerPicTypeAlignedFlag );
+    vpsVui.setCrossLayerIrapAlignedFlag   ( m_crossLayerIrapAlignedFlag    );
+    vpsVui.setAllLayersIdrAlignedFlag     ( m_allLayersIdrAlignedFlag      );
+    vpsVui.setBitRatePresentVpsFlag( m_bitRatePresentVpsFlag );
+    vpsVui.setPicRatePresentVpsFlag( m_picRatePresentVpsFlag );
+
+    if( vpsVui.getBitRatePresentVpsFlag( )  ||  vpsVui.getPicRatePresentVpsFlag( ) )
     {
       for( Int i = 0; i  <  vps.getNumLayerSets(); i++ )
@@ -2030,27 +2220,27 @@
         for( Int j = 0; j  <=  vps.getMaxTLayers(); j++ ) 
         {
-          if( pcVPSVUI->getBitRatePresentVpsFlag( ) && m_bitRatePresentFlag[i].size() > j )
+          if( vpsVui.getBitRatePresentVpsFlag( ) && m_bitRatePresentFlag[i].size() > j )
           {
-            pcVPSVUI->setBitRatePresentFlag( i, j, m_bitRatePresentFlag[i][j] );            
+            vpsVui.setBitRatePresentFlag( i, j, m_bitRatePresentFlag[i][j] );            
           }
-          if( pcVPSVUI->getPicRatePresentVpsFlag( ) && m_picRatePresentFlag[i].size() > j   )
+          if( vpsVui.getPicRatePresentVpsFlag( ) && m_picRatePresentFlag[i].size() > j   )
           {
-            pcVPSVUI->setPicRatePresentFlag( i, j, m_picRatePresentFlag[i][j] );
+            vpsVui.setPicRatePresentFlag( i, j, m_picRatePresentFlag[i][j] );
           }
-          if( pcVPSVUI->getBitRatePresentFlag( i, j )  && m_avgBitRate[i].size() > j )
+          if( vpsVui.getBitRatePresentFlag( i, j )  && m_avgBitRate[i].size() > j )
           {
-            pcVPSVUI->setAvgBitRate( i, j, m_avgBitRate[i][j] );          
+            vpsVui.setAvgBitRate( i, j, m_avgBitRate[i][j] );          
           }
-          if( pcVPSVUI->getBitRatePresentFlag( i, j )  && m_maxBitRate[i].size() > j )
+          if( vpsVui.getBitRatePresentFlag( i, j )  && m_maxBitRate[i].size() > j )
           {
-            pcVPSVUI->setMaxBitRate( i, j, m_maxBitRate[i][j] );
+            vpsVui.setMaxBitRate( i, j, m_maxBitRate[i][j] );
           }
-          if( pcVPSVUI->getPicRatePresentFlag( i, j ) && m_constantPicRateIdc[i].size() > j )
+          if( vpsVui.getPicRatePresentFlag( i, j ) && m_constantPicRateIdc[i].size() > j )
           {
-            pcVPSVUI->setConstantPicRateIdc( i, j, m_constantPicRateIdc[i][j] );
+            vpsVui.setConstantPicRateIdc( i, j, m_constantPicRateIdc[i][j] );
           }
-          if( pcVPSVUI->getPicRatePresentFlag( i, j ) && m_avgPicRate[i].size() > j )
+          if( vpsVui.getPicRatePresentFlag( i, j ) && m_avgPicRate[i].size() > j )
           {
-            pcVPSVUI->setAvgPicRate( i, j, m_avgPicRate[i][j] );
+            vpsVui.setAvgPicRate( i, j, m_avgPicRate[i][j] );
           }
         }
@@ -2058,14 +2248,14 @@
     }
 
-    pcVPSVUI->setTilesNotInUseFlag( m_tilesNotInUseFlag );
-
-    if( !pcVPSVUI->getTilesNotInUseFlag() ) 
+    vpsVui.setTilesNotInUseFlag( m_tilesNotInUseFlag );
+
+    if( !vpsVui.getTilesNotInUseFlag() ) 
     {      
       for( Int i = 0; i  <=  vps.getMaxLayersMinus1(); i++ )
       {
-        pcVPSVUI->setTilesInUseFlag( i, m_tilesInUseFlag[ i ] );
-        if( pcVPSVUI->getTilesInUseFlag( i ) )  
+        vpsVui.setTilesInUseFlag( i, m_tilesInUseFlag[ i ] );
+        if( vpsVui.getTilesInUseFlag( i ) )  
         {
-          pcVPSVUI->setLoopFilterNotAcrossTilesFlag( i, m_loopFilterNotAcrossTilesFlag[ i ] );
+          vpsVui.setLoopFilterNotAcrossTilesFlag( i, m_loopFilterNotAcrossTilesFlag[ i ] );
         }
       }  
@@ -2076,7 +2266,7 @@
         {  
           Int layerIdx = vps.getLayerIdInVps( vps.getIdDirectRefLayer(vps.getLayerIdInNuh( i ) , j  ));  
-          if( pcVPSVUI->getTilesInUseFlag( i )  &&  pcVPSVUI->getTilesInUseFlag( layerIdx ) )  
+          if( vpsVui.getTilesInUseFlag( i )  &&  vpsVui.getTilesInUseFlag( layerIdx ) )  
           {
-            pcVPSVUI->setTileBoundariesAlignedFlag( i, j, m_tileBoundariesAlignedFlag[i][j] );
+            vpsVui.setTileBoundariesAlignedFlag( i, j, m_tileBoundariesAlignedFlag[i][j] );
           }
         }  
@@ -2084,20 +2274,20 @@
     }  
 
-    pcVPSVUI->setWppNotInUseFlag( m_wppNotInUseFlag );
-
-    if( !pcVPSVUI->getWppNotInUseFlag( ) )
+    vpsVui.setWppNotInUseFlag( m_wppNotInUseFlag );
+
+    if( !vpsVui.getWppNotInUseFlag( ) )
     {
       for( Int i = 1; i  <=  vps.getMaxLayersMinus1(); i++ )  
       {
-        pcVPSVUI->setWppInUseFlag( i, m_wppInUseFlag[ i ]);
-      }
-    }
-
-  pcVPSVUI->setSingleLayerForNonIrapFlag( m_singleLayerForNonIrapFlag );
-  pcVPSVUI->setHigherLayerIrapSkipFlag( m_higherLayerIrapSkipFlag );
-
-    pcVPSVUI->setIlpRestrictedRefLayersFlag( m_ilpRestrictedRefLayersFlag );
-
-    if( pcVPSVUI->getIlpRestrictedRefLayersFlag( ) )
+        vpsVui.setWppInUseFlag( i, m_wppInUseFlag[ i ]);
+      }
+    }
+
+  vpsVui.setSingleLayerForNonIrapFlag( m_singleLayerForNonIrapFlag );
+  vpsVui.setHigherLayerIrapSkipFlag( m_higherLayerIrapSkipFlag );
+
+    vpsVui.setIlpRestrictedRefLayersFlag( m_ilpRestrictedRefLayersFlag );
+
+    if( vpsVui.getIlpRestrictedRefLayersFlag( ) )
     {
       for( Int i = 1; i  <=  vps.getMaxLayersMinus1(); i++ )
@@ -2107,17 +2297,17 @@
           if ( m_minSpatialSegmentOffsetPlus1[i].size() > j )
           {        
-            pcVPSVUI->setMinSpatialSegmentOffsetPlus1( i, j, m_minSpatialSegmentOffsetPlus1[i][j] );
+            vpsVui.setMinSpatialSegmentOffsetPlus1( i, j, m_minSpatialSegmentOffsetPlus1[i][j] );
           }
-          if( pcVPSVUI->getMinSpatialSegmentOffsetPlus1( i, j ) > 0 )
+          if( vpsVui.getMinSpatialSegmentOffsetPlus1( i, j ) > 0 )
           {
             if ( m_ctuBasedOffsetEnabledFlag[i].size() > j )
             {        
-              pcVPSVUI->setCtuBasedOffsetEnabledFlag( i, j, m_ctuBasedOffsetEnabledFlag[i][j] );
+              vpsVui.setCtuBasedOffsetEnabledFlag( i, j, m_ctuBasedOffsetEnabledFlag[i][j] );
             }
-            if( pcVPSVUI->getCtuBasedOffsetEnabledFlag( i, j ) )
+            if( vpsVui.getCtuBasedOffsetEnabledFlag( i, j ) )
             {
               if ( m_minHorizontalCtuOffsetPlus1[i].size() > j )
               {
-                pcVPSVUI->setMinHorizontalCtuOffsetPlus1( i, j, m_minHorizontalCtuOffsetPlus1[i][j] );
+                vpsVui.setMinHorizontalCtuOffsetPlus1( i, j, m_minHorizontalCtuOffsetPlus1[i][j] );
               }
             }
@@ -2126,32 +2316,33 @@
       }
     }      
-    pcVPSVUI->setVideoSignalInfoIdxPresentFlag( true ); 
-    pcVPSVUI->setVpsNumVideoSignalInfoMinus1  ( 0    ); 
-
-    assert ( pcVPSVUI->getVideoSignalInfo( 0 ) == NULL );
-
-    TComVideoSignalInfo* videoSignalInfo = new TComVideoSignalInfo; 
-
-    videoSignalInfo->setColourPrimariesVps        ( m_colourPrimaries ); 
-    videoSignalInfo->setMatrixCoeffsVps           ( m_matrixCoefficients ); 
-    videoSignalInfo->setTransferCharacteristicsVps( m_transferCharacteristics ); 
-    videoSignalInfo->setVideoVpsFormat            ( m_videoFormat ); 
-    videoSignalInfo->setVideoFullRangeVpsFlag     ( m_videoFullRangeFlag );  
-
-    pcVPSVUI->setVideoSignalInfo( 0, videoSignalInfo );       
+    vpsVui.setVideoSignalInfoIdxPresentFlag( true ); 
+    vpsVui.setVpsNumVideoSignalInfoMinus1  ( 0    );     
+
+    std::vector<TComVideoSignalInfo> videoSignalInfos;
+    videoSignalInfos.resize( vpsVui.getVpsNumVideoSignalInfoMinus1() + 1 );
+
+    videoSignalInfos[0].setColourPrimariesVps        ( m_colourPrimaries ); 
+    videoSignalInfos[0].setMatrixCoeffsVps           ( m_matrixCoefficients ); 
+    videoSignalInfos[0].setTransferCharacteristicsVps( m_transferCharacteristics ); 
+    videoSignalInfos[0].setVideoVpsFormat            ( m_videoFormat ); 
+    videoSignalInfos[0].setVideoFullRangeVpsFlag     ( m_videoFullRangeFlag );  
+
+    vpsVui.setVideoSignalInfo( videoSignalInfos );       
 
     for (Int i = 0; i < m_numberOfLayers; i++)
     {      
-      pcVPSVUI->setVpsVideoSignalInfoIdx( i, 0 ); 
-    }
-    pcVPSVUI->setVpsVuiBspHrdPresentFlag( false ); // TBD
+      vpsVui.setVpsVideoSignalInfoIdx( i, 0 ); 
+    }
+    vpsVui.setVpsVuiBspHrdPresentFlag( false ); // TBD
   }
   else
   {
-    pcVPSVUI->setCrossLayerIrapAlignedFlag   ( false   );
-  }
-}
-
-#if H_3D
+    //Default inference when not present.
+    vpsVui.setCrossLayerIrapAlignedFlag   ( false   );
+  }
+  vps.setVPSVUI( vpsVui ); 
+}
+
+#if NH_3D
 Void TAppEncTop::xSetCamPara                ( TComVPS& vps )
 {
Index: branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncTop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppEncoder/TAppEncTop.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,5 +46,5 @@
 #include "TLibCommon/AccessUnit.h"
 #include "TAppEncCfg.h"
-#if H_3D
+#if NH_3D
 #include "../../Lib/TLibRenderer/TRenTop.h"
 #endif
@@ -65,15 +65,15 @@
 private:
   // class interface
-#if H_MV
+#if NH_MV
   std::vector<TEncTop*>      m_acTEncTopList ;              ///< encoder class per layer 
   std::vector<TVideoIOYuv*>  m_acTVideoIOYuvInputFileList;  ///< input YUV file
   std::vector<TVideoIOYuv*>  m_acTVideoIOYuvReconFileList;  ///< output reconstruction file
   
-  std::vector<TComList<TComPicYuv*>*>  m_picYuvRec;         ///< list of reconstruction YUV files
+  std::vector<TComList<TComPicYuv*>*>  m_cListPicYuvRec;         ///< list of reconstruction YUV files
 
   std::vector<Int>           m_frameRcvd;                   ///< number of received frames 
 
   TComPicLists               m_ivPicLists;                  ///< picture buffers of encoder instances
-#if H_MV
+#if NH_MV
   TComVPS*                   m_vps;                         ///< vps
 #else
@@ -84,7 +84,7 @@
   TVideoIOYuv                m_cTVideoIOYuvInputFile;       ///< input YUV file
   TVideoIOYuv                m_cTVideoIOYuvReconFile;       ///< output reconstruction file
-  
+
   TComList<TComPicYuv*>      m_cListPicYuvRec;              ///< list of reconstruction YUV files
-  
+
   Int                        m_iFrameRcvd;                  ///< number of received frames
 #endif
@@ -92,4 +92,6 @@
 #if H_3D
   TComDLT                    m_dlt;                         ///< dlt
+#endif
+#if NH_3D
   TComSps3dExtension         m_sps3dExtension;              ///< Currently all layers share the same sps 3D Extension  
 #endif
@@ -97,5 +99,5 @@
   UInt m_essentialBytes;
   UInt m_totalBytes;
-#if H_3D_VSO
+#if NH_3D_VSO
   TRenTop                     m_cRendererTop; 
   TRenModel                   m_cRendererModel;   
@@ -107,7 +109,7 @@
   Void  xInitLib          (Bool isFieldCoding);             ///< initialize encoder class
   Void  xDestroyLib       ();                               ///< destroy encoder class
-  
+
   /// obtain required buffers
-#if H_MV
+#if NH_MV
   Void  xGetBuffer(TComPicYuv*& rpcPicYuvRec, UInt layer);
 #else
@@ -117,15 +119,18 @@
   /// delete allocated buffers
   Void  xDeleteBuffer     ();
-  
+
   // file I/O
-#if H_MV
+#if NH_MV
   Void xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, std::list<AccessUnit>& accessUnits, UInt layerId); ///< write bitstream to file
 #else
   Void xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits); ///< write bitstream to file
 #endif
-  void rateStatsAccum(const AccessUnit& au, const std::vector<UInt>& stats);
-  void printRateSummary();
+  Void rateStatsAccum(const AccessUnit& au, const std::vector<UInt>& stats);
+  Void printRateSummary();
+  Void printChromaFormat();
 
-#if H_MV
+#if NH_MV
+  Void xSetTimingInfo             ( TComVPS& vps );
+  Void xSetHrdParameters          ( TComVPS& vps );
   Void xSetLayerIds               ( TComVPS& vps );  
   Void xSetDimensionIdAndLength   ( TComVPS& vps );
@@ -134,13 +139,13 @@
   Void xSetProfileTierLevel       ( TComVPS& vps );
 
-  Void xSetProfileTierLevel( TComVPS& vps, Int profileTierLevelIdx, Int subLayer,                              
-                             Profile::Name profile, Level::Name level, Level::Tier tier, 
-                             Bool progressiveSourceFlag, Bool interlacedSourceFlag, 
-                             Bool nonPackedConstraintFlag, Bool frameOnlyConstraintFlag, 
-                             Bool inbldFlag );
+  Void xSetProfileTierLevel       ( TComVPS& vps, Int profileTierLevelIdx, Int subLayer,                              
+                                    Profile::Name profile, Level::Name level, Level::Tier tier, 
+                                    Bool progressiveSourceFlag, Bool interlacedSourceFlag, 
+                                    Bool nonPackedConstraintFlag, Bool frameOnlyConstraintFlag, 
+                                    Bool inbldFlag );
   Void xSetRepFormat              ( TComVPS& vps );
   Void xSetDpbSize                ( TComVPS& vps );
   Void xSetVPSVUI                 ( TComVPS& vps );
-#if H_3D
+#if NH_3D
   Void xSetCamPara                ( TComVPS& vps );
 #endif
@@ -155,10 +160,11 @@
   Void  xAnalyzeInputBaseDepth(UInt layer, UInt uiNumFrames, TComVPS* vps, TComDLT* dlt);
 #endif
+
 public:
   TAppEncTop();
   virtual ~TAppEncTop();
-  
+
   Void        encode      ();                               ///< main encoding function
-#if H_MV
+#if NH_MV
   TEncTop*    getTEncTop( UInt layer ) { return  m_acTEncTopList[layer]; }  ///< return pointer to encoder class for specific layer
 #else
Index: branches/HTM-14.1-update-dev0/source/App/TAppEncoder/encmain.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppEncoder/encmain.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppEncoder/encmain.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -41,9 +41,8 @@
 #include "TAppCommon/program_options_lite.h"
 
-using namespace std;
-namespace po = df::program_options_lite;
-
 //! \ingroup TAppEncoder
 //! \{
+
+#include "../Lib/TLibCommon/Debug.h"
 
 // ====================================================================================================================
@@ -57,13 +56,13 @@
   // print information
   fprintf( stdout, "\n" );
-#if H_MV
+#if NH_MV
   fprintf( stdout, "3D-HTM Software: Encoder Version [%s] based on HM Version [%s]", NV_VERSION, HM_VERSION );  
 #else
-  fprintf( stdout, "HM software: Encoder Version [%s]", NV_VERSION );
+  fprintf( stdout, "HM software: Encoder Version [%s] (including RExt)", NV_VERSION );
 #endif
   fprintf( stdout, NVM_ONOS );
   fprintf( stdout, NVM_COMPILEDBY );
   fprintf( stdout, NVM_BITS );
-  fprintf( stdout, "\n" );
+  fprintf( stdout, "\n\n" );
 
   // create application encoder class
@@ -76,16 +75,27 @@
     {
       cTAppEncTop.destroy();
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      EnvVar::printEnvVar();
+#endif
       return 1;
     }
   }
-  catch (po::ParseFailure& e)
+  catch (df::program_options_lite::ParseFailure &e)
   {
-    cerr << "Error parsing option \""<< e.arg <<"\" with argument \""<< e.val <<"\"." << endl;
+    std::cerr << "Error parsing option \""<< e.arg <<"\" with argument \""<< e.val <<"\"." << std::endl;
     return 1;
   }
 
+#if PRINT_MACRO_VALUES
+  printMacroSettings();
+#endif
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  EnvVar::printEnvVarInUse();
+#endif
+
   // starting time
-  double dResult;
-  long lBefore = clock();
+  Double dResult;
+  clock_t lBefore = clock();
 
   // call encoding function
@@ -93,5 +103,5 @@
 
   // ending time
-  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  dResult = (Double)(clock()-lBefore) / CLOCKS_PER_SEC;
   printf("\n Total Time: %12.3f sec.\n", dResult);
 
Index: branches/HTM-14.1-update-dev0/source/App/TAppExtractor/TAppExtrTop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppExtractor/TAppExtrTop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppExtractor/TAppExtrTop.cpp	(revision 1200)
@@ -42,5 +42,5 @@
 #include <assert.h>
 
-#if H_MV
+#if NH_MV
 // ====================================================================================================================
 // Constructor / destructor / initialization / destroy
@@ -49,7 +49,5 @@
 TAppExtrTop::TAppExtrTop()
 {
-  // To suppress compiler warnings on potential division by 0. 
-  g_uiMaxCUWidth  = 1;
-  g_uiMaxCUHeight = 1;
+
 }
 
@@ -110,5 +108,5 @@
     else
     {
-      read( nalu, nalUnit );
+      read( nalu );
 
       // decide whether to extract packet or not
Index: branches/HTM-14.1-update-dev0/source/App/TAppExtractor/TAppExtrTop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppExtractor/TAppExtrTop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppExtractor/TAppExtrTop.h	(revision 1200)
@@ -46,5 +46,5 @@
 #include "TAppExtrCfg.h"
 
-#if H_MV
+#if NH_MV
 // ====================================================================================================================
 // Class definition
Index: branches/HTM-14.1-update-dev0/source/App/TAppExtractor/extrmain.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppExtractor/extrmain.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppExtractor/extrmain.cpp	(revision 1200)
@@ -41,5 +41,5 @@
 #include "TAppExtrTop.h"
 
-#if H_MV
+#if NH_MV
 // ====================================================================================================================
 // Main function
@@ -82,5 +82,5 @@
 int main(int argc, char* argv[])
 {
-  std::cout << "Set H_MV equal to 1 in TypeDef.h to build bitstream extractor. " << std::endl; 
+  std::cout << "Set NH_MV equal to 1 in TypeDef.h to build bitstream extractor. " << std::endl; 
   return 1; 
 }
Index: branches/HTM-14.1-update-dev0/source/App/TAppRenderer/RendererMain.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppRenderer/RendererMain.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppRenderer/RendererMain.cpp	(revision 1200)
@@ -34,6 +34,6 @@
 
 #include <time.h>
-#include "../../Lib/TLibCommon/TypeDef.h"
-#if H_3D
+#include "../../Lib/TLibCommon/CommonDef.h"
+#if NH_3D
 #include "TAppRendererTop.h"
 // ====================================================================================================================
@@ -89,4 +89,4 @@
 }
 
-#endif // H_3D
+#endif // NH_3D
 
Index: branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererCfg.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 1200)
@@ -44,5 +44,5 @@
 #include "../../Lib/TAppCommon/program_options_lite.h"
 
-#if H_3D
+#if NH_3D
 
 using namespace std;
@@ -131,11 +131,11 @@
     ("SynthOutputFile_%d,s_%d", m_pchSynthOutputFileList,    (Char *) 0, MAX_OUTPUT_VIEW_NUM, "Synthesized Yuv output file name %d")
 
-    ("InputBitDepth",           m_inputBitDepthY,                     8, "Bit-depth of input file")
-    ("OutputBitDepth",          m_outputBitDepthY,                    0, "Bit-depth of output file (default:InternalBitDepth)")
-    ("InternalBitDepth",        m_internalBitDepthY,                  0, "Bit-depth the renderer operates at. (default:InputBitDepth)"                                                                          "If different to InputBitDepth, source data will be converted")
-
-    ("InputBitDepthC",        m_inputBitDepthC,    0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
-    ("OutputBitDepthC",       m_outputBitDepthC,   0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
-    ("InternalBitDepthC",     m_internalBitDepthC, 0, "As per InternalBitDepth but for chroma component. (default:IntrenalBitDepth)")
+    ("InputBitDepth",           m_inputBitDepth[0],                     8, "Bit-depth of input file")
+    ("OutputBitDepth",          m_outputBitDepth[0],                    0, "Bit-depth of output file (default:InternalBitDepth)")
+    ("InternalBitDepth",        m_internalBitDepth[0],                  0, "Bit-depth the renderer operates at. (default:InputBitDepth)"                                                                          "If different to InputBitDepth, source data will be converted")
+
+    ("InputBitDepthC",        m_inputBitDepth[1],    0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
+    ("OutputBitDepthC",       m_outputBitDepth[1],   0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
+    ("InternalBitDepthC",     m_internalBitDepth[1], 0, "As per InternalBitDepth but for chroma component. (default:IntrenalBitDepth)")
 
     /* Source Specification */
@@ -186,11 +186,9 @@
 
   /* rules for input, output and internal bitdepths as per help text */
-  if (!m_internalBitDepthY) { m_internalBitDepthY = m_inputBitDepthY; }
-  if (!m_internalBitDepthC) { m_internalBitDepthC = m_internalBitDepthY; }
-  if (!m_inputBitDepthC)    { m_inputBitDepthC    = m_inputBitDepthY; }
-  if (!m_outputBitDepthY)   { m_outputBitDepthY   = m_internalBitDepthY; }
-  if (!m_outputBitDepthC)   { m_outputBitDepthC   = m_internalBitDepthC; }
-
-  xSetGlobal();
+  if (!m_internalBitDepth[0]) { m_internalBitDepth[0] = m_inputBitDepth[0]; }
+  if (!m_internalBitDepth[1]) { m_internalBitDepth[1] = m_internalBitDepth[0]; }
+  if (!m_inputBitDepth[1])    { m_inputBitDepth[1]    = m_inputBitDepth[0]; }
+  if (!m_outputBitDepth[0])   { m_outputBitDepth[0]   = m_internalBitDepth[0]; }
+  if (!m_outputBitDepth[1])   { m_outputBitDepth[1]   = m_internalBitDepth[1]; }
 
   UInt  uiInputBitDepth   = 8;
@@ -275,7 +273,7 @@
 
   // bit depth 
-  xConfirmPara( m_internalBitDepthC != m_internalBitDepthY,  "InternalBitDepth for luma and chroma must be equal. "); 
-  xConfirmPara( m_inputBitDepthY < 8,                        "InputBitDepth must be at least 8" );
-  xConfirmPara( m_inputBitDepthC < 8,                        "InputBitDepthC must be at least 8" );
+  xConfirmPara( m_internalBitDepth[0] != m_internalBitDepth[1],  "InternalBitDepth for luma and chroma must be equal. "); 
+  xConfirmPara( m_inputBitDepth[0] < 8,                        "InputBitDepth must be at least 8" );
+  xConfirmPara( m_inputBitDepth[1] < 8,                        "InputBitDepthC must be at least 8" );
 
   // camera specification
@@ -504,5 +502,5 @@
 }
 
-Void TAppRendererCfg::xGetMaxPrecision( std::vector< Int > aiIn, Int& iPrecBefore, Int& iPrecAfter )
+Void TAppRendererCfg::xGetMaxPrecision( IntAry1d aiIn, Int& iPrecBefore, Int& iPrecAfter )
 {
   iPrecBefore = 0;
@@ -525,10 +523,3 @@
 }
 
-Void TAppRendererCfg::xSetGlobal()
-{
-  // set max CU width & height  
-  g_uiMaxCUWidth   = 0;
-  g_uiMaxCUHeight  = 0;  
-}
-
 #endif
Index: branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererCfg.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererCfg.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererCfg.h	(revision 1200)
@@ -47,5 +47,5 @@
 #include <vector>
 
-#if H_3D
+#if NH_3D
 
 // ====================================================================================================================
@@ -66,11 +66,8 @@
 
 
-  // bit-depth      ( Currently interal luma and chroma bit-depth are required to be equal. )
-  Int                m_inputBitDepthY;                 ///< bit-depth of input file (luma component)
-  Int                m_inputBitDepthC;                 ///< bit-depth of input file (chroma component)
-  Int                m_outputBitDepthY;                ///< bit-depth of output file (luma component)
-  Int                m_outputBitDepthC;                ///< bit-depth of output file (chroma component)
-  Int                m_internalBitDepthY;              ///< bit-depth renderer operates at in luma (input/output files will be converted)
-  Int                m_internalBitDepthC;              ///< bit-depth renderer operates at in chroma (input/output files will be converted)
+  // bit-depth      ( Currently internal, output and input luma and chroma bit-depth are required to be equal to 8 )
+  Int                m_inputBitDepth[2];               ///< bit-depth of input file (luma/chroma component)  
+  Int                m_outputBitDepth[2];              ///< bit-depth of output file (luma/chroma component)    
+  Int                m_internalBitDepth[2];            ///< bit-depth renderer operates at in luma/chroma (input/output files will be converted)
 
 
@@ -123,8 +120,7 @@
   Void xPrintParameter ();                              ///< print configuration values
   Void xPrintUsage     ();                              ///< print usage
-  Void xSetGlobal();
 
   Void xCreateFileNames();
-  Void xGetMaxPrecision( std::vector< Int > adIn, Int& iPrecBefore, Int& iPrecAfter );
+  Void xGetMaxPrecision( IntAry1d adIn, Int& iPrecBefore, Int& iPrecAfter );
   Void xAddNumberToFileName( Char* pchSourceFileName, Char*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter );
 public:
@@ -142,3 +138,3 @@
 
 #endif // __TAppRENDERERCFG__
-#endif // H_3D
+#endif // NH_3D
Index: branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererTop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 1200)
@@ -41,5 +41,5 @@
 #include "TAppRendererTop.h"
 
-#if H_3D
+#if NH_3D
 
 // ====================================================================================================================
@@ -67,8 +67,10 @@
     TVideoIOYuv* pcDepthInput = new TVideoIOYuv;
 
-    pcVideoInput->open( m_pchVideoInputFileList[iViewIdx], false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC);  // read mode
-    pcDepthInput->open( m_pchDepthInputFileList[iViewIdx], false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC  );  // read mode
-    pcVideoInput->skipFrames(m_iFrameSkip, m_iSourceWidth, m_iSourceHeight  );
-    pcDepthInput->skipFrames(m_iFrameSkip, m_iSourceWidth, m_iSourceHeight  );
+//    ( Char* pchFile, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] )
+
+    pcVideoInput->open( m_pchVideoInputFileList[iViewIdx], false, m_inputBitDepth, m_internalBitDepth, m_internalBitDepth );  // read mode
+    pcDepthInput->open( m_pchDepthInputFileList[iViewIdx], false, m_inputBitDepth, m_internalBitDepth, m_internalBitDepth );  // read mode
+    pcVideoInput->skipFrames(m_iFrameSkip, m_iSourceWidth, m_iSourceHeight, CHROMA_420 );
+    pcDepthInput->skipFrames(m_iFrameSkip, m_iSourceWidth, m_iSourceHeight, CHROMA_420 );
 
     m_apcTVideoIOYuvVideoInput.push_back( pcVideoInput );
@@ -79,5 +81,5 @@
   {
     TVideoIOYuv* pcSynthOutput = new TVideoIOYuv;
-    pcSynthOutput->open( m_pchSynthOutputFileList[iViewIdx], true, m_outputBitDepthY, m_outputBitDepthC, m_internalBitDepthY, m_internalBitDepthC );  // write mode
+    pcSynthOutput->open( m_pchSynthOutputFileList[iViewIdx], true, m_outputBitDepth, m_internalBitDepth, m_internalBitDepth );  // write mode
     m_apcTVideoIOYuvSynthOutput.push_back( pcSynthOutput );
   }
@@ -148,4 +150,7 @@
   Int aiPad[2] = { 0, 0 };
 
+  TComPicYuv* pcNewOrg = new TComPicYuv;
+  pcNewOrg->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
+
   for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
   {
@@ -153,8 +158,8 @@
     TComPicYuv* pcNewDepthPic = new TComPicYuv;
 
-    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
     apcPicYuvBaseVideo.push_back(pcNewVideoPic);
 
-    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true);
     apcPicYuvBaseDepth.push_back(pcNewDepthPic);
 
@@ -165,8 +170,8 @@
       pcNewDepthPic = new TComPicYuv;
 
-      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
       apcPicYuvLastBaseVideo.push_back(pcNewVideoPic);
 
-      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
       apcPicYuvLastBaseDepth.push_back(pcNewDepthPic);
     }
@@ -175,5 +180,5 @@
   // Create Buffer for synthesized View
   TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
-  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
 
   Bool bAnyEOS = false;
@@ -189,5 +194,5 @@
       for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
       {
-        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx],pcNewOrg, IPCOLOURSPACE_UNCHANGED, aiPad, CHROMA_420  ) ;
 
         apcPicYuvBaseVideo[iBaseViewIdx]->extendPicBorder();
@@ -195,5 +200,5 @@
         bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
 
-        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx],pcNewOrg, IPCOLOURSPACE_UNCHANGED, aiPad, CHROMA_420  ) ;
         apcPicYuvBaseDepth[iBaseViewIdx]->extendPicBorder();
         bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
@@ -428,5 +433,5 @@
       // Write Output
 
-      m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iSynthViewIdx]->write( pcPicYuvSynthOut, 0, 0, 0, 0 );
+      m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iSynthViewIdx]->write( pcPicYuvSynthOut, IPCOLOURSPACE_UNCHANGED, 0, 0, 0, 0, CHROMA_420 );
     }
     iFrame++;
@@ -435,4 +440,7 @@
 
   // Delete Buffers
+  pcNewOrg->destroy(); 
+  delete pcNewOrg; 
+
   for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
   {
@@ -468,5 +476,5 @@
     render();
     break;
-#if H_3D_VSO
+#if NH_3D_VSO
   case 1:
     renderModel();
@@ -490,5 +498,5 @@
 }
 
-#if H_3D_VSO
+#if NH_3D_VSO
 Void TAppRendererTop::renderModel()
 {
@@ -520,12 +528,14 @@
       TComPicYuv* pcNewDepthPic = new TComPicYuv;
 
-      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
       apcPicYuvBaseVideo.push_back(pcNewVideoPic);
 
-      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
       apcPicYuvBaseDepth.push_back(pcNewDepthPic);
     }
 
     Int aiPad[2] = { 0, 0 };
+    TComPicYuv* pcNewOrg = new TComPicYuv;
+    pcNewOrg->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
 
     // Init Model
@@ -550,5 +560,4 @@
         m_cRenModStrParser.getSingleModelData  ( iViewIdx, 1, iCurModel, iModelNum, iBlendMode, iLeftViewNum, iRightViewNum, iOrgRefNum, iDump ) ;
         cCurModel         .createSingleModel   ( iViewIdx, 1, iModelNum, iLeftViewNum, iRightViewNum, false, iBlendMode );
-
       }
     }
@@ -556,5 +565,5 @@
     // Create Buffer for synthesized View
     TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
-    pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
 
     Bool bAnyEOS = false;
@@ -571,8 +580,8 @@
         for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
         {
-          m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+          m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], pcNewOrg, IPCOLOURSPACE_UNCHANGED, aiPad, CHROMA_420  ) ;
           bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
 
-          m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+          m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], pcNewOrg, IPCOLOURSPACE_UNCHANGED, aiPad, CHROMA_420  ) ;
           bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
         }
@@ -672,5 +681,5 @@
 
           // Write Output
-          m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iModelNum]->write( pcPicYuvSynthOut, 0 ,0 ,0, 0 );
+          m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iModelNum]->write( pcPicYuvSynthOut, IPCOLOURSPACE_UNCHANGED,  0 ,0 ,0, 0, CHROMA_420 );
         }
       }
@@ -706,4 +715,7 @@
 
   Int aiPad[2] = { 0, 0 };
+  TComPicYuv* pcNewOrg = new TComPicYuv;
+  pcNewOrg->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
+
 
   // Init Model
@@ -711,5 +723,5 @@
 
   AOT( m_iLog2SamplingFactor != 0 );
-  cCurModel.setupPart( 0, m_iSourceHeight  ); 
+
 #if H_3D_VSO_EARLY_SKIP
   cCurModel.create( m_iNumberOfInputViews, m_iNumberOfOutputViews, m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin, false );
@@ -717,4 +729,5 @@
   cCurModel.create( m_iNumberOfInputViews, m_iNumberOfOutputViews, m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin );
 #endif
+  cCurModel.setupPart( 0, m_iSourceHeight  ); 
 
   for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
@@ -723,8 +736,8 @@
     TComPicYuv* pcNewDepthPic = new TComPicYuv;
 
-    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
     apcPicYuvBaseVideo.push_back(pcNewVideoPic);
 
-    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
     apcPicYuvBaseDepth.push_back(pcNewDepthPic);
   }
@@ -768,5 +781,5 @@
   // Create Buffer for synthesized View
   TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
-  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
 
   Bool bAnyEOS = false;
@@ -783,8 +796,8 @@
       for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
       {
-        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], pcNewOrg, IPCOLOURSPACE_UNCHANGED, aiPad, CHROMA_420  ) ;
         bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
 
-        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], pcNewOrg, IPCOLOURSPACE_UNCHANGED, aiPad, CHROMA_420  ) ;
         bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
 
@@ -871,5 +884,5 @@
 
       // Write Output
-      m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iSynthViewIdx]->write( pcPicYuvSynthOut, 0, 0, 0, 0 );
+      m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iSynthViewIdx]->write( pcPicYuvSynthOut, IPCOLOURSPACE_UNCHANGED,  0 ,0 ,0, 0, CHROMA_420 );
     }
     iFrame++;
@@ -909,4 +922,7 @@
   Int aiPad[2] = { 0, 0 };
 
+  TComPicYuv* pcNewOrg = new TComPicYuv;
+  pcNewOrg->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
+
   for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
   {
@@ -914,9 +930,10 @@
     TComPicYuv* pcNewDepthPic = new TComPicYuv;
 
-    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight,CHROMA_420, 1, 1, 1, true );
     apcPicYuvBaseVideo.push_back(pcNewVideoPic);
 
-    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1, true );
     apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+
 
     //Temporal improvement Filter
@@ -926,8 +943,8 @@
       pcNewDepthPic = new TComPicYuv;
 
-      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1, 1 , true);
       apcPicYuvLastBaseVideo.push_back(pcNewVideoPic);
 
-      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight,CHROMA_420, 1, 1, 1 , true);
       apcPicYuvLastBaseDepth.push_back(pcNewDepthPic);
     }
@@ -936,5 +953,5 @@
   // Create Buffer for synthesized View
   TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
-  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, 1, 1 ,1, true);
 
   Bool bAnyEOS = false;
@@ -950,9 +967,9 @@
       for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
       {
-        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], pcNewOrg, IPCOLOURSPACE_UNCHANGED,  aiPad, CHROMA_420  ) ;
         apcPicYuvBaseVideo[iBaseViewIdx]->extendPicBorder();
         bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
 
-        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], pcNewOrg, IPCOLOURSPACE_UNCHANGED,  aiPad, CHROMA_420  ) ;
         apcPicYuvBaseDepth[iBaseViewIdx]->extendPicBorder();
         bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
@@ -997,5 +1014,5 @@
 
       // Write Output
-      m_apcTVideoIOYuvSynthOutput[iViewIdx-1]->write( pcPicYuvSynthOut, 0, 0, 0 );
+      m_apcTVideoIOYuvSynthOutput[iViewIdx-1]->write( pcPicYuvSynthOut,  IPCOLOURSPACE_UNCHANGED, 0, 0, 0, 0, CHROMA_420 );
 
     }
@@ -1005,4 +1022,8 @@
 
   // Delete Buffers
+
+  pcNewOrg->destroy(); 
+  delete pcNewOrg; 
+
   for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
   {
Index: branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererTop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererTop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/TAppRenderer/TAppRendererTop.h	(revision 1200)
@@ -39,6 +39,6 @@
 #ifndef __TAppRendererTOP__
 #define __TAppRendererTOP__
-#include "../../Lib/TLibCommon/TypeDef.h"
-#if H_3D
+#include "../../Lib/TLibCommon/CommonDef.h"
+#if NH_3D
 #include "../../Lib/TLibRenderer/TRenTop.h"
 #include "../../Lib/TLibVideoIO/TVideoIOYuv.h"
@@ -68,5 +68,5 @@
   Void  xInitLib          ();                               ///< initialize renderer class
   Void  xDestroyLib       ();                               ///< destroy renderer class and video io
-#if H_3D_VSO
+#if NH_3D_VSO
   Void  xRenderModelFromString();                           ///< render using model using setup string
   Void  xRenderModelFromNums();                             ///< render using model using synth view numbers
@@ -78,5 +78,5 @@
 
   Void  render      ();                               ///< main encoding function
-#if H_3D_VSO
+#if NH_3D_VSO
   Void  renderModel ();
 #endif
@@ -87,4 +87,4 @@
 
 
-#endif // H_3D
+#endif // NH_3D
 #endif // __TAppRendererTOP__
Index: branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitrates.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2014, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,19 +45,19 @@
   {
     public:
-      
+
       /// Contructs a new zeroed tally
       Tally( ): m_sum( 0.0 ), m_numSlices( 0 ) { }
-      
+
       /// Adds to the sum and increments the sample-count
       void add( double in ) { ++m_numSlices; m_sum += in; }
-      
+
       /// \return The calculated average
       double average( ) const { return m_sum / ( double )m_numSlices; }
-    
+
     private:
       double m_sum;
       unsigned long m_numSlices;
   };
-  
+
   /// Ignores all of the the characters up to and including a given character
   /// \param line The line being read from
@@ -69,7 +69,10 @@
     while( iLine.good( ) && character != iLine.get( ) )
       ;
-    if( !iLine.good( ) ) throw POCParseException( line );
+    if( !iLine.good( ) )
+    {
+      throw POCParseException( line );
+    }
   }
-  
+
   /// Extracts the average bitrates for each of the temporal layers from the given log
   /// \param i The input stream that represents the log
@@ -79,5 +82,5 @@
   {
     std::map< unsigned char, Tally > tallyMap;
-    
+
     while( i.good( ) )
     {
@@ -86,40 +89,82 @@
       std::getline( i, line );
       std::istringstream iLine( line );
-      if( !iLine.good( ) ) continue;
-      
+      if( !iLine.good( ) )
+      {
+        continue;
+      }
+
       // Ignore the "POC"
-      if( iLine.get( ) != 'P' ) continue;
-      if( !iLine.good( ) ) continue;
-      if( iLine.get( ) != 'O' ) continue;
-      if( !iLine.good( ) ) continue;
-      if( iLine.get( ) != 'C' ) continue;
-      if( !iLine.good( ) ) throw POCParseException( line );
-      
+      if( iLine.get( ) != 'P' )
+      {
+        continue;
+      }
+      if( !iLine.good( ) )
+      {
+        continue;
+      }
+      if( iLine.get( ) != 'O' )
+      {
+        continue;
+      }
+      if( !iLine.good( ) )
+      {
+        continue;
+      }
+      if( iLine.get( ) != 'C' )
+      {
+        continue;
+      }
+      if( !iLine.good( ) )
+      {
+        throw POCParseException( line );
+      }
+
       ignoreUpTo( line, iLine, '(' );
-      
-      if( iLine.get( ) != ' ' ) throw POCParseException( line );
-      if( !iLine.good( ) ) throw POCParseException( line );
-      
-      if( 'I' == iLine.get( ) ) continue;
-      if( !iLine.good( ) ) throw POCParseException( line );
-      
+
+      if( iLine.get( ) != ' ' )
+      {
+        throw POCParseException( line );
+      }
+      if( !iLine.good( ) )
+      {
+        throw POCParseException( line );
+      }
+
+      if( 'I' == iLine.get( ) )
+      {
+        continue;
+      }
+      if( !iLine.good( ) )
+      {
+        throw POCParseException( line );
+      }
+
       ignoreUpTo( line, iLine, ' ' );
       ignoreUpTo( line, iLine, ' ' );
-      
+
       // Parse the qpIndex
       long qpIndexLong;
       iLine >> qpIndexLong;
-      if( ( long )std::numeric_limits< unsigned char >::max( ) < qpIndexLong ) throw POCParseException( line );
+      if( ( long )std::numeric_limits< unsigned char >::max( ) < qpIndexLong )
+      {
+        throw POCParseException( line );
+      }
       unsigned char qpIndex( ( unsigned char )qpIndexLong );
-      if( !iLine.good( ) ) throw POCParseException( line );
-      
+      if( !iLine.good( ) )
+      {
+        throw POCParseException( line );
+      }
+
       ignoreUpTo( line, iLine, ')' );
       ignoreUpTo( line, iLine, ' ' );
-      
+
       // Parse the number of bits
       unsigned long bitsULong;
       iLine >> bitsULong;
-      if( !iLine.good( ) ) throw POCParseException( line );
-      
+      if( !iLine.good( ) )
+      {
+        throw POCParseException( line );
+      }
+
       // Find the tally that corresponds to our QP.  If there is no such tally yet, then add a new one to the map.
       std::map< unsigned char, Tally >::iterator iter( tallyMap.find( qpIndex ) );
@@ -130,8 +175,8 @@
       }
       assert( iter != tallyMap.end( ) );
-      
+
       iter->second.add( ( double )bitsULong );
     }
-    
+
     // Populate and return the result based on all of the tallies
     std::map< unsigned char, double > result;
@@ -147,18 +192,21 @@
 {
   std::vector< double > result;
-  
+
   std::map< unsigned char, double > bitratesForQPsMap( extractBitratesForQPs( i ) );
   if( !bitratesForQPsMap.empty( ) )
   {
     unsigned char expectedNextQPIndex( bitratesForQPsMap.begin( )->first );
-    
+
     for( std::map< unsigned char, double >::const_iterator i( bitratesForQPsMap.begin( ) ); i != bitratesForQPsMap.end( ); ++i )
     {
-      if( i->first != expectedNextQPIndex ) throw NonContiguousQPSetException( );
+      if( i->first != expectedNextQPIndex )
+      {
+        throw NonContiguousQPSetException( );
+      }
       ++expectedNextQPIndex;
       result.push_back( i->second );
     }
   }
-  
+
   return result;
 }
Index: branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitrates.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
- * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -32,6 +32,6 @@
  */
 
-#ifndef EXTRACT_BITRATES_H
-#define EXTRACT_BITRATES_H
+#ifndef __EXTRACTBITRATES__
+#define __EXTRACTBITRATES__
 
 #include "RuntimeError.h"
@@ -44,8 +44,8 @@
     POCParseException( const std::string& pocLine ): m_pocLine( pocLine ) { }
     virtual ~POCParseException( ) throw ( ) { }
-  
+
   protected:
     void outputWhat( std::ostream& o ) const { o << "POC parse exception: " << m_pocLine; }
-  
+
   private:
     std::string m_pocLine;
@@ -57,5 +57,5 @@
   public:
     virtual ~NonContiguousQPSetException( ) throw( ) { }
-  
+
   protected:
     void outputWhat( std::ostream& o ) const { o << "Non-contiguous QP set exception"; }
Index: branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
- * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -44,5 +44,5 @@
   assert( 2 == toFind.size( ) );
   assert( 'e' == toFind[ 0 ] );
-  
+
   std::string::size_type pos( out.find( toFind ) );
   assert( pos != std::string::npos );
@@ -57,8 +57,8 @@
   oss << std::scientific << right;
   std::string s( oss.str( ) );
-  
+
   replaceWithE( s, "e+" );
   replaceWithE( s, "e0" );
-  
+
   left << s;
 }
@@ -69,5 +69,5 @@
   {
     std::vector< double > result( extractBitratesForTemporalLayers( std::cin ) );  // Extract the bitrate vector
-    
+
     // Output the bitrate vector
     if( 0 < result.size( ) )
@@ -89,5 +89,5 @@
       }
     }
-    
+
     return 0;
   }
Index: branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
- * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,12 +46,15 @@
   {
     assert( right.empty( ) );
-    
+
     for( ; ; )
     {
       assert( left.good( ) );
-      
+
       double bitrate;
       left >> bitrate;
-      if( left.fail( ) ) break;
+      if( left.fail( ) )
+      {
+        break;
+      }
       if( bitrate <= ( double )0.0 )
       {
@@ -62,6 +65,9 @@
         right.push_back( bitrate );
       }
-      if( !left.good( ) ) break;
-      
+      if( !left.good( ) )
+      {
+        break;
+      }
+
       if( left.peek( ) == ' ' )
       {
@@ -74,5 +80,5 @@
     }
   }
-  
+
   /// Makes a next guess for a single Lambda-modifier based on only one previous guess
   /// \param initialAdjustmentParameter The proportionality to use between the target bitrate and the previous guess
@@ -88,5 +94,5 @@
     assert( ( double )0.0 < previousPoint.lambdaModifier );
     assert( ( double )0.0 < previousPoint.bitrate );
-    
+
     double extrapolated( previousPoint.lambdaModifier * targetBitrate / previousPoint.bitrate );
     return previousPoint.lambdaModifier + initialAdjustmentParameter * ( extrapolated - previousPoint.lambdaModifier );
@@ -102,5 +108,5 @@
   assert( point1.lambdaModifier != point2.lambdaModifier );
   assert( point1.bitrate != point2.bitrate );
-  
+
   // Calculate and return the result
   double denominator( point1.bitrate - point2.bitrate );
@@ -119,7 +125,7 @@
   assert( interDampeningFactor <= ( double )1.0 );
   assert( !pointList.empty( ) );
-  
+
   double preliminaryResult;
-  
+
   if( 1 == pointList.size( ) )  // If there is only one prevous point, then we cannot interpolate, so we call incrementLambdaModifier
   {
@@ -132,5 +138,5 @@
     ++i;
     Point point2 = *i;
-    
+
     // If the slope is either horizontal or vertical, we cannot interpolate
     if( point1.lambdaModifier == point2.lambdaModifier || point1.bitrate == point2.bitrate )
@@ -143,7 +149,7 @@
     }
   }
-  
+
   double previousResult( pointList.back( ).lambdaModifier );
-  
+
   // Apply "intra dampening"
   {
@@ -159,5 +165,5 @@
     }
   }
-  
+
   // Apply "inter dampening factor".  If necessary, reduce the factor until a positive result is acheived.
   double result;
@@ -180,5 +186,5 @@
     return result;
   }
-  
+
   /// Calculates the inter dampening factor based
   /// \param parameter The inter dampening parameter which determines how severely the inter dampening factor is affected by Lambda-modifier changes at previous temporal layers
@@ -202,5 +208,5 @@
   assert( !targetBitrateVector.empty( ) );
   assert( !metaLogEntryList.empty( ) );
-  
+
   double cumulativeDelta( 0.0 );
   std::vector< double > resultVector;
@@ -212,6 +218,9 @@
     pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
     ++j;
-    if( j != metaLogEntryList.rend( ) ) pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
-    
+    if( j != metaLogEntryList.rend( ) )
+    {
+      pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
+    }
+
     // Calculate the new Lambda-modifier guess and add it to the result vector
     const double newLambdaModifier( guessLambdaModifier(
@@ -221,10 +230,10 @@
         interDampeningFactor( 50.0, cumulativeDelta ) ) );
     resultVector.push_back( newLambdaModifier );
-    
+
     // Increment the cumulativeDelta
     const double oldLambdaModifier( pointList.back( ).lambdaModifier );
     cumulativeDelta += std::abs( newLambdaModifier - oldLambdaModifier ) / oldLambdaModifier;
   }
-  
+
   return resultVector;
 }
@@ -240,7 +249,10 @@
     while( i.good( ) && character != i.get( ) )
       ;
-    if( !i.good( ) ) throw MetaLogParseException( );
-  }
-  
+    if( !i.good( ) )
+    {
+      throw MetaLogParseException( );
+    }
+  }
+
   /// Parses a Lambda-modifier map
   /// \param right The map to write the output to
@@ -250,25 +262,61 @@
     {
       assert( left.good( ) );
-      
+
       // Ignore the "-LM"
-      if( '-' != left.get( ) ) left.setstate( std::istream::failbit );
-      if( !left.good( ) ) break;
-      if( 'L' != left.get( ) ) left.setstate( std::istream::failbit );
-      if( !left.good( ) ) break;
-      if( 'M' != left.get( ) ) left.setstate( std::istream::failbit );
-      if( !left.good( ) ) break;
-      
+      if( '-' != left.get( ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      if( !left.good( ) )
+      {
+        break;
+      }
+      if( 'L' != left.get( ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      if( !left.good( ) )
+      {
+        break;
+      }
+      if( 'M' != left.get( ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      if( !left.good( ) )
+      {
+        break;
+      }
+
       // Parse the index
       long indexLong;
       left >> indexLong;
-      if( !left.good( ) ) break;
-      if( indexLong < std::numeric_limits< unsigned char >::min( ) ) left.setstate( std::istream::failbit );
-      if( std::numeric_limits< unsigned char >::max( ) < indexLong ) left.setstate( std::istream::failbit );
-      if( !left.good( ) ) break;
+      if( !left.good( ) )
+      {
+        break;
+      }
+      if( indexLong < std::numeric_limits< unsigned char >::min( ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      if( std::numeric_limits< unsigned char >::max( ) < indexLong )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      if( !left.good( ) )
+      {
+        break;
+      }
       unsigned char index( ( unsigned char )indexLong );
-      
-      if( ' ' != left.get( ) ) left.setstate( std::istream::failbit );
-      if( !left.good( ) ) break;
-      
+
+      if( ' ' != left.get( ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      if( !left.good( ) )
+      {
+        break;
+      }
+
       // Parse the Lambda-modifier
       double lambdaModifier;
@@ -282,6 +330,9 @@
         right[ index ] = lambdaModifier;
       }
-      if( !left.good( ) ) break;
-      
+      if( !left.good( ) )
+      {
+        break;
+      }
+
       // If we peek and see a space, then there should be more Lambda-modifiers to parse.  Otherwise, we are finished.
       if( left.peek( ) == ' ' )
@@ -295,5 +346,5 @@
     }
   }
-  
+
   /// Extracts the indexes from the given maps
   /// \return The set of indexes
@@ -322,10 +373,13 @@
     throw InitialAdjustmentParameterParseException( );
   }
-  
+
   // Parse the targets
   std::vector< double > targetVector;
   parseBitrateVector( targetsIstream, targetVector );
-  if( targetVector.empty( ) || targetsIstream.fail( ) || targetsIstream.good( ) ) throw TargetsParseException( );
-  
+  if( targetVector.empty( ) || targetsIstream.fail( ) || targetsIstream.good( ) )
+  {
+    throw TargetsParseException( );
+  }
+
   // Parse the metalog
   std::list< MetaLogEntry< std::map< unsigned char, double > > > metaLogEntryList;
@@ -335,32 +389,62 @@
     MetaLogEntry< std::map< unsigned char, double > > entry;
     parseLambdaModifierMap( metaLogIstream, entry.lambdaModifiers );
-    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
-    
+    if( !metaLogIstream.good( ) )
+    {
+      throw MetaLogParseException( );
+    }
+
     // Skip the ';'
-    if( ';' != metaLogIstream.get( ) ) throw MetaLogParseException( );
-    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
-    
+    if( ';' != metaLogIstream.get( ) )
+    {
+      throw MetaLogParseException( );
+    }
+    if( !metaLogIstream.good( ) )
+    {
+      throw MetaLogParseException( );
+    }
+
     // Parse the bitrates
     parseBitrateVector( metaLogIstream, entry.bitrateVector );
-    if( metaLogIstream.fail( ) ) throw MetaLogParseException( );
+    if( metaLogIstream.fail( ) )
+    {
+      throw MetaLogParseException( );
+    }
     metaLogEntryList.push_back( entry );
-    
-    if( !metaLogIstream.good( ) ) break;
-    if( metaLogIstream.get( ) != '\n' ) throw MetaLogParseException( );
+
+    if( !metaLogIstream.good( ) )
+    {
+      break;
+    }
+    if( metaLogIstream.get( ) != '\n' )
+    {
+      throw MetaLogParseException( );
+    }
     metaLogIstream.peek( );
   } while( metaLogIstream.good( ) );
-  if( metaLogEntryList.empty( ) ) throw MetaLogParseException( );  // The meta-log should not be empty
-  
+  if( metaLogEntryList.empty( ) )
+  {
+    throw MetaLogParseException( );  // The meta-log should not be empty
+  }
+
   // Initialize firstIndexVector and check that the sizes and indexes match
   std::set< unsigned char > firstIndexSet( indexSetFromMap( metaLogEntryList.front( ).lambdaModifiers ) );
-  if( firstIndexSet.size( ) != targetVector.size( ) ) throw MismatchedIndexesException( );
+  if( firstIndexSet.size( ) != targetVector.size( ) )
+  {
+    throw MismatchedIndexesException( );
+  }
   for( std::list< MetaLogEntry< std::map< unsigned char, double > > >::const_iterator i( metaLogEntryList.begin( ) );
       i != metaLogEntryList.end( );
       ++i )
   {
-    if( indexSetFromMap( i->lambdaModifiers ) != firstIndexSet ) throw MismatchedIndexesException( );
-    if( i->bitrateVector.size( ) != targetVector.size( ) ) throw MismatchedIndexesException( );
-  }
-  
+    if( indexSetFromMap( i->lambdaModifiers ) != firstIndexSet )
+    {
+      throw MismatchedIndexesException( );
+    }
+    if( i->bitrateVector.size( ) != targetVector.size( ) )
+    {
+      throw MismatchedIndexesException( );
+    }
+  }
+
   // Initialize simplifiedMetaLogEntryList
   std::list< MetaLogEntry< std::vector< double > > > simplifiedMetaLogEntryList;
@@ -376,8 +460,8 @@
     simplifiedMetaLogEntryList.back( ).bitrateVector = i->bitrateVector;
   }
-  
+
   // Run the calculations
   std::vector< double > resultVector( guessLambdaModifiers( initialAdjustmentParameter, targetVector, simplifiedMetaLogEntryList ) );
-  
+
   // Output the results
   std::set< unsigned char >::const_iterator indexIter( firstIndexSet.begin( ) );
@@ -385,10 +469,13 @@
   do
   {
-    if( indexIter != firstIndexSet.begin( ) ) o << " ";
+    if( indexIter != firstIndexSet.begin( ) )
+    {
+      o << " ";
+    }
     o << "-LM" << ( long )( *indexIter ) << " ";
     o.setf( std::ostream::fixed, std::ostream::floatfield );
     o.precision( 7 );
     o << ( *resultIter );
-    
+
     ++indexIter;
     ++resultIter;
Index: branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
- * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -32,6 +32,6 @@
  */
 
-#ifndef CALCULATE_LAMBDA_MODIFIER_H
-#define CALCULATE_LAMBDA_MODIFIER_H
+#ifndef __GUESSLAMBDAMODIFIERS__
+#define __GUESSLAMBDAMODIFIERS__
 
 #include "RuntimeError.h"
@@ -94,5 +94,5 @@
 
 /// Performs interpolation/extrapolation to guess a single Lambda-modifier
-/// \param target The target bitrate value that this Lambda-modifier is trying to reach
+/// \param targetBitrate The target bitrate value that this Lambda-modifier is trying to reach
 /// \param point1 One of the two previously tried points where first is the Lambda-modifier and second is the obtained bitrate
 /// \param point2 One of the two previously tried points where first is the Lambda-modifier and second is the obtained bitrate
@@ -134,5 +134,5 @@
 /// \param o The output stream to write the guessed Lambda-modifiers to
 /// \param initialAdjustmentParameterIstream The input stream that contains the initial adjustment parameter
-/// \param targetIstream The input stream that contains the target bitrates
+/// \param targetsIstream The input stream that contains the target bitrates
 /// \param metaLogIstream The input stream that contains the meta-log
 /// \throw InitialAdjustmentParameterParseException if there is an error parsing the initial adjustment parameter
Index: branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
- * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -49,15 +49,18 @@
   try
   {
-    if( argc != 3 ) throw WrongNumberOfArgumentsException( );
-    
+    if( argc != 3 )
+    {
+      throw WrongNumberOfArgumentsException( );
+    }
+
     std::string initialAdjustmentParameterString( ppArgv[ 1 ] );
     std::istringstream initialAdjustmentParameterIstream( initialAdjustmentParameterString );
-    
+
     std::string targetBitratesString( ppArgv[ 2 ] );
     std::istringstream targetBitratesIstream( targetBitratesString );
-    
+
     guessLambdaModifiers( std::cout, initialAdjustmentParameterIstream, targetBitratesIstream, std::cin );
     return 0;
-  
+
   }
   catch( std::exception& e )
Index: branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/RuntimeError.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
- * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -32,6 +32,6 @@
  */
 
-#ifndef DIRECTORY_LIB_RUNTIME_ERROR_H
-#define DIRECTORY_LIB_RUNTIME_ERROR_H
+#ifndef __RUNTIMEERROR__
+#define __RUNTIMEERROR__
 
 #include <sstream>
@@ -44,5 +44,5 @@
     RuntimeError( ): std::runtime_error( "" ), m_firstWhat( true ) { }
     virtual ~RuntimeError( ) throw ( ) { }
-    
+
     /// Implementation of the std::exception::what method
     const char * what( ) const throw( )
@@ -57,10 +57,10 @@
       return m_what.c_str( );
     }
-    
+
   protected:
     /// The implementing class implements this method to customize the what output
     /// \param o The what stream is outputted to this parameter
     virtual void outputWhat( std::ostream & o ) const =0;
-  
+
   private:
     mutable bool m_firstWhat;  ///< True i.f.f. the what method has not yet been called
Index: branches/HTM-14.1-update-dev0/source/App/utils/annexBbytecount.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/annexBbytecount.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/annexBbytecount.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2014, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -43,5 +43,5 @@
 using namespace std;
 
-static struct {
+static const struct {
   AnnexBStats expected;
   unsigned data_len;
@@ -86,5 +86,7 @@
       cout << hex << (unsigned int)tests[i].data[j] << dec;
       if (j < tests[i].data_len-1)
+      {
         cout << ",";
+      }
     }
     cout << "} ";
@@ -103,5 +105,7 @@
 #undef VERIFY
     if (ok)
+    {
       cout << "OK";
+    }
     cout << endl;
   }
@@ -113,5 +117,7 @@
 
   if (argc != 2)
+  {
     return 0;
+  }
 
   ifstream in(argv[1], ifstream::in | ifstream::binary);
@@ -150,5 +156,7 @@
 
     if (!annexBStatsSingle.m_numBytesInNALUnit)
+    {
       continue;
+    }
 
     /* identify the NAL unit type and add stats to the correct
Index: branches/HTM-14.1-update-dev0/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
- * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -41,12 +41,12 @@
 namespace po = df::program_options_lite;
 
-int main(int argc, const char** argv)
+Int main(Int argc, const char** argv)
 {
-  bool do_help;
+  Bool do_help;
   string filename_in, filename_out;
-  unsigned int width, height;
-  unsigned int bitdepth_in, bitdepth_out;
-  unsigned int num_frames;
-  unsigned int num_frames_skip;
+  UInt width, height;
+  UInt bitdepth_in, bitdepth_out, chromaFormatRaw;
+  UInt num_frames;
+  UInt num_frames_skip;
 
   po::Options opts;
@@ -59,4 +59,5 @@
   ("InputBitDepth", bitdepth_in, 8u, "bit-depth of input file")
   ("OutputBitDepth", bitdepth_out, 8u, "bit-depth of output file")
+  ("ChromaFormat", chromaFormatRaw, 420u, "chroma format. 400, 420, 422 or 444 only")
   ("NumFrames", num_frames, 0xffffffffu, "number of frames to process")
   ("FrameSkip,-fs", num_frames_skip, 0u, "Number of frames to skip at start of input YUV")
@@ -65,4 +66,5 @@
   po::setDefaults(opts);
   po::scanArgv(opts, argc, argv);
+
 
   if (argc == 1 || do_help)
@@ -73,44 +75,73 @@
   }
 
+  ChromaFormat chromaFormatIDC=CHROMA_420;
+  switch (chromaFormatRaw)
+  {
+    case 400: chromaFormatIDC=CHROMA_400; break;
+    case 420: chromaFormatIDC=CHROMA_420; break;
+    case 422: chromaFormatIDC=CHROMA_422; break;
+    case 444: chromaFormatIDC=CHROMA_444; break;
+    default:
+      fprintf(stderr, "Bad chroma format string\n");
+      return EXIT_FAILURE;
+  }
+
   TVideoIOYuv input;
   TVideoIOYuv output;
 
-  input.open((char*)filename_in.c_str(), false, bitdepth_in, bitdepth_in, bitdepth_out, bitdepth_out);
-  output.open((char*)filename_out.c_str(), true, bitdepth_out, bitdepth_out, bitdepth_out, bitdepth_out);
+  Int inputBitDepths [MAX_NUM_CHANNEL_TYPE];
+  Int outputBitDepths[MAX_NUM_CHANNEL_TYPE];
 
-  input.skipFrames(num_frames_skip, width, height);
+  for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+  {
+    inputBitDepths [channelTypeIndex] = bitdepth_in;
+    outputBitDepths[channelTypeIndex] = bitdepth_out;
+  }
+
+  input.open((char*)filename_in.c_str(), false, inputBitDepths, inputBitDepths, outputBitDepths);
+  output.open((char*)filename_out.c_str(), true, outputBitDepths, outputBitDepths, outputBitDepths);
+
+  input.skipFrames(num_frames_skip, width, height, chromaFormatIDC);
 
   TComPicYuv frame;
-  frame.create( width, height, 1, 1, 0 );
+  frame.create( width, height, chromaFormatIDC, width, height, 0, false);
 
-  int pad[2] = {0, 0};
+  Int pad[2] = {0, 0};
 
-  unsigned int num_frames_processed = 0;
-  while (!input.isEof()) 
+  TComPicYuv cPicYuvTrueOrg;
+  cPicYuvTrueOrg.create( width, height, chromaFormatIDC, width, height, 0, false );
+
+  UInt num_frames_processed = 0;
+  while (!input.isEof())
   {
-    if (! input.read(&frame, pad))
+    if (! input.read(&frame, &cPicYuvTrueOrg, IPCOLOURSPACE_UNCHANGED, pad))
     {
       break;
     }
 #if 0
-    Pel* img = frame.getLumaAddr();
-    for (int y = 0; y < height; y++) 
+    Pel* img = frame.getAddr(COMPONENT_Y);
+    for (Int y = 0; y < height; y++)
     {
-      for (int x = 0; x < height; x++)
+      for (Int x = 0; x < height; x++)
+      {
         img[x] = 0;
+      }
       img += frame.getStride();
     }
-    img = frame.getLumaAddr();
+    img = frame.getAddr(COMPONENT_Y);
     img[0] = 1;
 #endif
 
-    output.write(&frame);
+    output.write(&frame, IPCOLOURSPACE_UNCHANGED);
     num_frames_processed++;
     if (num_frames_processed == num_frames)
+    {
       break;
+    }
   }
 
   input.close();
   output.close();
+  cPicYuvTrueOrg.destroy();
 
   return EXIT_SUCCESS;
Index: branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/TAppComCamPara.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 1200)
@@ -49,5 +49,5 @@
 #include <functional>
 #include <string>
-#if H_3D
+#if NH_3D
 
 
@@ -1366,5 +1366,5 @@
 }
 
-#if H_3D_VSO
+#if NH_3D_VSO
 Void
 TAppComCamPara::setDispCoeff( UInt uiFrameId, Int iViewIdx )
Index: branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/TAppComCamPara.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/TAppComCamPara.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/TAppComCamPara.h	(revision 1200)
@@ -188,5 +188,5 @@
 #endif
 
-#if H_3D_VSO
+#if NH_3D_VSO
   // SAIT_VSO_EST_A033
   Void                setDispCoeff              ( UInt uiStartFrameId, Int iViewIdx );
Index: branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -40,5 +40,5 @@
 #include <algorithm>
 #include "program_options_lite.h"
-#include  "../TLibCommon/TypeDef.h"
+#include  "../TLibCommon/CommonDef.h"
 using namespace std;
 
@@ -50,5 +50,19 @@
   namespace program_options_lite
   {
-    
+    ErrorReporter default_error_reporter;
+
+    ostream& ErrorReporter::error(const string& where)
+    {
+      is_errored = 1;
+      cerr << where << " error: ";
+      return cerr;
+    }
+
+    ostream& ErrorReporter::warn(const string& where)
+    {
+      cerr << where << " warning: ";
+      return cerr;
+    }
+
     Options::~Options()
     {
@@ -58,5 +72,5 @@
       }
     }
-    
+
     void Options::addOption(OptionBase *opt)
     {
@@ -64,5 +78,5 @@
       names->opt = opt;
       string& opt_string = opt->opt_string;
-      
+
       size_t opt_start = 0;
       for (size_t opt_end = 0; opt_end != string::npos;)
@@ -96,6 +110,6 @@
       return OptionSpecific(*this);
     }
-    
-    static void setOptions(Options::NamesPtrList& opt_list, const string& value)
+
+    static void setOptions(Options::NamesPtrList& opt_list, const string& value, ErrorReporter& error_reporter)
     {
       /* multiple options may be registered for the same name:
@@ -103,10 +117,10 @@
       for (Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); ++it)
       {
-        (*it)->opt->parse(value);
+        (*it)->opt->parse(value, error_reporter);
       }
     }
 
     static const char spaces[41] = "                                        ";
-    
+
     /* format help text for a single option:
      * using the formatting: "-x, --long",
@@ -138,5 +152,5 @@
       }
     }
-    
+
     /* format the help text */
     void doHelp(ostream& out, Options& opts, unsigned columns)
@@ -147,5 +161,5 @@
       for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
       {
-#if H_MV
+#if NH_MV
         if  ( (*it)->opt->opt_duplicate ) continue; 
 #endif
@@ -157,5 +171,5 @@
       unsigned opt_width = min(max_width+2, 28u + pad_short) + 2;
       unsigned desc_width = columns - opt_width;
-      
+
       /* second pass: write out formatted option and help text.
        *  - align start of help text to start at opt_width
@@ -165,5 +179,5 @@
       for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
       {
-#if H_MV
+#if NH_MV
         if  ( (*it)->opt->opt_duplicate ) continue; 
 #endif
@@ -215,5 +229,5 @@
             split_pos = opt_desc.find_last_not_of(' ', split_pos) + 1;
           }
-          
+
           /* bad split if no suitable space to split at.  fall back to width */
           bool bad_split = split_pos == string::npos || split_pos <= cur_pos;
@@ -223,5 +237,5 @@
           }
           line << opt_desc.substr(cur_pos, split_pos - cur_pos);
-          
+
           /* eat up any space for the start of the next line */
           if (!bad_split)
@@ -230,5 +244,5 @@
           }
           cur_pos = newline_pos = split_pos;
-          
+
           if (cur_pos >= opt_desc.size())
           {
@@ -241,6 +255,25 @@
       }
     }
-    
-    bool storePair(Options& opts, bool allow_long, bool allow_short, const string& name, const string& value)
+
+    struct OptionWriter
+    {
+      OptionWriter(Options& rOpts, ErrorReporter& err)
+      : opts(rOpts), error_reporter(err)
+      {}
+      virtual ~OptionWriter() {}
+
+      virtual const string where() = 0;
+
+      bool storePair(bool allow_long, bool allow_short, const string& name, const string& value);
+      bool storePair(const string& name, const string& value)
+      {
+        return storePair(true, true, name, value);
+      }
+
+      Options& opts;
+      ErrorReporter& error_reporter;
+    };
+
+    bool OptionWriter::storePair(bool allow_long, bool allow_short, const string& name, const string& value)
     {
       bool found = false;
@@ -254,5 +287,5 @@
         }
       }
-      
+
       /* check for the short list */
       if (allow_short && !(found && allow_long))
@@ -267,22 +300,29 @@
       if (!found)
       {
-        /* not found */
-        cerr << "Unknown option: `" << name << "' (value:`" << value << "')" << endl;
+        error_reporter.error(where())
+          << "Unknown option `" << name << "' (value:`" << value << "')\n";
         return false;
       }
 
-      setOptions((*opt_it).second, value);
+      setOptions((*opt_it).second, value, error_reporter);
       return true;
     }
-    
-    bool storePair(Options& opts, const string& name, const string& value)
-    {
-      return storePair(opts, true, true, name, value);
-    }
-    
+
+    struct ArgvParser : public OptionWriter
+    {
+      ArgvParser(Options& rOpts, ErrorReporter& rError_reporter)
+      : OptionWriter(rOpts, rError_reporter)
+      {}
+
+      const string where() { return "command line"; }
+
+      unsigned parseGNU(unsigned argc, const char* argv[]);
+      unsigned parseSHORT(unsigned argc, const char* argv[]);
+    };
+
     /**
      * returns number of extra arguments consumed
      */
-    unsigned parseGNU(Options& opts, unsigned argc, const char* argv[])
+    unsigned ArgvParser::parseGNU(unsigned argc, const char* argv[])
     {
       /* gnu style long options can take the forms:
@@ -294,5 +334,5 @@
       size_t arg_opt_sep = arg.find_first_of('=');
       string option = arg.substr(arg_opt_start, arg_opt_sep - arg_opt_start);
-      
+
       unsigned extra_argc_consumed = 0;
       if (arg_opt_sep == string::npos)
@@ -305,8 +345,10 @@
         * booleans */
         if (argc == 1)
+        {
           return 0; /* run out of argv for argument */
+        }
         extra_argc_consumed = 1;
 #endif
-        if(!storePair(opts, true, false, option, "1"))
+        if(!storePair(true, false, option, "1"))
         {
           return 0;
@@ -317,5 +359,5 @@
         /* argument occurs after option_sep */
         string val = arg.substr(arg_opt_sep + 1);
-        storePair(opts, true, false, option, val);
+        storePair(true, false, option, val);
       }
 
@@ -323,5 +365,5 @@
     }
 
-    unsigned parseSHORT(Options& opts, unsigned argc, const char* argv[])
+    unsigned ArgvParser::parseSHORT(unsigned argc, const char* argv[])
     {
       /* short options can take the forms:
@@ -338,15 +380,18 @@
       if (argc == 1)
       {
-        cerr << "Not processing option without argument `" << option << "'" << endl;
+        error_reporter.error(where())
+          << "Not processing option `" << option << "' without argument\n";
         return 0; /* run out of argv for argument */
       }
-      storePair(opts, false, true, option, string(argv[1]));
+      storePair(false, true, option, string(argv[1]));
 
       return 1;
     }
-    
+
     list<const char*>
-    scanArgv(Options& opts, unsigned argc, const char* argv[])
-    {
+    scanArgv(Options& opts, unsigned argc, const char* argv[], ErrorReporter& error_reporter)
+    {
+      ArgvParser avp(opts, error_reporter);
+
       /* a list for anything that didn't get handled as an option */
       list<const char*> non_option_arguments;
@@ -370,9 +415,5 @@
         {
           /* handle short (single dash) options */
-#if 0
-          i += parsePOSIX(opts, argc - i, &argv[i]);
-#else
-          i += parseSHORT(opts, argc - i, &argv[i]);
-#endif
+          i += avp.parseSHORT(argc - i, &argv[i]);
           continue;
         }
@@ -382,16 +423,39 @@
           /* a lone double dash ends option processing */
           while (++i < argc)
+          {
             non_option_arguments.push_back(argv[i]);
+          }
           break;
         }
 
         /* handle long (double dash) options */
-        i += parseGNU(opts, argc - i, &argv[i]);
+        i += avp.parseGNU(argc - i, &argv[i]);
       }
 
       return non_option_arguments;
     }
-    
-    void scanLine(Options& opts, string& line)
+
+    struct CfgStreamParser : public OptionWriter
+    {
+      CfgStreamParser(const string& rName, Options& rOpts, ErrorReporter& rError_reporter)
+      : OptionWriter(rOpts, rError_reporter)
+      , name(rName)
+      , linenum(0)
+      {}
+
+      const string name;
+      int linenum;
+      const string where()
+      {
+        ostringstream os;
+        os << name << ":" << linenum;
+        return os.str();
+      }
+
+      void scanLine(string& line);
+      void scanStream(istream& in);
+    };
+
+    void CfgStreamParser::scanLine(string& line)
     {
       /* strip any leading whitespace */
@@ -416,4 +480,5 @@
       {
         /* error: badly formatted line */
+        error_reporter.warn(where()) << "line formatting error\n";
         return;
       }
@@ -421,4 +486,5 @@
       {
         /* error: badly formatted line */
+        error_reporter.warn(where()) << "line formatting error\n";
         return;
       }
@@ -429,4 +495,9 @@
       {
         /* error: badly formatted line */
+#if !NH_MV
+        error_reporter.warn(where()) << "line formatting error\n";
+#else
+        // HTM also allows empty parameters.
+#endif
         return;
       }
@@ -447,6 +518,5 @@
          * any trailing whitespace will be removed shortly */
         value_end = line.find_first_not_of(" \t\n\r", value_end);
-      }
-      while (value_end != string::npos);
+      } while (value_end != string::npos);
       /* strip any trailing space from value*/
       value_end = line.find_last_not_of(" \t\n\r", value_end);
@@ -460,20 +530,25 @@
       {
         /* error: no value */
+#if !NH_MV
+        error_reporter.warn(where()) << "no value found\n";
+#else
+        // This is ok for HTM.
+#endif
         return;
       }
 
       /* store the value in option */
-      storePair(opts, true, false, option, value);
-    }
-
-    void scanFile(Options& opts, istream& in)
+      storePair(true, false, option, value);
+    }
+
+    void CfgStreamParser::scanStream(istream& in)
     {
       do
       {
+        linenum++;
         string line;
         getline(in, line);
-        scanLine(opts, line);
-      }
-      while(!!in);
+        scanLine(line);
+      } while(!!in);
     }
 
@@ -488,17 +563,18 @@
     }
 
-    void parseConfigFile(Options& opts, const string& filename)
+    void parseConfigFile(Options& opts, const string& filename, ErrorReporter& error_reporter)
     {
       ifstream cfgstream(filename.c_str(), ifstream::in);
       if (!cfgstream)
       {
-        cerr << "Failed to open config file: `" << filename << "'" << endl;
-        exit(EXIT_FAILURE);
-      }
-      scanFile(opts, cfgstream);
-    }
-
-  };
-};
+        error_reporter.error(filename) << "Failed to open config file\n";
+        return;
+      }
+      CfgStreamParser csp(filename, opts, error_reporter);
+      csp.scanStream(cfgstream);
+    }
+
+  }
+}
 
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/program_options_lite.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TAppCommon/program_options_lite.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,7 +36,7 @@
 #include <list>
 #include <map>
-#include  "../TLibCommon/TypeDef.h"
-
-#if H_MV
+#include  "../TLibCommon/CommonDef.h" 
+
+#if NH_MV
 #include <vector>
 #include <errno.h>
@@ -47,4 +47,9 @@
 #endif
 #endif
+
+
+#ifndef __PROGRAM_OPTIONS_LITE__
+#define __PROGRAM_OPTIONS_LITE__
+
 //! \ingroup TAppCommon
 //! \{
@@ -56,5 +61,5 @@
   {
     struct Options;
-    
+
     struct ParseFailure : public std::exception
     {
@@ -71,14 +76,20 @@
     };
 
+    struct ErrorReporter
+    {
+      ErrorReporter() : is_errored(0) {}
+      virtual ~ErrorReporter() {}
+      virtual std::ostream& error(const std::string& where);
+      virtual std::ostream& warn(const std::string& where);
+      bool is_errored;
+    };
+
+    extern ErrorReporter default_error_reporter;
+
     void doHelp(std::ostream& out, Options& opts, unsigned columns = 80);
-    unsigned parseGNU(Options& opts, unsigned argc, const char* argv[]);
-    unsigned parseSHORT(Options& opts, unsigned argc, const char* argv[]);
-    std::list<const char*> scanArgv(Options& opts, unsigned argc, const char* argv[]);
-    void scanLine(Options& opts, std::string& line);
-    void scanFile(Options& opts, std::istream& in);
+    std::list<const char*> scanArgv(Options& opts, unsigned argc, const char* argv[], ErrorReporter& error_reporter = default_error_reporter);
     void setDefaults(Options& opts);
-    void parseConfigFile(Options& opts, const std::string& filename);
-    bool storePair(Options& opts, const std::string& name, const std::string& value);
-    
+    void parseConfigFile(Options& opts, const std::string& filename, ErrorReporter& error_reporter = default_error_reporter);
+
     /** OptionBase: Virtual base class for storing information relating to a
      * specific option This base class describes common elements.  Type specific
@@ -86,5 +97,5 @@
     struct OptionBase
     {
-#if H_MV      
+#if NH_MV      
       OptionBase(const std::string& name, const std::string& desc, bool duplicate = false)
         : opt_string(name), opt_desc(desc), opt_duplicate(duplicate)
@@ -94,24 +105,24 @@
 #endif
       {};
-      
+
       virtual ~OptionBase() {}
-      
+
       /* parse argument arg, to obtain a value for the option */
-      virtual void parse(const std::string& arg) = 0;
+      virtual void parse(const std::string& arg, ErrorReporter&) = 0;
       /* set the argument to the default value */
       virtual void setDefault() = 0;
-      
+
       std::string opt_string;
       std::string opt_desc;
-#if H_MV
+#if NH_MV
       bool        opt_duplicate; 
 #endif
     };
-    
+
     /** Type specific option storage */
     template<typename T>
     struct Option : public OptionBase
     {
-#if H_MV
+#if NH_MV
       Option(const std::string& name, T& storage, T default_val, const std::string& desc, bool duplicate = false)
         : OptionBase(name, desc, duplicate), opt_storage(storage), opt_default_val(default_val)
@@ -121,20 +132,20 @@
 #endif
       {}
-      
-      void parse(const std::string& arg);
-      
+
+      void parse(const std::string& arg, ErrorReporter&);
+
       void setDefault()
       {
         opt_storage = opt_default_val;
       }
-      
+
       T& opt_storage;
       T opt_default_val;
     };
-    
+
     /* Generic parsing */
     template<typename T>
     inline void
-    Option<T>::parse(const std::string& arg)
+    Option<T>::parse(const std::string& arg, ErrorReporter&)
     {
       std::istringstream arg_ss (arg,std::istringstream::in);
@@ -149,18 +160,18 @@
       }
     }
-    
+
     /* string parsing is specialized -- copy the whole string, not just the
      * first word */
     template<>
     inline void
-    Option<std::string>::parse(const std::string& arg)
+    Option<std::string>::parse(const std::string& arg, ErrorReporter&)
     {
       opt_storage = arg;
     }
 
-#if H_MV    
+#if NH_MV    
     template<>
     inline void
-      Option<char*>::parse(const std::string& arg)
+      Option<char*>::parse(const std::string& arg, ErrorReporter&)
     {
       opt_storage = arg.empty() ? NULL : strdup(arg.c_str()) ;
@@ -169,5 +180,5 @@
     template<>
     inline void
-      Option< std::vector<char*> >::parse(const std::string& arg)
+      Option< std::vector<char*> >::parse(const std::string& arg, ErrorReporter&)
     {
       opt_storage.clear(); 
@@ -191,5 +202,5 @@
     template<>    
     inline void
-      Option< std::vector<double> >::parse(const std::string& arg)
+      Option< std::vector<double> >::parse(const std::string& arg, ErrorReporter&)
     {
       char* pcNextStart = (char*) arg.data();
@@ -227,5 +238,5 @@
     template<>
     inline void
-      Option< std::vector<int> >::parse(const std::string& arg)
+      Option< std::vector<int> >::parse(const std::string& arg, ErrorReporter&)
     {
       opt_storage.clear();
@@ -265,5 +276,5 @@
     template<>
     inline void
-      Option< std::vector<bool> >::parse(const std::string& arg)
+      Option< std::vector<bool> >::parse(const std::string& arg, ErrorReporter&)
     {
       char* pcNextStart = (char*) arg.data();
@@ -299,32 +310,32 @@
     struct OptionFunc : public OptionBase
     {
-      typedef void (Func)(Options&, const std::string&);
-      
+      typedef void (Func)(Options&, const std::string&, ErrorReporter&);
+
       OptionFunc(const std::string& name, Options& parent_, Func *func_, const std::string& desc)
       : OptionBase(name, desc), parent(parent_), func(func_)
       {}
-      
-      void parse(const std::string& arg)
-      {
-        func(parent, arg);
-      }
-      
+
+      void parse(const std::string& arg, ErrorReporter& error_reporter)
+      {
+        func(parent, arg, error_reporter);
+      }
+
       void setDefault()
       {
         return;
       }
-      
+
     private:
       Options& parent;
-      void (*func)(Options&, const std::string&);
-    };
-    
+      Func* func;
+    };
+
     class OptionSpecific;
     struct Options
     {
       ~Options();
-      
+
       OptionSpecific addOptions();
-      
+
       struct Names
       {
@@ -333,5 +344,7 @@
         {
           if (opt)
+          {
             delete opt;
+          }
         }
         std::list<std::string> opt_long;
@@ -341,13 +354,13 @@
 
       void addOption(OptionBase *opt);
-      
+
       typedef std::list<Names*> NamesPtrList;
       NamesPtrList opt_list;
-      
+
       typedef std::map<std::string, NamesPtrList> NamesMap;
       NamesMap opt_long_map;
       NamesMap opt_short_map;
     };
-    
+
     /* Class with templated overloaded operator(), for use by Options::addOptions() */
     class OptionSpecific
@@ -355,5 +368,5 @@
     public:
       OptionSpecific(Options& parent_) : parent(parent_) {}
-      
+
       /**
        * Add option described by name to the parent Options list,
@@ -369,6 +382,6 @@
         return *this;
       }
-      
-#if H_MV
+
+#if NH_MV
       template<typename T>
       OptionSpecific&
@@ -419,7 +432,9 @@
       Options& parent;
     };
-    
-  }; /* namespace: program_options_lite */
-}; /* namespace: df */
+
+  } /* namespace: program_options_lite */
+} /* namespace: df */
 
 //! \}
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/AccessUnit.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/AccessUnit.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/AccessUnit.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -32,5 +32,5 @@
  */
 
-/** 
+/**
  \file     AccessUnit.h
  \brief    Access Unit class (header)
@@ -38,4 +38,7 @@
 
 #pragma once
+
+#ifndef __ACCESSUNIT__
+#define __ACCESSUNIT__
 
 #include <list>
@@ -57,5 +60,5 @@
  * AccessUnit will delete all contained objects.
  */
-class AccessUnit : public std::list<NALUnitEBSP*>
+class AccessUnit : public std::list<NALUnitEBSP*> // NOTE: Should not inherit from STL.
 {
 public:
@@ -70,2 +73,4 @@
 
 //! \}
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/CommonDef.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/CommonDef.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -33,5 +33,5 @@
 
 /** \file     CommonDef.h
-    \brief    Defines constants, macros and tool parameters
+    \brief    Defines version information, constants and small in-line functions
 */
 
@@ -40,13 +40,26 @@
 
 #include <algorithm>
+#include <iostream>
+#include <assert.h>
 
 #if _MSC_VER > 1000
 // disable "signed and unsigned mismatch"
 #pragma warning( disable : 4018 )
-// disable bool coercion "performance warning"
+// disable Bool coercion "performance warning"
 #pragma warning( disable : 4800 )
+// NH_MV
+// disabled decorated name length warning issued for IntAry5d
+#pragma warning(disable : 4503)
+// 
 #endif // _MSC_VER > 1000
+
+
 #include "TypeDef.h"
-#if H_MV
+#ifdef _MSC_VER
+#if _MSC_VER <= 1500
+inline Int64 abs (Int64 x) { return _abs64(x); };
+#endif
+#endif
+#if NH_MV
 #include <assert.h>
 #endif
@@ -58,12 +71,10 @@
 // Version information
 // ====================================================================================================================
-
-#if H_MV
+#if NH_MV
 #define NV_VERSION        "14.1"                ///< Current software version
-#define HM_VERSION        "15.0"                ///< 
-#else
-#define NV_VERSION        "15.0"                 ///< Current software version
-#endif
-
+#define HM_VERSION        "16.5"                ///< 
+#else
+#define NV_VERSION        "16.5"                 ///< Current software version
+#endif
 // ====================================================================================================================
 // Platform information
@@ -101,5 +112,5 @@
 #endif
 
-#define NVM_BITS          "[%d bit] ", (sizeof(void*) == 8 ? 64 : 32) ///< used for checking 64-bit O/S
+#define NVM_BITS          "[%d bit] ", (sizeof(Void*) == 8 ? 64 : 32) ///< used for checking 64-bit O/S
 
 #ifndef NULL
@@ -111,36 +122,178 @@
 // ====================================================================================================================
 
-#define _SUMMARY_OUT_               0           ///< print-out PSNR results of all slices to summary.txt
-#define _SUMMARY_PIC_               0           ///< print-out PSNR results for each slice type to summary.txt
-
-#define MAX_GOP                     64          ///< max. value of hierarchical GOP size
-
-#define MAX_NUM_REF_PICS            16          ///< max. number of pictures used for reference
-#define MAX_NUM_REF                 16          ///< max. number of entries in picture reference list
-
-#define MAX_UINT                    0xFFFFFFFFU ///< max. value of unsigned 32-bit integer
-#define MAX_INT                     2147483647  ///< max. value of signed 32-bit integer
-#define MIN_INT                     (-2147483647-1) // < min. value of signed 32-bit integer
-
-#define MAX_INT64                   0x7FFFFFFFFFFFFFFFLL  ///< max. value of signed 64-bit integer
-#define MAX_DOUBLE                  1.7e+308    ///< max. value of double-type value
-
-#define MIN_QP                      0
-#define MAX_QP                      51
-
-#define NOT_VALID                   -1
+static const UInt   MAX_UINT =                            0xFFFFFFFFU; ///< max. value of unsigned 32-bit integer
+static const Int    MAX_INT =                              2147483647; ///< max. value of signed 32-bit integer
+#if NH_MV
+static const Int    MIN_INT =                         (- MAX_INT - 1); ///< max. value of signed 32-bit integer
+#endif
+static const Double MAX_DOUBLE =                             1.7e+308; ///< max. value of Double-type value
+
+// ====================================================================================================================
+// Coding tool configuration
+// ====================================================================================================================
+// Most of these should not be changed - they resolve the meaning of otherwise magic numbers.
+
+static const Int MAX_GOP =                                         64; ///< max. value of hierarchical GOP size
+static const Int MAX_NUM_REF_PICS =                                16; ///< max. number of pictures used for reference
+static const Int MAX_NUM_REF =                                     16; ///< max. number of entries in picture reference list
+static const Int MAX_QP =                                          51;
+static const Int NOT_VALID =                                       -1;
+
+static const Int AMVP_MAX_NUM_CANDS =                               2; ///< AMVP: advanced motion vector prediction - max number of final candidates
+static const Int AMVP_MAX_NUM_CANDS_MEM =                           3; ///< AMVP: advanced motion vector prediction - max number of candidates
+static const Int AMVP_DECIMATION_FACTOR =                           4;
+static const Int MRG_MAX_NUM_CANDS =                                5; ///< MERGE
+
+
+static const Int MAX_TLAYER =                                       7; ///< Explicit temporal layer QP offset - max number of temporal layer
+
+static const Int ADAPT_SR_SCALE =                                   1; ///< division factor for adaptive search range
+
+static const Int MAX_NUM_PICS_IN_SOP =                           1024;
+
+static const Int MAX_NESTING_NUM_OPS =                           1024;
+static const Int MAX_NESTING_NUM_LAYER =                           64;
+
+#if NH_MV
+static const Int MAX_VPS_NUM_HRD_PARAMETERS =                    1024;
+#else
+static const Int MAX_VPS_NUM_HRD_PARAMETERS =                       1;
+#endif
+static const Int MAX_VPS_OP_SETS_PLUS1 =                         1024;
+#if NH_MV
+static const Int MAX_VPS_NUH_LAYER_ID_PLUS1 =                      63;                
+#else
+static const Int MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 =         1;
+#endif
+
+static const Int MAXIMUM_INTRA_FILTERED_WIDTH =                    16;
+static const Int MAXIMUM_INTRA_FILTERED_HEIGHT =                   16;
+
+static const Int MAX_CPB_CNT =                                     32; ///< Upper bound of (cpb_cnt_minus1 + 1)
+#if NH_MV
+static const Int MAX_NUM_LAYER_IDS =                               63;
+#else
+static const Int MAX_NUM_LAYER_IDS =                               64;
+#endif
+
+static const Int COEF_REMAIN_BIN_REDUCTION =                        3; ///< indicates the level at which the VLC transitions from Golomb-Rice to TU+EG(k)
+
+static const Int CU_DQP_TU_CMAX =                                   5; ///< max number bins for truncated unary
+static const Int CU_DQP_EG_k =                                      0; ///< expgolomb order
+
+static const Int SBH_THRESHOLD =                                    4; ///< value of the fixed SBH controlling threshold
+
+static const Int C1FLAG_NUMBER =                                    8; // maximum number of largerThan1 flag coded in one chunk:  16 in HM5
+static const Int C2FLAG_NUMBER =                                    1; // maximum number of largerThan2 flag coded in one chunk:  16 in HM5
+
+static const Int MAX_NUM_VPS =                                     16;
+static const Int MAX_NUM_SPS =                                     16;
+static const Int MAX_NUM_PPS =                                     64;
+
+
+static const Int MLS_GRP_NUM =                                     64; ///< Max number of coefficient groups, max(16, 64)
+static const Int MLS_CG_LOG2_WIDTH =                                2;
+static const Int MLS_CG_LOG2_HEIGHT =                               2;
+static const Int MLS_CG_SIZE =                                      4; ///< Coefficient group size of 4x4; = MLS_CG_LOG2_WIDTH + MLS_CG_LOG2_HEIGHT
+
+#if ADAPTIVE_QP_SELECTION
+static const Int ARL_C_PRECISION =                                  7; ///< G382: 7-bit arithmetic precision
+static const Int LEVEL_RANGE =                                     30; ///< G382: max coefficient level in statistics collection
+#endif
+
+static const Int RVM_VCEGAM10_M =                                   4;
+
+static const Int FAST_UDI_MAX_RDMODE_NUM =                         35; ///< maximum number of RD comparison in fast-UDI estimation loop
+
+static const Int NUM_INTRA_MODE =                                  36;
+static const Int PLANAR_IDX =                                       0;
+static const Int VER_IDX =                                         26; ///< index for intra VERTICAL   mode
+static const Int HOR_IDX =                                         10; ///< index for intra HORIZONTAL mode
+static const Int DC_IDX =                                           1; ///< index for intra DC mode
+static const Int NUM_CHROMA_MODE =                                  5; ///< total number of chroma modes
+static const Int DM_CHROMA_IDX =                                   36; ///< chroma mode index for derived from luma intra mode
+
+static const Int MDCS_ANGLE_LIMIT =                                 4; ///< 0 = Horizontal/vertical only, 1 = Horizontal/vertical +/- 1, 2 = Horizontal/vertical +/- 2 etc...
+static const Int MDCS_MAXIMUM_WIDTH =                               8; ///< (measured in pixels) TUs with width greater than this can only use diagonal scan
+static const Int MDCS_MAXIMUM_HEIGHT =                              8; ///< (measured in pixels) TUs with height greater than this can only use diagonal scan
+
+
+static const Int LOG2_MAX_NUM_COLUMNS_MINUS1 =                      7;
+static const Int LOG2_MAX_NUM_ROWS_MINUS1 =                         7;
+
+static const Int CABAC_INIT_PRESENT_FLAG =                          1;
+
+static const Int LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS =   4;
+static const Int CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS = 8;
+
+static const Int MAX_NUM_LONG_TERM_REF_PICS =                      33;
+static const Int NUM_LONG_TERM_REF_PIC_SPS =                        0;
+
+
+static const Int MAX_QP_OFFSET_LIST_SIZE =                          6; ///< Maximum size of QP offset list is 6 entries
+
+// Cost mode support
+static const Int LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP =      0; ///< QP to use for lossless coding.
+static const Int LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME =4; ///< QP' to use for mixed_lossy_lossless coding.
+
+static const Int RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS =     4;
+static const Int RExt__GOLOMB_RICE_INCREMENT_DIVISOR =              4;
+
+static const Int RExt__PREDICTION_WEIGHTING_ANALYSIS_DC_PRECISION = 0; ///< Additional fixed bit precision used during encoder-side weighting prediction analysis. Currently only used when high_precision_prediction_weighting_flag is set, for backwards compatibility reasons.
+
+static const Int MAX_TIMECODE_SEI_SETS =                            3; ///< Maximum number of time sets
+
+static const Int MAX_CU_DEPTH =                                     6; ///< log2(CTUSize)
+static const Int MAX_CU_SIZE =                                     64; ///< = 1<<(MAX_CU_DEPTH)
+static const Int MIN_PU_SIZE =                                      4;
+static const Int MIN_TU_SIZE =                                      4;
+static const Int MAX_TU_SIZE =                                     32;
+static const Int MAX_NUM_PART_IDXS_IN_CTU_WIDTH = MAX_CU_SIZE/MIN_PU_SIZE; ///< maximum number of partition indices across the width of a CTU (or height of a CTU)
+static const Int SCALING_LIST_REM_NUM =                             6;
+
+static const Int QUANT_SHIFT =                                     14; ///< Q(4) = 2^14
+static const Int IQUANT_SHIFT =                                     6;
+static const Int SCALE_BITS =                                      15; ///< For fractional bit estimates in RDOQ
+
+static const Int SCALING_LIST_NUM = MAX_NUM_COMPONENT * NUMBER_OF_PREDICTION_MODES; ///< list number for quantization matrix
+
+static const Int SCALING_LIST_START_VALUE =                        8 ; ///< start value for dpcm mode
+static const Int MAX_MATRIX_COEF_NUM =                            64 ; ///< max coefficient number for quantization matrix
+static const Int MAX_MATRIX_SIZE_NUM =                             8 ; ///< max size number for quantization matrix
+static const Int SCALING_LIST_BITS =                               8 ; ///< bit depth of scaling list entries
+static const Int LOG2_SCALING_LIST_NEUTRAL_VALUE =                 4 ; ///< log2 of the value that, when used in a scaling list, has no effect on quantisation
+static const Int SCALING_LIST_DC =                                16 ; ///< default DC value
+
+static const Int CONTEXT_STATE_BITS =                              6 ;
+static const Int LAST_SIGNIFICANT_GROUPS =                        10 ;
+
+#if NH_MV
+static const Int  MAX_VPS_NUM_ADD_LAYER_SETS =                  1024 ;
+static const Int  MAX_NUM_SCALABILITY_TYPES =                     16 ;
+static const Int  ENC_CFG_CONSOUT_SPACE =                         34 ;           
+static const Int  MAX_NUM_LAYERS =                                63 ;
+static const Int  MAX_VPS_PROFILE_TIER_LEVEL =                    64 ;
+static const Int  MAX_VPS_ADD_OUTPUT_LAYER_SETS =               1024 ;
+static const Int  MAX_VPS_OUTPUTLAYER_SETS =  MAX_VPS_ADD_OUTPUT_LAYER_SETS + MAX_VPS_OP_SETS_PLUS1 + MAX_VPS_OP_SETS_PLUS1 ;
+static const Int  MAX_NUM_VIDEO_SIGNAL_INFO =                     16 ;
+static const Int  MAX_NUM_SCALED_REF_LAYERS =     MAX_NUM_LAYERS - 1 ; 
+#endif
 
 // ====================================================================================================================
 // Macro functions
 // ====================================================================================================================
-extern Int g_bitDepthY;
-extern Int g_bitDepthC;
-
-/** clip x, such that 0 <= x <= #g_maxLumaVal */
-template <typename T> inline T ClipY(T x) { return std::min<T>(T((1 << g_bitDepthY)-1), std::max<T>( T(0), x)); }
-template <typename T> inline T ClipC(T x) { return std::min<T>(T((1 << g_bitDepthC)-1), std::max<T>( T(0), x)); }
-
-/** clip a, such that minVal <= a <= maxVal */
-template <typename T> inline T Clip3( T minVal, T maxVal, T a) { return std::min<T> (std::max<T> (minVal, a) , maxVal); }  ///< general min/max clip
+
+template <typename T> inline T Clip3 (const T minVal, const T maxVal, const T a) { return std::min<T> (std::max<T> (minVal, a) , maxVal); }  ///< general min/max clip
+template <typename T> inline T ClipBD(const T x, const Int bitDepth)             { return Clip3(T(0), T((1 << bitDepth)-1), x);           }
+
+template <typename T> inline Void Check3( T minVal, T maxVal, T a)
+{
+  if ((a > maxVal) || (a < minVal))
+  {
+    std::cerr << "ERROR: Range check " << minVal << " >= " << a << " <= " << maxVal << " failed" << std::endl;
+    assert(false);
+    exit(1);
+  }
+}  ///< general min/max clip
 
 #define DATA_ALIGN                  1                                                                 ///< use 32-bit aligned malloc/free
@@ -159,5 +312,16 @@
 }
 
-#if H_MV
+template <typename ValueType> inline ValueType leftShift       (const ValueType value, const Int shift) { return (shift >= 0) ? ( value                                  << shift) : ( value                                   >> -shift); }
+template <typename ValueType> inline ValueType rightShift      (const ValueType value, const Int shift) { return (shift >= 0) ? ( value                                  >> shift) : ( value                                   << -shift); }
+template <typename ValueType> inline ValueType leftShift_round (const ValueType value, const Int shift) { return (shift >= 0) ? ( value                                  << shift) : ((value + (ValueType(1) << (-shift - 1))) >> -shift); }
+template <typename ValueType> inline ValueType rightShift_round(const ValueType value, const Int shift) { return (shift >= 0) ? ((value + (ValueType(1) << (shift - 1))) >> shift) : ( value                                   << -shift); }
+#if O0043_BEST_EFFORT_DECODING
+// when shift = 0, returns value
+// when shift = 1, (value + 0 + value[1]) >> 1
+// when shift = 2, (value + 1 + value[2]) >> 2
+// when shift = 3, (value + 3 + value[3]) >> 3
+template <typename ValueType> inline ValueType rightShiftEvenRounding(const ValueType value, const UInt shift) { return (shift == 0) ? value : ((value + (1<<(shift-1))-1 + ((value>>shift)&1)) >> shift) ; }
+#endif
+#if NH_MV
 
 #define AOF( exp )                  \
@@ -195,138 +359,30 @@
 }
 
-#define RemoveBitIncrement( exp ) ( exp >> ( g_bitDepthY - 8 ) )
-
-#endif
-
-// ====================================================================================================================
-// Coding tool configuration
-// ====================================================================================================================
-
-// AMVP: advanced motion vector prediction
-#define AMVP_MAX_NUM_CANDS          2           ///< max number of final candidates
-#define AMVP_MAX_NUM_CANDS_MEM      3           ///< max number of candidates
-// MERGE
-#define MRG_MAX_NUM_CANDS           5
+#define RemoveBitIncrement( exp ) ( exp >> ( REN_BIT_DEPTH - 8 ) )
+
+#endif
+
 #if H_3D_IV_MERGE
 #define MRG_MAX_NUM_CANDS_MEM       (MRG_MAX_NUM_CANDS+1) // one extra for inter-view motion prediction
 #endif
-// Reference memory management
-#define DYN_REF_FREE                0           ///< dynamic free of reference memories
-
-// Explicit temporal layer QP offset
-#define MAX_TLAYER                  7           ///< max number of temporal layer
-#define HB_LAMBDA_FOR_LDC           1           ///< use of B-style lambda for non-key pictures in low-delay mode
-
-// Fast estimation of generalized B in low-delay mode
-#define GPB_SIMPLE                  1           ///< Simple GPB mode
-#if     GPB_SIMPLE
-#define GPB_SIMPLE_UNI              1           ///< Simple mode for uni-direction
-#endif
-
-// Fast ME using smoother MV assumption
-#define FASTME_SMOOTHER_MV          1           ///< reduce ME time using faster option
-
-// Adaptive search range depending on POC difference
-#define ADAPT_SR_SCALE              1           ///< division factor for adaptive search range
-
-#define CLIP_TO_709_RANGE           0
-
-// Early-skip threshold (encoder)
-#define EARLY_SKIP_THRES            1.50        ///< if RD < thres*avg[BestSkipRD]
-
-
-#define MAX_CHROMA_FORMAT_IDC      3
-
-// TODO: Existing names used for the different NAL unit types can be altered to better reflect the names in the spec.
-//       However, the names in the spec are not yet stable at this point. Once the names are stable, a cleanup 
-//       effort can be done without use of macros to alter the names used to indicate the different NAL unit types.
-enum NalUnitType
-{
-  NAL_UNIT_CODED_SLICE_TRAIL_N = 0,   // 0
-  NAL_UNIT_CODED_SLICE_TRAIL_R,   // 1
-  
-  NAL_UNIT_CODED_SLICE_TSA_N,     // 2
-  NAL_UNIT_CODED_SLICE_TSA_R,       // 3
-  
-  NAL_UNIT_CODED_SLICE_STSA_N,    // 4
-  NAL_UNIT_CODED_SLICE_STSA_R,    // 5
-
-  NAL_UNIT_CODED_SLICE_RADL_N,    // 6
-  NAL_UNIT_CODED_SLICE_RADL_R,      // 7
-  
-  NAL_UNIT_CODED_SLICE_RASL_N,    // 8
-  NAL_UNIT_CODED_SLICE_RASL_R,      // 9
-
-  NAL_UNIT_RESERVED_VCL_N10,
-  NAL_UNIT_RESERVED_VCL_R11,
-  NAL_UNIT_RESERVED_VCL_N12,
-  NAL_UNIT_RESERVED_VCL_R13,
-  NAL_UNIT_RESERVED_VCL_N14,
-  NAL_UNIT_RESERVED_VCL_R15,
-
-  NAL_UNIT_CODED_SLICE_BLA_W_LP,    // 16
-  NAL_UNIT_CODED_SLICE_BLA_W_RADL,  // 17
-  NAL_UNIT_CODED_SLICE_BLA_N_LP,  // 18
-  NAL_UNIT_CODED_SLICE_IDR_W_RADL,  // 19
-  NAL_UNIT_CODED_SLICE_IDR_N_LP,  // 20
-  NAL_UNIT_CODED_SLICE_CRA,       // 21
-  NAL_UNIT_RESERVED_IRAP_VCL22,
-  NAL_UNIT_RESERVED_IRAP_VCL23,
-
-  NAL_UNIT_RESERVED_VCL24,
-  NAL_UNIT_RESERVED_VCL25,
-  NAL_UNIT_RESERVED_VCL26,
-  NAL_UNIT_RESERVED_VCL27,
-  NAL_UNIT_RESERVED_VCL28,
-  NAL_UNIT_RESERVED_VCL29,
-  NAL_UNIT_RESERVED_VCL30,
-  NAL_UNIT_RESERVED_VCL31,
-
-  NAL_UNIT_VPS,                   // 32
-  NAL_UNIT_SPS,                   // 33
-  NAL_UNIT_PPS,                   // 34
-  NAL_UNIT_ACCESS_UNIT_DELIMITER, // 35
-  NAL_UNIT_EOS,                   // 36
-  NAL_UNIT_EOB,                   // 37
-  NAL_UNIT_FILLER_DATA,           // 38
-  NAL_UNIT_PREFIX_SEI,              // 39
-  NAL_UNIT_SUFFIX_SEI,              // 40
-  NAL_UNIT_RESERVED_NVCL41,
-  NAL_UNIT_RESERVED_NVCL42,
-  NAL_UNIT_RESERVED_NVCL43,
-  NAL_UNIT_RESERVED_NVCL44,
-  NAL_UNIT_RESERVED_NVCL45,
-  NAL_UNIT_RESERVED_NVCL46,
-  NAL_UNIT_RESERVED_NVCL47,
-  NAL_UNIT_UNSPECIFIED_48,
-  NAL_UNIT_UNSPECIFIED_49,
-  NAL_UNIT_UNSPECIFIED_50,
-  NAL_UNIT_UNSPECIFIED_51,
-  NAL_UNIT_UNSPECIFIED_52,
-  NAL_UNIT_UNSPECIFIED_53,
-  NAL_UNIT_UNSPECIFIED_54,
-  NAL_UNIT_UNSPECIFIED_55,
-  NAL_UNIT_UNSPECIFIED_56,
-  NAL_UNIT_UNSPECIFIED_57,
-  NAL_UNIT_UNSPECIFIED_58,
-  NAL_UNIT_UNSPECIFIED_59,
-  NAL_UNIT_UNSPECIFIED_60,
-  NAL_UNIT_UNSPECIFIED_61,
-  NAL_UNIT_UNSPECIFIED_62,
-  NAL_UNIT_UNSPECIFIED_63,
-  NAL_UNIT_INVALID,
-};
-
-#if H_3D
+
+
+#if NH_3D
 //PICYUV
 #define PICYUV_PAD         16
 
 //RENDERER
-#define REN_LUMA_MARGIN   ( g_uiMaxCUWidth + PICYUV_PAD )
+
+
+#define REN_BIT_DEPTH     8
+#define REN_LUMA_MARGIN   ( PICYUV_PAD + 1 ) // + g_uiMaxCuWidth instead of 1 ???
 #define REN_VDWEIGHT_PREC  8
 #define REN_IS_FILLED     ( 1 << REN_VDWEIGHT_PREC )
-#define REN_USED_PEL       ( (1 << g_bitDepthY) - 1 )
+#define REN_USED_PEL       ( (1 << REN_BIT_DEPTH) - 1 )
 #define REN_UNUSED_PEL     0
 #define REN_IS_HOLE        0
+#if NH_3D_VSO
+#define ENC_INTERNAL_BIT_DEPTH  REN_BIT_DEPTH // consider making this a variable
+#endif
 
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -65,5 +65,5 @@
 }
 
-const UChar ContextModel::m_aucNextStateMPS[ 128 ] =
+const UChar ContextModel::m_aucNextStateMPS[ ContextModel::m_totalStates ] =
 {
   2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
@@ -77,5 +77,5 @@
 };
 
-const UChar ContextModel::m_aucNextStateLPS[ 128 ] =
+const UChar ContextModel::m_aucNextStateLPS[ ContextModel::m_totalStates ] =
 {
   1, 0, 0, 1, 2, 3, 4, 5, 4, 5, 8, 9, 8, 9, 10, 11,
@@ -90,9 +90,9 @@
 
 #if FAST_BIT_EST
-UChar ContextModel::m_nextState[128][2];
+UChar ContextModel::m_nextState[ ContextModel::m_totalStates ][2 /*MPS = [0|1]*/];
 
 Void ContextModel::buildNextStateTable()
 {
-  for (Int i = 0; i < 128; i++)
+  for (Int i = 0; i < ContextModel::m_totalStates; i++)
   {
     for (Int j = 0; j < 2; j++)
@@ -104,5 +104,5 @@
 #endif
 
-const Int ContextModel::m_entropyBits[128] =
+const Int ContextModel::m_entropyBits[ ContextModel::m_totalStates ] =
 {
 #if FAST_BIT_EST
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,6 +37,6 @@
 */
 
-#ifndef __CONTEXT_MODEL__
-#define __CONTEXT_MODEL__
+#ifndef __CONTEXTMODEL__
+#define __CONTEXTMODEL__
 
 #if _MSC_VER > 1000
@@ -45,4 +45,5 @@
 
 #include "CommonDef.h"
+#include "TComRom.h"
 
 //! \ingroup TLibCommon
@@ -59,23 +60,23 @@
   ContextModel  ()                        { m_ucState = 0; m_binsCoded = 0; }
   ~ContextModel ()                        {}
-  
+
   UChar getState  ()                { return ( m_ucState >> 1 ); }                    ///< get current state
   UChar getMps    ()                { return ( m_ucState  & 1 ); }                    ///< get curret MPS
   Void  setStateAndMps( UChar ucState, UChar ucMPS) { m_ucState = (ucState << 1) + ucMPS; } ///< set state and MPS
-  
+
   Void init ( Int qp, Int initValue );   ///< initialize state with initial probability
-  
+
   Void updateLPS ()
   {
     m_ucState = m_aucNextStateLPS[ m_ucState ];
   }
-  
+
   Void updateMPS ()
   {
     m_ucState = m_aucNextStateMPS[ m_ucState ];
   }
-  
+
   Int getEntropyBits(Short val) { return m_entropyBits[m_ucState ^ val]; }
-    
+
 #if FAST_BIT_EST
   Void update( Int binVal )
@@ -88,12 +89,14 @@
   Void setBinsCoded(UInt val)   { m_binsCoded = val;  }
   UInt getBinsCoded()           { return m_binsCoded;   }
-  
+
 private:
   UChar         m_ucState;                                                                  ///< internal state variable
-  static const  UChar m_aucNextStateMPS[ 128 ];
-  static const  UChar m_aucNextStateLPS[ 128 ];
-  static const Int m_entropyBits[ 128 ];
+
+  static const  UInt  m_totalStates = (1 << CONTEXT_STATE_BITS) * 2; //*2 for MPS = [0|1]
+  static const  UChar m_aucNextStateMPS[m_totalStates];
+  static const  UChar m_aucNextStateLPS[m_totalStates];
+  static const  Int   m_entropyBits    [m_totalStates];
 #if FAST_BIT_EST
-  static UChar m_nextState[128][2];
+  static UChar m_nextState[m_totalStates][2 /*MPS = [0|1]*/];
 #endif
   UInt          m_binsCoded;
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -60,14 +60,14 @@
 
 /**
- * Initialize 3D buffer with respect to slicetype, QP and given initial probability table
+ * Initialize 3D buffer with respect to slice type, QP and given initial probability table
  *
- * \param  eSliceType      slice type
- * \param  iQp             input QP value
- * \param  psCtxModel      given probability table
+ * \param  sliceType      slice type
+ * \param  qp             input QP value
+ * \param  ctxModel       given probability table
  */
 Void ContextModel3DBuffer::initBuffer( SliceType sliceType, Int qp, UChar* ctxModel )
 {
   ctxModel += sliceType * m_sizeXYZ;
-  
+
   for ( Int n = 0; n < m_sizeXYZ; n++ )
   {
@@ -95,5 +95,5 @@
 
     // Map the 64 CABAC states to their corresponding probability values
-    static Double aStateToProbLPS[] = {0.50000000, 0.47460857, 0.45050660, 0.42762859, 0.40591239, 0.38529900, 0.36573242, 0.34715948, 0.32952974, 0.31279528, 0.29691064, 0.28183267, 0.26752040, 0.25393496, 0.24103941, 0.22879875, 0.21717969, 0.20615069, 0.19568177, 0.18574449, 0.17631186, 0.16735824, 0.15885931, 0.15079198, 0.14313433, 0.13586556, 0.12896592, 0.12241667, 0.11620000, 0.11029903, 0.10469773, 0.09938088, 0.09433404, 0.08954349, 0.08499621, 0.08067986, 0.07658271, 0.07269362, 0.06900203, 0.06549791, 0.06217174, 0.05901448, 0.05601756, 0.05317283, 0.05047256, 0.04790942, 0.04547644, 0.04316702, 0.04097487, 0.03889405, 0.03691890, 0.03504406, 0.03326442, 0.03157516, 0.02997168, 0.02844963, 0.02700488, 0.02563349, 0.02433175, 0.02309612, 0.02192323, 0.02080991, 0.01975312, 0.01875000};
+    static const Double aStateToProbLPS[] = {0.50000000, 0.47460857, 0.45050660, 0.42762859, 0.40591239, 0.38529900, 0.36573242, 0.34715948, 0.32952974, 0.31279528, 0.29691064, 0.28183267, 0.26752040, 0.25393496, 0.24103941, 0.22879875, 0.21717969, 0.20615069, 0.19568177, 0.18574449, 0.17631186, 0.16735824, 0.15885931, 0.15079198, 0.14313433, 0.13586556, 0.12896592, 0.12241667, 0.11620000, 0.11029903, 0.10469773, 0.09938088, 0.09433404, 0.08954349, 0.08499621, 0.08067986, 0.07658271, 0.07269362, 0.06900203, 0.06549791, 0.06217174, 0.05901448, 0.05601756, 0.05317283, 0.05047256, 0.04790942, 0.04547644, 0.04316702, 0.04097487, 0.03889405, 0.03691890, 0.03504406, 0.03326442, 0.03157516, 0.02997168, 0.02844963, 0.02700488, 0.02563349, 0.02433175, 0.02309612, 0.02192323, 0.02080991, 0.01975312, 0.01875000};
 
     Double probLPS          = aStateToProbLPS[ m_contextModel[ n ].getState() ];
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,9 +36,8 @@
 */
 
-#ifndef _HM_CONTEXT_MODEL_3DBUFFER_H_
-#define _HM_CONTEXT_MODEL_3DBUFFER_H_
+#ifndef __CONTEXTMODEL3DBUFFER__
+#define __CONTEXTMODEL3DBUFFER__
 
 #include <stdio.h>
-#include <assert.h>
 #include <memory.h>
 
@@ -61,9 +60,9 @@
   const UInt    m_sizeXY;       ///< X times Y size of 3D buffer
   const UInt    m_sizeXYZ;      ///< total size of 3D buffer
-  
+
 public:
   ContextModel3DBuffer  ( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX, ContextModel *basePtr, Int &count );
   ~ContextModel3DBuffer () {}
-  
+
   // access functions
   ContextModel& get( UInt uiZ, UInt uiY, UInt uiX )
@@ -79,13 +78,13 @@
     return &m_contextModel[ uiZ * m_sizeXY ];
   }
-  
+
   // initialization & copy functions
   Void initBuffer( SliceType eSliceType, Int iQp, UChar* ctxModel );          ///< initialize 3D buffer by slice type & QP
-  
+
   UInt calcCost( SliceType sliceType, Int qp, UChar* ctxModel );      ///< determine cost of choosing a probability table based on current probabilities
   /** copy from another buffer
    * \param src buffer to copy from
    */
-  Void copyFrom( ContextModel3DBuffer* src )
+  Void copyFrom( const ContextModel3DBuffer* src )
   {
     assert( m_sizeXYZ == src->m_sizeXYZ );
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextTables.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/ContextTables.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -61,30 +61,95 @@
 #define NUM_PRED_MODE_CTX             1       ///< number of context models for prediction mode
 
-#define NUM_ADI_CTX                   1       ///< number of context models for intra prediction
+#define NUM_INTRA_PREDICT_CTX         1       ///< number of context models for intra prediction
 
 #define NUM_CHROMA_PRED_CTX           2       ///< number of context models for intra prediction (chroma)
 #define NUM_INTER_DIR_CTX             5       ///< number of context models for inter prediction direction
 #define NUM_MV_RES_CTX                2       ///< number of context models for motion vector difference
+#define NUM_CHROMA_QP_ADJ_FLAG_CTX    1       ///< number of context models for chroma_qp_adjustment_flag
+#define NUM_CHROMA_QP_ADJ_IDC_CTX     1       ///< number of context models for chroma_qp_adjustment_idc
 
 #define NUM_REF_NO_CTX                2       ///< number of context models for reference index
 #define NUM_TRANS_SUBDIV_FLAG_CTX     3       ///< number of context models for transform subdivision flags
-#define NUM_QT_CBF_CTX                4       ///< number of context models for QT CBF
 #define NUM_QT_ROOT_CBF_CTX           1       ///< number of context models for QT ROOT CBF
 #define NUM_DELTA_QP_CTX              3       ///< number of context models for dQP
 
 #define NUM_SIG_CG_FLAG_CTX           2       ///< number of context models for MULTI_LEVEL_SIGNIFICANCE
-
-#define NUM_SIG_FLAG_CTX              42      ///< number of context models for sig flag
-#define NUM_SIG_FLAG_CTX_LUMA         27      ///< number of context models for luma sig flag
-#define NUM_SIG_FLAG_CTX_CHROMA       15      ///< number of context models for chroma sig flag
+#define NUM_EXPLICIT_RDPCM_FLAG_CTX   1       ///< number of context models for the flag which specifies whether to use RDPCM on inter coded residues
+#define NUM_EXPLICIT_RDPCM_DIR_CTX    1       ///< number of context models for the flag which specifies which RDPCM direction is used on inter coded residues
+
+//--------------------------------------------------------------------------------------------------
+
+// context size definitions for significance map
+
+#define NUM_SIG_FLAG_CTX_LUMA        28       ///< number of context models for luma sig flag
+#define NUM_SIG_FLAG_CTX_CHROMA      16       ///< number of context models for chroma sig flag
+
+//                                                                                                           |----Luma-----|  |---Chroma----|
+static const UInt significanceMapContextSetStart         [MAX_NUM_CHANNEL_TYPE][CONTEXT_NUMBER_OF_TYPES] = { {0,  9, 21, 27}, {0,  9, 12, 15} };
+static const UInt significanceMapContextSetSize          [MAX_NUM_CHANNEL_TYPE][CONTEXT_NUMBER_OF_TYPES] = { {9, 12,  6,  1}, {9,  3,  3,  1} };
+static const UInt nonDiagonalScan8x8ContextOffset        [MAX_NUM_CHANNEL_TYPE]                          = {  6,               0              };
+static const UInt notFirstGroupNeighbourhoodContextOffset[MAX_NUM_CHANNEL_TYPE]                          = {  3,               0              };
+
+//------------------
+
+#define NEIGHBOURHOOD_00_CONTEXT_1_THRESHOLD_4x4  3
+#define NEIGHBOURHOOD_00_CONTEXT_2_THRESHOLD_4x4  1
+
+//------------------
+
+#define FIRST_SIG_FLAG_CTX_LUMA                   0
+#define FIRST_SIG_FLAG_CTX_CHROMA     (FIRST_SIG_FLAG_CTX_LUMA + NUM_SIG_FLAG_CTX_LUMA)
+
+#define NUM_SIG_FLAG_CTX              (NUM_SIG_FLAG_CTX_LUMA + NUM_SIG_FLAG_CTX_CHROMA)       ///< number of context models for sig flag
+
+//--------------------------------------------------------------------------------------------------
+
+// context size definitions for last significant coefficient position
+
+#define NUM_CTX_LAST_FLAG_SETS         2
 
 #define NUM_CTX_LAST_FLAG_XY          15      ///< number of context models for last coefficient position
 
-#define NUM_ONE_FLAG_CTX              24      ///< number of context models for greater than 1 flag
-#define NUM_ONE_FLAG_CTX_LUMA         16      ///< number of context models for greater than 1 flag of luma
-#define NUM_ONE_FLAG_CTX_CHROMA        8      ///< number of context models for greater than 1 flag of chroma
-#define NUM_ABS_FLAG_CTX               6      ///< number of context models for greater than 2 flag
-#define NUM_ABS_FLAG_CTX_LUMA          4      ///< number of context models for greater than 2 flag of luma
-#define NUM_ABS_FLAG_CTX_CHROMA        2      ///< number of context models for greater than 2 flag of chroma
+//--------------------------------------------------------------------------------------------------
+
+// context size definitions for greater-than-one and greater-than-two maps
+
+#define NUM_ONE_FLAG_CTX_PER_SET       4      ///< number of context models for greater than 1 flag in a set
+#define NUM_ABS_FLAG_CTX_PER_SET       1      ///< number of context models for greater than 2 flag in a set
+
+//------------------
+
+#define NUM_CTX_SETS_LUMA              4      ///< number of context model sets for luminance
+#define NUM_CTX_SETS_CHROMA            2      ///< number of context model sets for combined chrominance
+
+#define FIRST_CTX_SET_LUMA             0      ///< index of first luminance context set
+
+//------------------
+
+#define NUM_ONE_FLAG_CTX_LUMA         (NUM_ONE_FLAG_CTX_PER_SET * NUM_CTX_SETS_LUMA)           ///< number of context models for greater than 1 flag of luma
+#define NUM_ONE_FLAG_CTX_CHROMA       (NUM_ONE_FLAG_CTX_PER_SET * NUM_CTX_SETS_CHROMA)         ///< number of context models for greater than 1 flag of chroma
+
+#define NUM_ABS_FLAG_CTX_LUMA         (NUM_ABS_FLAG_CTX_PER_SET * NUM_CTX_SETS_LUMA)           ///< number of context models for greater than 2 flag of luma
+#define NUM_ABS_FLAG_CTX_CHROMA       (NUM_ABS_FLAG_CTX_PER_SET * NUM_CTX_SETS_CHROMA)         ///< number of context models for greater than 2 flag of chroma
+
+#define NUM_ONE_FLAG_CTX              (NUM_ONE_FLAG_CTX_LUMA + NUM_ONE_FLAG_CTX_CHROMA)        ///< number of context models for greater than 1 flag
+#define NUM_ABS_FLAG_CTX              (NUM_ABS_FLAG_CTX_LUMA + NUM_ABS_FLAG_CTX_CHROMA)        ///< number of context models for greater than 2 flag
+
+#define FIRST_CTX_SET_CHROMA          (FIRST_CTX_SET_LUMA + NUM_CTX_SETS_LUMA)                 ///< index of first chrominance context set
+
+//--------------------------------------------------------------------------------------------------
+
+// context size definitions for CBF
+
+#define NUM_QT_CBF_CTX_SETS           2
+
+#define NUM_QT_CBF_CTX_PER_SET        5       ///< number of context models for QT CBF
+
+#define FIRST_CBF_CTX_LUMA            0       ///< index of first luminance CBF context
+
+#define FIRST_CBF_CTX_CHROMA          (FIRST_CBF_CTX_LUMA + NUM_QT_CBF_CTX_PER_SET)  ///< index of first chrominance CBF context
+
+
+//--------------------------------------------------------------------------------------------------
 
 #define NUM_MVP_IDX_CTX               1       ///< number of context models for MVP index
@@ -93,6 +158,7 @@
 #define NUM_SAO_TYPE_IDX_CTX          1       ///< number of context models for SAO type index
 
-#define NUM_TRANSFORMSKIP_FLAG_CTX    1       ///< number of context models for transform skipping 
-#define NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX  1 
+#define NUM_TRANSFORMSKIP_FLAG_CTX    1       ///< number of context models for transform skipping
+
+#define NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX  1
 
 #if H_3D_ARP
@@ -103,4 +169,5 @@
 #define NUM_IC_FLAG_CTX               1       ///< number of context models for illumination compensation flag
 #endif
+#define NUM_CROSS_COMPONENT_PREDICTION_CTX 10
 
 #define CNU                          154      ///< dummy initialization value for unused context models 'Context model Not Used'
@@ -130,5 +197,395 @@
 // initial probability for cu_transquant_bypass flag
 static const UChar
-INIT_CU_TRANSQUANT_BYPASS_FLAG[3][NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX] =
+INIT_CU_TRANSQUANT_BYPASS_FLAG[NUMBER_OF_SLICE_TYPES][NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX] =
+{
+  { 154 },
+  { 154 },
+  { 154 },
+};
+
+// initial probability for split flag
+static const UChar
+INIT_SPLIT_FLAG[NUMBER_OF_SLICE_TYPES][NUM_SPLIT_FLAG_CTX] =
+{
+  { 107,  139,  126, },
+  { 107,  139,  126, },
+  { 139,  141,  157, },
+};
+
+static const UChar
+INIT_SKIP_FLAG[NUMBER_OF_SLICE_TYPES][NUM_SKIP_FLAG_CTX] =
+{
+  { 197,  185,  201, },
+  { 197,  185,  201, },
+  { CNU,  CNU,  CNU, },
+};
+#if H_3D
+static const UChar 
+INIT_DIS_FLAG[3][NUM_DIS_FLAG_CTX] =  
+{
+    { 185 }, 
+    { 185 }, 
+    { 185 },
+};
+static const UChar
+INIT_DIS_TYPE[3][NUM_DIS_TYPE_CTX] = 
+{
+    { 137 }, 
+    { 137 }, 
+    { 137 }, 
+};
+#endif
+static const UChar
+INIT_MERGE_FLAG_EXT[NUMBER_OF_SLICE_TYPES][NUM_MERGE_FLAG_EXT_CTX] =
+{
+  { 154, },
+  { 110, },
+  { CNU, },
+};
+
+static const UChar
+INIT_MERGE_IDX_EXT[NUMBER_OF_SLICE_TYPES][NUM_MERGE_IDX_EXT_CTX] =
+{
+  { 137, },
+  { 122, },
+  { CNU, },
+};
+
+static const UChar
+INIT_PART_SIZE[NUMBER_OF_SLICE_TYPES][NUM_PART_SIZE_CTX] =
+{
+  { 154,  139,  154, 154 },
+  { 154,  139,  154, 154 },
+  { 184,  CNU,  CNU, CNU },
+};
+
+static const UChar
+INIT_PRED_MODE[NUMBER_OF_SLICE_TYPES][NUM_PRED_MODE_CTX] =
+{
+  { 134, },
+  { 149, },
+  { CNU, },
+};
+
+static const UChar
+INIT_INTRA_PRED_MODE[NUMBER_OF_SLICE_TYPES][NUM_INTRA_PREDICT_CTX] =
+{
+  { 183, },
+  { 154, },
+  { 184, },
+};
+
+static const UChar
+INIT_CHROMA_PRED_MODE[NUMBER_OF_SLICE_TYPES][NUM_CHROMA_PRED_CTX] =
+{
+  { 152,  139, },
+  { 152,  139, },
+  {  63,  139, },
+};
+
+static const UChar
+INIT_INTER_DIR[NUMBER_OF_SLICE_TYPES][NUM_INTER_DIR_CTX] =
+{
+  {  95,   79,   63,   31,  31, },
+  {  95,   79,   63,   31,  31, },
+  { CNU,  CNU,  CNU,  CNU, CNU, },
+};
+
+static const UChar
+INIT_MVD[NUMBER_OF_SLICE_TYPES][NUM_MV_RES_CTX] =
+{
+  { 169,  198, },
+  { 140,  198, },
+  { CNU,  CNU, },
+};
+
+static const UChar
+INIT_REF_PIC[NUMBER_OF_SLICE_TYPES][NUM_REF_NO_CTX] =
+{
+  { 153,  153 },
+  { 153,  153 },
+  { CNU,  CNU },
+};
+
+static const UChar
+INIT_DQP[NUMBER_OF_SLICE_TYPES][NUM_DELTA_QP_CTX] =
+{
+  { 154,  154,  154, },
+  { 154,  154,  154, },
+  { 154,  154,  154, },
+};
+
+static const UChar
+INIT_CHROMA_QP_ADJ_FLAG[NUMBER_OF_SLICE_TYPES][NUM_CHROMA_QP_ADJ_FLAG_CTX] =
+{
+  { 154, },
+  { 154, },
+  { 154, },
+};
+
+static const UChar
+INIT_CHROMA_QP_ADJ_IDC[NUMBER_OF_SLICE_TYPES][NUM_CHROMA_QP_ADJ_IDC_CTX] =
+{
+  { 154, },
+  { 154, },
+  { 154, },
+};
+
+//--------------------------------------------------------------------------------------------------
+
+//Initialisation for CBF
+
+//                                 |---------Luminance---------|
+#define BSLICE_LUMA_CBF_CONTEXT     153,  111,  CNU,  CNU,  CNU
+#define PSLICE_LUMA_CBF_CONTEXT     153,  111,  CNU,  CNU,  CNU
+#define ISLICE_LUMA_CBF_CONTEXT     111,  141,  CNU,  CNU,  CNU
+//                                 |--------Chrominance--------|
+#define BSLICE_CHROMA_CBF_CONTEXT   149,   92,  167,  154,  154
+#define PSLICE_CHROMA_CBF_CONTEXT   149,  107,  167,  154,  154
+#define ISLICE_CHROMA_CBF_CONTEXT    94,  138,  182,  154,  154
+
+
+static const UChar
+INIT_QT_CBF[NUMBER_OF_SLICE_TYPES][NUM_QT_CBF_CTX_SETS * NUM_QT_CBF_CTX_PER_SET] =
+{
+  { BSLICE_LUMA_CBF_CONTEXT, BSLICE_CHROMA_CBF_CONTEXT },
+  { PSLICE_LUMA_CBF_CONTEXT, PSLICE_CHROMA_CBF_CONTEXT },
+  { ISLICE_LUMA_CBF_CONTEXT, ISLICE_CHROMA_CBF_CONTEXT },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+static const UChar
+INIT_QT_ROOT_CBF[NUMBER_OF_SLICE_TYPES][NUM_QT_ROOT_CBF_CTX] =
+{
+  {  79, },
+  {  79, },
+  { CNU, },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+//Initialisation for last-significant-position
+
+//                                           |------------------------------Luminance----------------------------------|
+#define BSLICE_LUMA_LAST_POSITION_CONTEXT     125, 110, 124, 110,  95,  94, 125, 111, 111,  79, 125, 126, 111, 111,  79
+#define PSLICE_LUMA_LAST_POSITION_CONTEXT     125, 110,  94, 110,  95,  79, 125, 111, 110,  78, 110, 111, 111,  95,  94
+#define ISLICE_LUMA_LAST_POSITION_CONTEXT     110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111,  79
+//                                           |------------------------------Chrominance--------------------------------|
+#define BSLICE_CHROMA_LAST_POSITION_CONTEXT   108, 123,  93, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU
+#define PSLICE_CHROMA_LAST_POSITION_CONTEXT   108, 123, 108, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU
+#define ISLICE_CHROMA_LAST_POSITION_CONTEXT   108, 123,  63, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU
+
+
+static const UChar
+INIT_LAST[NUMBER_OF_SLICE_TYPES][NUM_CTX_LAST_FLAG_SETS * NUM_CTX_LAST_FLAG_XY] =
+{
+  { BSLICE_LUMA_LAST_POSITION_CONTEXT, BSLICE_CHROMA_LAST_POSITION_CONTEXT },
+  { PSLICE_LUMA_LAST_POSITION_CONTEXT, PSLICE_CHROMA_LAST_POSITION_CONTEXT },
+  { ISLICE_LUMA_LAST_POSITION_CONTEXT, ISLICE_CHROMA_LAST_POSITION_CONTEXT },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+static const UChar
+INIT_SIG_CG_FLAG[NUMBER_OF_SLICE_TYPES][2 * NUM_SIG_CG_FLAG_CTX] =
+{
+  { 121,  140,
+    61,  154,
+  },
+  { 121,  140,
+    61,  154,
+  },
+  {  91,  171,
+    134,  141,
+  },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+//Initialisation for significance map
+
+//                                          |-DC-|  |-----------------4x4------------------|  |------8x8 Diagonal Scan------|  |----8x8 Non-Diagonal Scan----|  |-NxN First group-|  |-NxN Other group-| |-Single context-|
+//                                          |    |  |                                      |  |-First Group-| |-Other Group-|  |-First Group-| |-Other Group-|  |                 |  |                 | |                |
+#define BSLICE_LUMA_SIGNIFICANCE_CONTEXT     170,    154, 139, 153, 139, 123, 123,  63, 124,   166, 183, 140,  136, 153, 154,   166, 183, 140,  136, 153, 154,   166,   183,   140,   136,   153,   154,        140
+#define PSLICE_LUMA_SIGNIFICANCE_CONTEXT     155,    154, 139, 153, 139, 123, 123,  63, 153,   166, 183, 140,  136, 153, 154,   166, 183, 140,  136, 153, 154,   166,   183,   140,   136,   153,   154,        140
+#define ISLICE_LUMA_SIGNIFICANCE_CONTEXT     111,    111, 125, 110, 110,  94, 124, 108, 124,   107, 125, 141,  179, 153, 125,   107, 125, 141,  179, 153, 125,   107,   125,   141,   179,   153,   125,        141
+
+//                                          |-DC-|  |-----------------4x4------------------|  |-8x8 Any group-|  |-NxN Any group-| |-Single context-|
+#define BSLICE_CHROMA_SIGNIFICANCE_CONTEXT   170,    153, 138, 138, 122, 121, 122, 121, 167,   151,  183,  140,   151,  183,  140,        140
+#define PSLICE_CHROMA_SIGNIFICANCE_CONTEXT   170,    153, 123, 123, 107, 121, 107, 121, 167,   151,  183,  140,   151,  183,  140,        140
+#define ISLICE_CHROMA_SIGNIFICANCE_CONTEXT   140,    139, 182, 182, 152, 136, 152, 136, 153,   136,  139,  111,   136,  139,  111,        111
+
+//------------------------------------------------
+
+static const UChar
+INIT_SIG_FLAG[NUMBER_OF_SLICE_TYPES][NUM_SIG_FLAG_CTX] =
+{
+  { BSLICE_LUMA_SIGNIFICANCE_CONTEXT, BSLICE_CHROMA_SIGNIFICANCE_CONTEXT },
+  { PSLICE_LUMA_SIGNIFICANCE_CONTEXT, PSLICE_CHROMA_SIGNIFICANCE_CONTEXT },
+  { ISLICE_LUMA_SIGNIFICANCE_CONTEXT, ISLICE_CHROMA_SIGNIFICANCE_CONTEXT },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+//Initialisation for greater-than-one flags and greater-than-two flags
+
+//                                 |------Set 0-------| |------Set 1-------| |------Set 2-------| |------Set 3-------|
+#define BSLICE_LUMA_ONE_CONTEXT     154, 196, 167, 167,  154, 152, 167, 182,  182, 134, 149, 136,  153, 121, 136, 122
+#define PSLICE_LUMA_ONE_CONTEXT     154, 196, 196, 167,  154, 152, 167, 182,  182, 134, 149, 136,  153, 121, 136, 137
+#define ISLICE_LUMA_ONE_CONTEXT     140,  92, 137, 138,  140, 152, 138, 139,  153,  74, 149,  92,  139, 107, 122, 152
+
+#define BSLICE_LUMA_ABS_CONTEXT     107,                 167,                  91,                 107
+#define PSLICE_LUMA_ABS_CONTEXT     107,                 167,                  91,                 122
+#define ISLICE_LUMA_ABS_CONTEXT     138,                 153,                 136,                 167
+
+//                                 |------Set 4-------| |------Set 5-------|
+#define BSLICE_CHROMA_ONE_CONTEXT   169, 208, 166, 167,  154, 152, 167, 182
+#define PSLICE_CHROMA_ONE_CONTEXT   169, 194, 166, 167,  154, 167, 137, 182
+#define ISLICE_CHROMA_ONE_CONTEXT   140, 179, 166, 182,  140, 227, 122, 197
+
+#define BSLICE_CHROMA_ABS_CONTEXT   107,                 167
+#define PSLICE_CHROMA_ABS_CONTEXT   107,                 167
+#define ISLICE_CHROMA_ABS_CONTEXT   152,                 152
+
+
+//------------------------------------------------
+
+static const UChar
+INIT_ONE_FLAG[NUMBER_OF_SLICE_TYPES][NUM_ONE_FLAG_CTX] =
+{
+  { BSLICE_LUMA_ONE_CONTEXT, BSLICE_CHROMA_ONE_CONTEXT },
+  { PSLICE_LUMA_ONE_CONTEXT, PSLICE_CHROMA_ONE_CONTEXT },
+  { ISLICE_LUMA_ONE_CONTEXT, ISLICE_CHROMA_ONE_CONTEXT },
+};
+
+static const UChar
+INIT_ABS_FLAG[NUMBER_OF_SLICE_TYPES][NUM_ABS_FLAG_CTX] =
+{
+  { BSLICE_LUMA_ABS_CONTEXT, BSLICE_CHROMA_ABS_CONTEXT },
+  { PSLICE_LUMA_ABS_CONTEXT, PSLICE_CHROMA_ABS_CONTEXT },
+  { ISLICE_LUMA_ABS_CONTEXT, ISLICE_CHROMA_ABS_CONTEXT },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+static const UChar
+INIT_MVP_IDX[NUMBER_OF_SLICE_TYPES][NUM_MVP_IDX_CTX] =
+{
+  { 168, },
+  { 168, },
+  { CNU, },
+};
+
+static const UChar
+INIT_SAO_MERGE_FLAG[NUMBER_OF_SLICE_TYPES][NUM_SAO_MERGE_FLAG_CTX] =
+{
+  { 153,  },
+  { 153,  },
+  { 153,  },
+};
+
+static const UChar
+INIT_SAO_TYPE_IDX[NUMBER_OF_SLICE_TYPES][NUM_SAO_TYPE_IDX_CTX] =
+{
+  { 160, },
+  { 185, },
+  { 200, },
+};
+
+static const UChar
+INIT_TRANS_SUBDIV_FLAG[NUMBER_OF_SLICE_TYPES][NUM_TRANS_SUBDIV_FLAG_CTX] =
+{
+  { 224,  167,  122, },
+  { 124,  138,   94, },
+  { 153,  138,  138, },
+};
+
+static const UChar
+INIT_TRANSFORMSKIP_FLAG[NUMBER_OF_SLICE_TYPES][2*NUM_TRANSFORMSKIP_FLAG_CTX] =
+{
+  { 139,  139},
+  { 139,  139},
+  { 139,  139},
+};
+
+static const UChar
+INIT_EXPLICIT_RDPCM_FLAG[NUMBER_OF_SLICE_TYPES][2*NUM_EXPLICIT_RDPCM_FLAG_CTX] =
+{
+  {139, 139},
+  {139, 139},
+  {CNU, CNU}
+};
+
+static const UChar
+INIT_EXPLICIT_RDPCM_DIR[NUMBER_OF_SLICE_TYPES][2*NUM_EXPLICIT_RDPCM_DIR_CTX] =
+{
+  {139, 139},
+  {139, 139},
+  {CNU, CNU}
+};
+
+static const UChar
+INIT_CROSS_COMPONENT_PREDICTION[NUMBER_OF_SLICE_TYPES][NUM_CROSS_COMPONENT_PREDICTION_CTX] =
+{
+  { 154, 154, 154, 154, 154, 154, 154, 154, 154, 154 },
+  { 154, 154, 154, 154, 154, 154, 154, 154, 154, 154 },
+  { 154, 154, 154, 154, 154, 154, 154, 154, 154, 154 },
+};
+
+//! \}
+
+#if H_3D_ARP
+static const UChar 
+INIT_ARPW[3][NUM_ARPW_CTX] = 
+{
+    { 162, 153, 162 },
+    { 162, 153, 162 },
+    { 162, 153, 162 },
+};
+
+#endif
+#if H_3D_IC
+static const UChar 
+INIT_IC_FLAG[3][NUM_IC_FLAG_CTX] =  
+{
+    { 154 },
+    { 154 },
+    { 154 },
+};
+
+#endif
+#if H_3D_DIM
+static const UChar
+INIT_DEPTH_INTRA_MODE[3][NUM_DEPTH_INTRA_MODE_CTX] =
+{
+  { 154, },
+  { 154, },
+  { 154, }
+};
+
+static const UChar 
+INIT_ANGLE_FLAG[3][NUM_ANGLE_FLAG_CTX] =
+{
+  { 154 },
+  { 141 },
+  { 155 },
+};
+
+static const UChar 
+INIT_DDC_FLAG[3][NUM_DDC_FLAG_CTX] =
+{
+  {0 , CNU},
+  {0 , CNU},
+  {64, CNU}
+};
+static const UChar
+INIT_DDC_DATA[3][NUM_DDC_DATA_CTX] = 
 {
   { 154 }, 
@@ -136,276 +593,4 @@
   { 154 }, 
 };
-
-// initial probability for split flag
-static const UChar 
-INIT_SPLIT_FLAG[3][NUM_SPLIT_FLAG_CTX] =  
-{
-  { 107,  139,  126, },
-  { 107,  139,  126, }, 
-  { 139,  141,  157, }, 
-};
-
-static const UChar 
-INIT_SKIP_FLAG[3][NUM_SKIP_FLAG_CTX] =  
-{
-  { 197,  185,  201, }, 
-  { 197,  185,  201, }, 
-  { CNU,  CNU,  CNU, }, 
-};
-#if H_3D
-static const UChar 
-INIT_DIS_FLAG[3][NUM_DIS_FLAG_CTX] =  
-{
-    { 185 }, 
-    { 185 }, 
-    { 185 },
-};
-static const UChar
-INIT_DIS_TYPE[3][NUM_DIS_TYPE_CTX] = 
-{
-    { 137 }, 
-    { 137 }, 
-    { 137 }, 
-};
-#endif
-static const UChar
-INIT_MERGE_FLAG_EXT[3][NUM_MERGE_FLAG_EXT_CTX] = 
-{
-  { 154, }, 
-  { 110, }, 
-  { CNU, }, 
-};
-
-static const UChar 
-INIT_MERGE_IDX_EXT[3][NUM_MERGE_IDX_EXT_CTX] =  
-{
-  { 137, }, 
-  { 122, }, 
-  { CNU, }, 
-};
-
-static const UChar 
-INIT_PART_SIZE[3][NUM_PART_SIZE_CTX] =  
-{
-  { 154,  139,  154,  154 },
-  { 154,  139,  154,  154 },
-  { 184,  CNU,  CNU,  CNU },
-};
-
-static const UChar 
-INIT_PRED_MODE[3][NUM_PRED_MODE_CTX] = 
-{
-  { 134, }, 
-  { 149, }, 
-  { CNU, }, 
-};
-
-static const UChar 
-INIT_INTRA_PRED_MODE[3][NUM_ADI_CTX] = 
-{
-  { 183, }, 
-  { 154, }, 
-  { 184, }, 
-};
-
-static const UChar 
-INIT_CHROMA_PRED_MODE[3][NUM_CHROMA_PRED_CTX] = 
-{
-  { 152,  139, }, 
-  { 152,  139, }, 
-  {  63,  139, }, 
-};
-
-static const UChar 
-INIT_INTER_DIR[3][NUM_INTER_DIR_CTX] = 
-{
-  {  95,   79,   63,   31,  31, }, 
-  {  95,   79,   63,   31,  31, }, 
-  { CNU,  CNU,  CNU,  CNU, CNU, }, 
-};
-
-static const UChar 
-INIT_MVD[3][NUM_MV_RES_CTX] =  
-{
-  { 169,  198, }, 
-  { 140,  198, }, 
-  { CNU,  CNU, }, 
-};
-
-static const UChar 
-INIT_REF_PIC[3][NUM_REF_NO_CTX] =  
-{
-  { 153,  153 }, 
-  { 153,  153 }, 
-  { CNU,  CNU }, 
-};
-
-static const UChar 
-INIT_DQP[3][NUM_DELTA_QP_CTX] = 
-{
-  { 154,  154,  154, }, 
-  { 154,  154,  154, }, 
-  { 154,  154,  154, }, 
-};
-
-static const UChar 
-INIT_QT_CBF[3][2*NUM_QT_CBF_CTX] =  
-{
-  { 153,  111,  CNU,  CNU,   149,   92,  167,  154 },
-  { 153,  111,  CNU,  CNU,   149,  107,  167,  154 },
-  { 111,  141,  CNU,  CNU,    94,  138,  182,  154 },
-};
-
-static const UChar 
-INIT_QT_ROOT_CBF[3][NUM_QT_ROOT_CBF_CTX] = 
-{
-  {  79, }, 
-  {  79, }, 
-  { CNU, }, 
-};
-
-static const UChar 
-INIT_LAST[3][2*NUM_CTX_LAST_FLAG_XY] =  
-{
-  { 125,  110,  124,  110,   95,   94,  125,  111,  111,   79,  125,  126,  111,  111,   79,
-    108,  123,   93,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, 
-  }, 
-  { 125,  110,   94,  110,   95,   79,  125,  111,  110,   78,  110,  111,  111,   95,   94,
-    108,  123,  108,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,
-  }, 
-  { 110,  110,  124,  125,  140,  153,  125,  127,  140,  109,  111,  143,  127,  111,   79, 
-    108,  123,   63,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, 
-  }, 
-};
-
-static const UChar 
-INIT_SIG_CG_FLAG[3][2 * NUM_SIG_CG_FLAG_CTX] =  
-{
-  { 121,  140,  
-    61,  154, 
-  }, 
-  { 121,  140, 
-    61,  154, 
-  }, 
-  {  91,  171,  
-    134,  141, 
-  }, 
-};
-
-static const UChar 
-INIT_SIG_FLAG[3][NUM_SIG_FLAG_CTX] = 
-{
-  { 170,  154,  139,  153,  139,  123,  123,   63,  124,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  170,  153,  138,  138,  122,  121,  122,  121,  167,  151,  183,  140,  151,  183,  140,  }, 
-  { 155,  154,  139,  153,  139,  123,  123,   63,  153,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  170,  153,  123,  123,  107,  121,  107,  121,  167,  151,  183,  140,  151,  183,  140,  }, 
-  { 111,  111,  125,  110,  110,   94,  124,  108,  124,  107,  125,  141,  179,  153,  125,  107,  125,  141,  179,  153,  125,  107,  125,  141,  179,  153,  125,  140,  139,  182,  182,  152,  136,  152,  136,  153,  136,  139,  111,  136,  139,  111,  }, 
-};
-
-static const UChar 
-INIT_ONE_FLAG[3][NUM_ONE_FLAG_CTX] = 
-{
-  { 154,  196,  167,  167,  154,  152,  167,  182,  182,  134,  149,  136,  153,  121,  136,  122,  169,  208,  166,  167,  154,  152,  167,  182, }, 
-  { 154,  196,  196,  167,  154,  152,  167,  182,  182,  134,  149,  136,  153,  121,  136,  137,  169,  194,  166,  167,  154,  167,  137,  182, }, 
-  { 140,   92,  137,  138,  140,  152,  138,  139,  153,   74,  149,   92,  139,  107,  122,  152,  140,  179,  166,  182,  140,  227,  122,  197, }, 
-};
-
-static const UChar 
-INIT_ABS_FLAG[3][NUM_ABS_FLAG_CTX] =  
-{
-  { 107,  167,   91,  107,  107,  167, }, 
-  { 107,  167,   91,  122,  107,  167, }, 
-  { 138,  153,  136,  167,  152,  152, }, 
-};
-
-static const UChar 
-INIT_MVP_IDX[3][NUM_MVP_IDX_CTX] =  
-{
-  { 168 },
-  { 168 },
-  { CNU }, 
-};
-
-static const UChar 
-INIT_SAO_MERGE_FLAG[3][NUM_SAO_MERGE_FLAG_CTX] = 
-{
-  { 153,  }, 
-  { 153,  }, 
-  { 153,  }, 
-};
-
-static const UChar 
-INIT_SAO_TYPE_IDX[3][NUM_SAO_TYPE_IDX_CTX] = 
-{
-  { 160, },
-  { 185, },
-  { 200, },
-};
-
-static const UChar
-INIT_TRANS_SUBDIV_FLAG[3][NUM_TRANS_SUBDIV_FLAG_CTX] =
-{
-  { 224,  167,  122, },
-  { 124,  138,   94, },
-  { 153,  138,  138, },
-};
-
-static const UChar
-INIT_TRANSFORMSKIP_FLAG[3][2*NUM_TRANSFORMSKIP_FLAG_CTX] = 
-{
-  { 139,  139}, 
-  { 139,  139}, 
-  { 139,  139}, 
-};
-
-#if H_3D_ARP
-static const UChar 
-INIT_ARPW[3][NUM_ARPW_CTX] = 
-{
-    { 162, 153, 162 },
-    { 162, 153, 162 },
-    { 162, 153, 162 },
-};
-
-#endif
-#if H_3D_IC
-static const UChar 
-INIT_IC_FLAG[3][NUM_IC_FLAG_CTX] =  
-{
-    { 154 },
-    { 154 },
-    { 154 },
-};
-
-#endif
-#if H_3D_DIM
-static const UChar
-INIT_DEPTH_INTRA_MODE[3][NUM_DEPTH_INTRA_MODE_CTX] =
-{
-  { 154, },
-  { 154, },
-  { 154, }
-};
-
-static const UChar 
-INIT_ANGLE_FLAG[3][NUM_ANGLE_FLAG_CTX] =
-{
-  { 154 },
-  { 141 },
-  { 155 },
-};
-
-static const UChar 
-INIT_DDC_FLAG[3][NUM_DDC_FLAG_CTX] =
-{
-  {0 , CNU},
-  {0 , CNU},
-  {64, CNU}
-};
-static const UChar
-INIT_DDC_DATA[3][NUM_DDC_DATA_CTX] = 
-{
-  { 154 }, 
-  { 154 }, 
-  { 154 }, 
-};
 #if H_3D_DIM_DMM
 static const UChar
@@ -434,7 +619,4 @@
 #endif
 #endif
-
-
-//! \}
 #if H_3D_DIM_SDC
 static const UChar 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/Debug.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/Debug.cpp	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/Debug.cpp	(revision 1200)
@@ -0,0 +1,487 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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.
+ */
+
+/** \file     Debug.cpp
+    \brief    Defines types and objects for environment-variable-based debugging and feature control
+*/
+
+#include "Debug.h"
+#include <algorithm>
+#include <math.h>
+#include "TComDataCU.h"
+#include "TComPic.h"
+#include "TComYuv.h"
+
+static const UInt settingNameWidth  = 66;
+static const UInt settingHelpWidth  = 84;
+static const UInt settingValueWidth = 3;
+
+#if DEBUG_STRING
+// these strings are used to reorder the debug output so that the encoder and decoder match.
+const Char *debug_reorder_data_inter_token[MAX_NUM_COMPONENT+1]
+ = {"Start of channel 0 inter debug\n", "Start of channel 1 inter debug\n", "Start of channel 2 inter debug\n", "End of inter residual debug\n"} ;
+const Char *partSizeToString[NUMBER_OF_PART_SIZES]={"2Nx2N(0)", "2NxN(1)", "Nx2N(2)", "NxN(3)", "2Nx(N/2+3N/2)(4)", "2Nx(3N/2+N/2)(5)", "(N/2+3N/2)x2N(6)", "(3N/2+N/2)x2N(7)"};
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+//EnvVar definition
+
+std::list<std::pair<std::string, std::string> > &EnvVar::getEnvVarList()
+{
+  static std::list<std::pair<std::string, std::string> > varInfoList;
+  return varInfoList;
+}
+
+std::list<EnvVar*> &EnvVar::getEnvVarInUse()
+{
+  static std::list<EnvVar*> varInUseList;
+  return varInUseList;
+}
+
+static inline Void printPair(const std::pair<std::string, std::string> &p)
+{
+  if (p.second=="")
+  {
+    std::cout << "\n" << std::setw(settingNameWidth) << p.first << "\n" << std::endl;
+  }
+  else
+  {
+    std::cout << std::setw(settingNameWidth) << p.first << ":   " << p.second << "\n" << std::endl;
+  }
+}
+
+static inline Void printVal(const EnvVar* env)
+{
+  std::cout << std::setw(settingNameWidth) << env->getName() << " = " << std::setw(settingValueWidth) << env->getInt() << " (string = " << std::setw(15) << env->getString() << ")" << std::endl;
+}
+
+//static inline Bool sameEnvName( const std::pair<std::string, std::string> &a,
+//                                const std::pair<std::string, std::string> &b )
+//{
+//  // only check env name
+//  return (a.first==b.first);
+//}
+
+Void EnvVar::printEnvVar()
+{
+//  getEnvVarList().unique(sameEnvName);
+  if (getEnvVarList().size()!=0)
+  {
+    std::cout << "--- Environment variables:\n" << std::endl;
+    for_each(getEnvVarList().begin(), getEnvVarList().end(), printPair);
+  }
+  std::cout << std::endl;
+}
+
+Void EnvVar::printEnvVarInUse()
+{
+  if (getEnvVarInUse().size()!=0)
+  {
+    std::cout << "RExt Environment variables set as follows: \n" << std::endl;
+    for_each(getEnvVarInUse().begin(), getEnvVarInUse().end(), printVal);
+  }
+  std::cout << std::endl;
+}
+
+EnvVar::EnvVar(const std::string &sName, const std::string &sDefault, const std::string &sHelp) :
+                                                                m_sName(sName),
+                                                                m_sHelp(sHelp),
+                                                                m_sVal(),
+                                                                m_dVal(0),
+                                                                m_iVal(0),
+                                                                m_bSet(false)
+{
+  if (getenv(m_sName.c_str()))
+  {
+    m_sVal = getenv(m_sName.c_str());
+    m_bSet = true;
+    getEnvVarInUse().push_back(this);
+  }
+  else
+  {
+    m_sVal = sDefault;
+  }
+
+  m_dVal = strtod(m_sVal.c_str(), 0);
+  m_iVal = Int(m_dVal);
+
+  getEnvVarList().push_back( std::pair<std::string, std::string>(m_sName, indentNewLines(lineWrap(splitOnSettings(m_sHelp), settingHelpWidth), (settingNameWidth + 4))) );
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+// Debug environment variables:
+
+EnvVar Debug("-- Debugging","","");
+
+EnvVar DebugOptionList::DebugSBAC             ("DEBUG_SBAC",        "0", "Output debug data from SBAC entropy coder (coefficient data etc.)"                              );
+EnvVar DebugOptionList::DebugRQT              ("DEBUG_RQT",         "0", "Output RQT debug data from entropy coder"                                                       );
+EnvVar DebugOptionList::DebugPred             ("DEBUG_PRED",        "0", "Output prediction debug"                                                                        );
+EnvVar DebugOptionList::ForceLumaMode         ("FORCE_LUMA_MODE",   "0", "Force a particular intra direction for Luma (0-34)"                                             );
+EnvVar DebugOptionList::ForceChromaMode       ("FORCE_CHROMA_MODE", "0", "Force a particular intra direction for chroma (0-5)"                                            );
+
+#if DEBUG_STRING
+EnvVar DebugOptionList::DebugString_Structure ("DEBUG_STRUCTURE",   "0", "Produce output on chosen structure                        bit0=intra, bit1=inter");
+EnvVar DebugOptionList::DebugString_Pred      ("DEBUG_PRED",        "0", "Produce output on prediction data.                        bit0=intra, bit1=inter");
+EnvVar DebugOptionList::DebugString_Resi      ("DEBUG_RESI",        "0", "Produce output on residual data.                          bit0=intra, bit1=inter");
+EnvVar DebugOptionList::DebugString_Reco      ("DEBUG_RECO",        "0", "Produce output on reconstructed data.                     bit0=intra, bit1=inter");
+EnvVar DebugOptionList::DebugString_InvTran   ("DEBUG_INV_QT",      "0", "Produce output on inverse-quantiser and transform stages. bit0=intra, bit1=inter");
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+//macro value printing function
+
+Void printMacroSettings()
+{
+  std::cout << "Non-environment-variable-controlled macros set as follows: \n" << std::endl;
+
+  //------------------------------------------------
+
+  //setting macros
+
+  PRINT_CONSTANT(RExt__DECODER_DEBUG_BIT_STATISTICS,                                settingNameWidth, settingValueWidth);
+  PRINT_CONSTANT(RExt__HIGH_BIT_DEPTH_SUPPORT,                                      settingNameWidth, settingValueWidth);
+  PRINT_CONSTANT(RExt__HIGH_PRECISION_FORWARD_TRANSFORM,                            settingNameWidth, settingValueWidth);
+
+  PRINT_CONSTANT(O0043_BEST_EFFORT_DECODING,                                        settingNameWidth, settingValueWidth);
+
+  //------------------------------------------------
+
+  std::cout << std::endl;
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+//Debugging
+
+UInt  g_debugCounter  = 0;
+
+#if DEBUG_ENCODER_SEARCH_BINS
+const UInt debugEncoderSearchBinTargetLine = 0;
+const UInt debugEncoderSearchBinWindow     = 1000000;
+#endif
+
+#if DEBUG_CABAC_BINS
+const UInt debugCabacBinTargetLine = 0;
+const UInt debugCabacBinWindow     = 1000000;
+#endif
+
+Void printSBACCoeffData(  const UInt          lastX,
+                          const UInt          lastY,
+                          const UInt          width,
+                          const UInt          height,
+                          const UInt          chan,
+                          const UInt          absPart,
+                          const UInt          scanIdx,
+                          const TCoeff *const pCoeff,
+                          const Bool          finalEncode
+                        )
+{
+  if (DebugOptionList::DebugSBAC.getInt()!=0 && finalEncode)
+  {
+    std::cout << "Size: " << width << "x" << height << ", Last X/Y: (" << lastX << ", " << lastY << "), absPartIdx: " << absPart << ", scanIdx: " << scanIdx << ", chan: " << chan << "\n";
+    for (Int i=0; i<width*height; i++)
+    {
+      std::cout << std::setw(3) << pCoeff[i];// + dcVal;
+      if (i%width == width-1)
+      {
+        std::cout << "\n";
+      }
+      else
+      {
+        std::cout << ",";
+      }
+    }
+    std::cout << std::endl;
+  }
+}
+
+Void printCbfArray( TComDataCU* pcCU  )
+{
+  const UInt CUSizeInParts = pcCU->getWidth(0)/4;
+  const UInt numValidComp=pcCU->getPic()->getNumberValidComponents();
+  for (UInt ch=0; ch<numValidComp; ch++)
+  {
+    const ComponentID compID=ComponentID(ch);
+    printf("channel: %d\n", ch);
+    for (Int y=0; y<CUSizeInParts; y++)
+    {
+      for (Int x=0; x<CUSizeInParts; x++)
+      {
+        printf(x+1==CUSizeInParts?"%3d\n":"%3d, ", pcCU->getCbf(compID)[g_auiRasterToZscan[y*CUSizeInParts + x]]);
+      }
+    }
+  }
+}
+
+UInt getDecimalWidth(const Double value)
+{
+  return (value == 0) ? 1 : (UInt(floor(log10(fabs(value)))) + ((value < 0) ? 2 : 1));
+                                                               //for the minus sign
+}
+
+UInt getZScanIndex(const UInt x, const UInt y)
+{
+  UInt remainingX = x;
+  UInt remainingY = y;
+  UInt offset     = 0;
+  UInt result     = 0;
+
+  while ((remainingX != 0) || (remainingY != 0))
+  {
+    result |= ((remainingX & 0x1) << offset) | ((remainingY & 0x1) << (offset + 1));
+
+    remainingX >>= 1;
+    remainingY >>= 1;
+    offset      += 2;
+  }
+
+  return result;
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+//String manipulation functions for aligning and wrapping printed text
+
+
+std::string splitOnSettings(const std::string &input)
+{
+  std::string result = input;
+
+  std::string::size_type searchFromPosition = 0;
+
+  while (searchFromPosition < result.length())
+  {
+    //find the " = " that is used to define each setting
+    std::string::size_type equalsPosition = result.find(" = ", searchFromPosition);
+
+    if (equalsPosition == std::string::npos)
+    {
+      break;
+    }
+
+    //then find the end of the numeric characters
+    std::string::size_type splitPosition = result.find_last_of("1234567890", equalsPosition);
+
+    //then find the last space before the first numeric character...
+    if (splitPosition != std::string::npos)
+    {
+      splitPosition = result.find_last_of(' ', splitPosition);
+    }
+
+    //...and replace it with a new line
+    if (splitPosition != std::string::npos)
+    {
+      result.replace(splitPosition, 1, 1, '\n');
+    }
+
+    //start the next search from the end of the " = " string
+    searchFromPosition = (equalsPosition + 3);
+  }
+
+  return result;
+}
+
+
+std::string lineWrap(const std::string &input, const UInt maximumLineLength)
+{
+  if (maximumLineLength == 0)
+  {
+    return input;
+  }
+  std::string result = input;
+
+  std::string::size_type lineStartPosition = result.find_first_not_of(' '); //don't wrap any leading spaces in the string
+
+  while (lineStartPosition != std::string::npos)
+  {
+    //------------------------------------------------
+
+    const std::string::size_type searchFromPosition = lineStartPosition + maximumLineLength;
+
+    if (searchFromPosition >= result.length())
+    {
+      break;
+    }
+
+    //------------------------------------------------
+
+    //first check to see if there is another new line character before the maximum line length
+    //we can't use find for this unfortunately because it doesn't take both a beginning and an end for its search range
+    std::string::size_type nextLineStartPosition = std::string::npos;
+    for (std::string::size_type currentPosition = lineStartPosition; currentPosition <= searchFromPosition; currentPosition++)
+    {
+      if (result[currentPosition] == '\n')
+      {
+        nextLineStartPosition = currentPosition + 1;
+        break;
+      }
+    }
+
+    //------------------------------------------------
+
+    //if there ia another new line character before the maximum line length, we need to start this loop again from that position
+    if (nextLineStartPosition != std::string::npos)
+    {
+      lineStartPosition = nextLineStartPosition;
+    }
+    else
+    {
+      std::string::size_type spacePosition = std::string::npos;
+
+      //search backwards for the last space character (must use signed Int because lineStartPosition can be 0)
+      for (Int currentPosition = Int(searchFromPosition); currentPosition >= Int(lineStartPosition); currentPosition--)
+      {
+        if (result[currentPosition] == ' ')
+        {
+          spacePosition = currentPosition;
+          break;
+        }
+      }
+
+      //if we didn't find a space searching backwards, we must hyphenate
+      if (spacePosition == std::string::npos)
+      {
+        result.insert(searchFromPosition, "-\n");
+        lineStartPosition = searchFromPosition + 2; //make sure the next search ignores the hyphen
+      }
+      else //if we found a space to split on, replace it with a new line character
+      {
+        result.replace(spacePosition, 1, 1, '\n');
+        lineStartPosition = spacePosition + 1;
+      }
+    }
+
+    //------------------------------------------------
+  }
+
+  return result;
+}
+
+
+std::string indentNewLines(const std::string &input, const UInt indentBy)
+{
+  std::string result = input;
+
+  const std::string indentString(indentBy, ' ');
+  std::string::size_type offset = 0;
+
+  while ((offset = result.find('\n', offset)) != std::string::npos)
+  {
+    if ((++offset) >= result.length())
+    {
+      break; //increment offset so we don't find the same \n again and do no indentation at the end
+    }
+    result.insert(offset, indentString);
+  }
+
+  return result;
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+
+Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, TComYuv &src, const UInt numSubBlocksAcross, const UInt numSubBlocksUp, const UInt defWidth )
+{
+  const UInt numValidComp=src.getNumberValidComponents();
+
+  for (UInt ch=0; ch<numValidComp ; ch++)
+  {
+    const ComponentID compID = ComponentID(ch);
+    const UInt width  = src.getWidth(compID);
+    const UInt height = src.getHeight(compID);
+    const UInt stride = src.getStride(compID);
+    const Pel* blkSrc = src.getAddr(compID);
+    const UInt subBlockWidth=width/numSubBlocksAcross;
+    const UInt subBlockHeight=height/numSubBlocksUp;
+
+    ss << pLinePrefix << " compID: " << compID << "\n";
+    for (UInt y=0; y<height; y++)
+    {
+      if ((y%subBlockHeight)==0 && y!=0)
+      {
+        ss << pLinePrefix << '\n';
+      }
+
+      ss << pLinePrefix;
+      for (UInt x=0; x<width; x++)
+      {
+        if ((x%subBlockWidth)==0 && x!=0)
+        {
+          ss << std::setw(defWidth+2) << "";
+        }
+
+        ss << std::setw(defWidth) << blkSrc[y*stride + x] << ' ';
+      }
+      ss << '\n';
+    }
+    ss << pLinePrefix << " --- \n";
+  }
+}
+
+#if DEBUG_STRING
+Int DebugStringGetPredModeMask(PredMode mode)
+{
+  return (mode==MODE_INTRA)?1:2;
+}
+
+Void DebugInterPredResiReco(std::string &sDebug, TComYuv &pred, TComYuv &resi, TComYuv &reco, Int predmode_mask)
+{
+  if (DebugOptionList::DebugString_Pred.getInt()&predmode_mask)
+  {
+    std::stringstream ss(std::stringstream::out);
+    printBlockToStream(ss, "###inter-pred: ", pred);
+    std::string debugTmp;
+    debugTmp=ss.str();
+    sDebug=debugTmp+sDebug;
+  }
+  if (DebugOptionList::DebugString_Resi.getInt()&predmode_mask)
+  {
+    std::stringstream ss(std::stringstream::out);
+    printBlockToStream(ss, "###inter-resi: ", resi);
+    sDebug+=ss.str();
+  }
+  if (DebugOptionList::DebugString_Reco.getInt()&predmode_mask)
+  {
+    std::stringstream ss(std::stringstream::out);
+    printBlockToStream(ss, "###inter-reco: ", reco);
+    sDebug+=ss.str();
+  }
+}
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/Debug.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/Debug.h	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/Debug.h	(revision 1200)
@@ -0,0 +1,278 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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.
+ */
+
+/** \file     Debug.h
+    \brief    Defines types and objects for environment-variable-based debugging and feature control
+*/
+
+#ifndef __DEBUG__
+#define __DEBUG__
+
+#include <iostream>
+#include <iomanip>
+#include <string>
+#include <list>
+#include <stdlib.h>
+#include <sstream>
+#include <TLibCommon/CommonDef.h>
+
+#if DEBUG_STRING
+extern const Char *debug_reorder_data_inter_token[MAX_NUM_COMPONENT+1];
+extern const Char *partSizeToString[NUMBER_OF_PART_SIZES];
+#endif
+
+// ---------------------------------------------------------------------------------------------- //
+
+//constant print-out macro
+
+#define PRINT_CONSTANT(NAME, NAME_WIDTH, VALUE_WIDTH) std::cout << std::setw(NAME_WIDTH) << #NAME << " = " << std::setw(VALUE_WIDTH) << NAME << std::endl;
+
+// ---------------------------------------------------------------------------------------------- //
+
+// ---- Environment variables for test/debug ---- //
+
+class EnvVar
+{
+private:
+  std::string m_sName;
+  std::string m_sHelp;
+  std::string m_sVal;
+  Double      m_dVal;
+  Int         m_iVal;
+  Bool        m_bSet;
+
+public:
+
+  static std::list< std::pair<std::string, std::string> > &getEnvVarList();
+  static std::list<EnvVar*>                               &getEnvVarInUse();
+  static Void printEnvVar();
+  static Void printEnvVarInUse();
+
+  EnvVar(const std::string &sName, const std::string &sDefault, const std::string &sHelp);
+
+  Double              getDouble()   const       { return m_dVal;    }
+  Int                 getInt()      const       { return m_iVal;    }
+  const std::string  &getString()   const       { return m_sVal;    }
+  Bool                isSet()       const       { return m_bSet;    }
+  Bool                isTrue()      const       { return m_iVal!=0; }
+  const std::string  &getName()     const       { return m_sName;   }
+
+};
+
+
+// ---------------------------------------------------------------------------------------------- //
+
+// ---- Control switches for debugging and feature control ---- //
+
+namespace DebugOptionList
+{
+  extern EnvVar DebugSBAC;
+  extern EnvVar DebugRQT;
+  extern EnvVar DebugPred;
+  extern EnvVar ForceLumaMode;
+  extern EnvVar ForceChromaMode;
+
+#if DEBUG_STRING
+  extern EnvVar DebugString_Structure;
+  extern EnvVar DebugString_Pred;
+  extern EnvVar DebugString_Resi;
+  extern EnvVar DebugString_Reco;
+  extern EnvVar DebugString_InvTran;
+#endif
+}
+
+// ---------------------------------------------------------------------------------------------- //
+
+Void printMacroSettings();
+
+// ---------------------------------------------------------------------------------------------- //
+
+//Debugging
+
+extern UInt g_debugCounter;
+
+#if DEBUG_ENCODER_SEARCH_BINS
+extern const UInt debugEncoderSearchBinTargetLine;
+extern const UInt debugEncoderSearchBinWindow;
+#endif
+
+#if DEBUG_CABAC_BINS
+extern const UInt debugCabacBinTargetLine;
+extern const UInt debugCabacBinWindow;
+#endif
+
+
+Void printSBACCoeffData(  const UInt          lastX,
+                          const UInt          lastY,
+                          const UInt          width,
+                          const UInt          height,
+                          const UInt          chan,
+                          const UInt          absPart,
+                          const UInt          scanIdx,
+                          const TCoeff *const pCoeff,
+                          const Bool          finalEncode=true
+                        );
+
+
+Void printCbfArray( class TComDataCU* pcCU  );
+
+UInt getDecimalWidth(const Double value);
+UInt getZScanIndex(const UInt x, const UInt y);
+
+//template specialisation for Char types to get it to render as a number
+template <typename ValueType> inline Void writeValueToStream       (const ValueType &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) <<      value;  }
+template <>                   inline Void writeValueToStream<Char >(const Char      &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) <<  Int(value); }
+template <>                   inline Void writeValueToStream<UChar>(const UChar     &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) << UInt(value); }
+
+template <typename ValueType>
+Void printBlock(const ValueType    *const source,
+                const UInt                width,
+                const UInt                height,
+                const UInt                stride,
+                const UInt                outputValueWidth = 0,         //if set to 0, the maximum output width will be calculated and used
+                const Bool                onlyPrintEdges   = false,     //print only the top row and left column for printing prediction reference samples
+                const Bool                printInZScan     = false,     //output values in Z-scan format (useful for values addressed by AbsPartIdxes)
+                const Int                 shiftLeftBy      = 0,         //set a negative value to right-shift instead
+                const Bool                printAverage     = false,     //also print the average of the values in the block
+                      std::ostream      & stream           = std::cout)
+{
+  //find the maximum output width
+  UInt outputWidth = outputValueWidth;
+
+  if (outputWidth == 0)
+  {
+    ValueType minimumValue = leftShift(source[0], shiftLeftBy);
+    ValueType maximumValue = minimumValue;
+
+    for (UInt y = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++)
+      {
+        ValueType value = 0;
+
+        if (!onlyPrintEdges || (x == 0) || (y == 0))
+        {
+          value = leftShift(source[printInZScan ? getZScanIndex(x, y) : ((y * stride) + x)], shiftLeftBy);
+        }
+
+        if (value < minimumValue)
+        {
+          minimumValue = value;
+        }
+        else if (value > maximumValue)
+        {
+          maximumValue = value;
+        }
+      }
+    }
+
+    outputWidth = std::max<UInt>(getDecimalWidth(Double(minimumValue)), getDecimalWidth(Double(maximumValue))) + 1; //+1 so the numbers don't run into each other
+  }
+
+  //------------------
+  //print out the block
+
+  ValueType valueSum = 0;
+
+  for (UInt y = 0; y < height; y++)
+  {
+    for (UInt x = 0; x < width; x++)
+    {
+      ValueType value = 0;
+
+      if (!onlyPrintEdges || (x == 0) || (y == 0))
+      {
+        value     = leftShift(source[printInZScan ? getZScanIndex(x, y) : ((y * stride) + x)], shiftLeftBy);
+        valueSum += value;
+      }
+
+      writeValueToStream(value, stream, outputWidth);
+    }
+    stream << "\n";
+  }
+
+  const Int valueCount = onlyPrintEdges ? Int((width + height) - 1) : Int(width * height);
+  if (printAverage)
+  {
+    stream << "Average: " << (valueSum / valueCount) << "\n";
+  }
+  stream << "\n";
+}
+
+
+template <typename T>
+Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, const T * blkSrc, const UInt width, const UInt height, const UInt stride, const UInt subBlockWidth=0, const UInt subBlockHeight=0, const UInt defWidth=3 )
+{
+  for (UInt y=0; y<height; y++)
+  {
+    if (subBlockHeight!=0 && (y%subBlockHeight)==0 && y!=0)
+    {
+      ss << pLinePrefix << '\n';
+    }
+
+    ss << pLinePrefix;
+    for (UInt x=0; x<width; x++)
+    {
+      if (subBlockWidth!=0 && (x%subBlockWidth)==0 && x!=0)
+      {
+        ss << std::setw(defWidth+2) << "";
+      }
+
+      ss << std::setw(defWidth) << blkSrc[y*stride + x] << ' ';
+    }
+    ss << '\n';
+  }
+}
+
+class TComYuv;
+Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, TComYuv &src, const UInt numSubBlocksAcross=1, const UInt numSubBlocksUp=1, const UInt defWidth=3 );
+
+// ---------------------------------------------------------------------------------------------- //
+
+//String manipulation functions for aligning and wrapping printed text
+
+std::string splitOnSettings(const std::string &input);
+
+std::string lineWrap(const std::string &input, const UInt maximumLineLength);
+
+std::string indentNewLines(const std::string &input, const UInt indentBy);
+
+// ---------------------------------------------------------------------------------------------- //
+
+#if DEBUG_STRING
+  Int DebugStringGetPredModeMask(PredMode mode);
+  Void DebugInterPredResiReco(std::string &sDebug, TComYuv &pred, TComYuv &resi, TComYuv &reco, Int predmode_mask);
+#endif
+
+
+#endif /* __DEBUG__ */
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/NAL.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/NAL.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/NAL.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -34,7 +34,12 @@
 #pragma once
 
-#include <vector>
+#ifndef __NAL__
+#define __NAL__
+
 #include <sstream>
 #include "CommonDef.h"
+#if NH_MV
+#include <vector>
+#endif
 
 class TComOutputBitstream;
@@ -47,30 +52,29 @@
   NalUnitType m_nalUnitType; ///< nal_unit_type
   UInt        m_temporalId;  ///< temporal_id
-#if H_MV
-  Int         m_layerId;     ///< layer id
+#if NH_MV
+  Int         m_nuhLayerId;     ///< layer id
 #else
-  UInt        m_reservedZero6Bits; ///< reserved_zero_6bits
+  UInt        m_nuhLayerId;  ///< nuh_layer_id
 #endif
 
+  NALUnit(const NALUnit &src)
+  :m_nalUnitType (src.m_nalUnitType)
+  ,m_temporalId  (src.m_temporalId)
+  ,m_nuhLayerId  (src.m_nuhLayerId)
+  { }
   /** construct an NALunit structure with given header values. */
   NALUnit(
     NalUnitType nalUnitType,
     Int         temporalId = 0,
-#if H_MV
-    Int         layerId = 0)
-#else
-    Int         reservedZero6Bits = 0)
-#endif
+    Int         nuhLayerId = 0)
     :m_nalUnitType (nalUnitType)
     ,m_temporalId  (temporalId)
-#if H_MV
-    ,m_layerId     (layerId)
-#else
-    ,m_reservedZero6Bits(reservedZero6Bits)
-#endif
+    ,m_nuhLayerId  (nuhLayerId)
   {}
 
-  /** default constructor - no initialization; must be perfomed by user */
+  /** default constructor - no initialization; must be performed by user */
   NALUnit() {}
+
+  virtual ~NALUnit() { }
 
   /** returns true if the NALunit is a slice NALunit */
@@ -96,5 +100,5 @@
   Bool isSei()
   {
-    return m_nalUnitType == NAL_UNIT_PREFIX_SEI 
+    return m_nalUnitType == NAL_UNIT_PREFIX_SEI
         || m_nalUnitType == NAL_UNIT_SUFFIX_SEI;
   }
@@ -116,5 +120,5 @@
 
   /**
-   * convert the OutputNALUnit #nalu# into EBSP format by writing out
+   * convert the OutputNALUnit nalu into EBSP format by writing out
    * the NALUnit header, then the rbsp_bytes including any
    * emulation_prevention_three_byte symbols.
@@ -124,2 +128,4 @@
 //! \}
 //! \}
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/SEI.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/SEI.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,7 +39,4 @@
 #include "SEI.h"
 
-//Table D-7 Meaning of camera iso sensitivity indicator and exposure index rating indicator
-Int  Table_exp_indicator[32] = {0, 10, 12, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, -1};
-
 SEIMessages getSeisByType(SEIMessages &seiList, SEI::PayloadType seiType)
 {
@@ -60,6 +57,6 @@
   SEIMessages result;
 
-  SEIMessages::iterator it=seiList.begin(); 
-  while ( it!=seiList.end() ) 
+  SEIMessages::iterator it=seiList.begin();
+  while ( it!=seiList.end() )
   {
     if ((*it)->payloadType() == seiType)
@@ -85,2 +82,75 @@
   seiList.clear();
 }
+
+void SEIBufferingPeriod::copyTo (SEIBufferingPeriod& target)
+{
+  target.m_bpSeqParameterSetId = m_bpSeqParameterSetId;
+  target.m_rapCpbParamsPresentFlag = m_rapCpbParamsPresentFlag;
+  target.m_cpbDelayOffset = m_cpbDelayOffset;
+  target.m_dpbDelayOffset = m_dpbDelayOffset;
+  target.m_concatenationFlag = m_concatenationFlag;
+  target.m_auCpbRemovalDelayDelta = m_auCpbRemovalDelayDelta;
+  ::memcpy(target.m_initialCpbRemovalDelay, m_initialCpbRemovalDelay, sizeof(m_initialCpbRemovalDelay));
+  ::memcpy(target.m_initialCpbRemovalDelayOffset, m_initialCpbRemovalDelayOffset, sizeof(m_initialCpbRemovalDelayOffset));
+  ::memcpy(target.m_initialAltCpbRemovalDelay, m_initialAltCpbRemovalDelay, sizeof(m_initialAltCpbRemovalDelay));
+  ::memcpy(target.m_initialAltCpbRemovalDelayOffset, m_initialAltCpbRemovalDelayOffset, sizeof(m_initialAltCpbRemovalDelayOffset));
+}
+
+void SEIPictureTiming::copyTo (SEIPictureTiming& target)
+{
+  target.m_picStruct = m_picStruct;
+  target.m_sourceScanType = m_sourceScanType;
+  target.m_duplicateFlag = m_duplicateFlag;
+
+  target.m_auCpbRemovalDelay = m_auCpbRemovalDelay;
+  target.m_picDpbOutputDelay = m_picDpbOutputDelay;
+  target.m_picDpbOutputDuDelay = m_picDpbOutputDuDelay;
+  target.m_numDecodingUnitsMinus1 = m_numDecodingUnitsMinus1;
+  target.m_duCommonCpbRemovalDelayFlag = m_duCommonCpbRemovalDelayFlag;
+  target.m_duCommonCpbRemovalDelayMinus1 = m_duCommonCpbRemovalDelayMinus1;
+
+  target.m_numNalusInDuMinus1 = m_numNalusInDuMinus1;
+  target.m_duCpbRemovalDelayMinus1 = m_duCpbRemovalDelayMinus1;
+}
+
+// Static member
+const Char *SEI::getSEIMessageString(SEI::PayloadType payloadType)
+{
+  switch (payloadType)
+  {
+    case SEI::BUFFERING_PERIOD:                     return "Buffering period";
+    case SEI::PICTURE_TIMING:                       return "Picture timing";
+    case SEI::PAN_SCAN_RECT:                        return "Pan-scan rectangle";                   // not currently decoded
+    case SEI::FILLER_PAYLOAD:                       return "Filler payload";                       // not currently decoded
+    case SEI::USER_DATA_REGISTERED_ITU_T_T35:       return "User data registered";                 // not currently decoded
+    case SEI::USER_DATA_UNREGISTERED:               return "User data unregistered";
+    case SEI::RECOVERY_POINT:                       return "Recovery point";
+    case SEI::SCENE_INFO:                           return "Scene information";                    // not currently decoded
+    case SEI::FULL_FRAME_SNAPSHOT:                  return "Picture snapshot";                     // not currently decoded
+    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_START: return "Progressive refinement segment start"; // not currently decoded
+    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_END:   return "Progressive refinement segment end";   // not currently decoded
+    case SEI::FILM_GRAIN_CHARACTERISTICS:           return "Film grain characteristics";           // not currently decoded
+    case SEI::POST_FILTER_HINT:                     return "Post filter hint";                     // not currently decoded
+    case SEI::TONE_MAPPING_INFO:                    return "Tone mapping information";
+    case SEI::KNEE_FUNCTION_INFO:                   return "Knee function information";
+    case SEI::FRAME_PACKING:                        return "Frame packing arrangement";
+    case SEI::DISPLAY_ORIENTATION:                  return "Display orientation";
+    case SEI::SOP_DESCRIPTION:                      return "Structure of pictures information";
+    case SEI::ACTIVE_PARAMETER_SETS:                return "Active parameter sets";
+    case SEI::DECODING_UNIT_INFO:                   return "Decoding unit information";
+    case SEI::TEMPORAL_LEVEL0_INDEX:                return "Temporal sub-layer zero index";
+    case SEI::DECODED_PICTURE_HASH:                 return "Decoded picture hash";
+    case SEI::SCALABLE_NESTING:                     return "Scalable nesting";
+    case SEI::REGION_REFRESH_INFO:                  return "Region refresh information";
+    case SEI::NO_DISPLAY:                           return "No display";
+    case SEI::TIME_CODE:                            return "Time code";
+    case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:      return "Mastering display colour volume";
+    case SEI::SEGM_RECT_FRAME_PACKING:              return "Segmented rectangular frame packing arrangement";
+    case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:    return "Temporal motion constrained tile sets";
+    case SEI::CHROMA_SAMPLING_FILTER_HINT:          return "Chroma sampling filter hint";
+#if NH_MV
+    case SEI::SUB_BITSTREAM_PROPERTY:               return "Sub-bitstream property SEI message";      
+#endif
+    default:                                        return "Unknown";
+  }
+}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/SEI.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/SEI.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/SEI.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -32,8 +32,14 @@
  */
 
+#ifndef __SEI__
+#define __SEI__
+
 #pragma once
 #include <list>
 #include <vector>
 #include <cstring>
+
+#include "CommonDef.h"
+#include "libmd5/MD5.h"
 
 //! \ingroup TLibCommon
@@ -72,14 +78,26 @@
     SCALABLE_NESTING                     = 133,
     REGION_REFRESH_INFO                  = 134,
-#if H_MV
-    SUB_BITSTREAM_PROPERTY               = 139,    // Final PayloadType to be defined after finalization
+    NO_DISPLAY                           = 135,
+    TIME_CODE                            = 136,
+    MASTERING_DISPLAY_COLOUR_VOLUME      = 137,
+    SEGM_RECT_FRAME_PACKING              = 138,
+    TEMP_MOTION_CONSTRAINED_TILE_SETS    = 139,
+    CHROMA_SAMPLING_FILTER_HINT          = 140,
+    KNEE_FUNCTION_INFO                   = 141
+#if NH_MV
+    ,SUB_BITSTREAM_PROPERTY              = 164
 #endif
+
   };
-  
+
   SEI() {}
   virtual ~SEI() {}
-  
+
+  static const Char *getSEIMessageString(SEI::PayloadType payloadType);
+
   virtual PayloadType payloadType() const = 0;
 };
+
+static const UInt ISO_IEC_11578_LEN=16;
 
 class SEIuserDataUnregistered : public SEI
@@ -97,6 +115,6 @@
   }
 
-  UChar uuid_iso_iec_11578[16];
-  UInt userDataLength;
+  UChar uuid_iso_iec_11578[ISO_IEC_11578_LEN];
+  UInt  userDataLength;
   UChar *userData;
 };
@@ -109,5 +127,5 @@
   SEIDecodedPictureHash() {}
   virtual ~SEIDecodedPictureHash() {}
-  
+
   enum Method
   {
@@ -118,13 +136,13 @@
   } method;
 
-  UChar digest[3][16];
-};
-
-class SEIActiveParameterSets : public SEI 
+  TComPictureHash m_pictureHash;
+};
+
+class SEIActiveParameterSets : public SEI
 {
 public:
   PayloadType payloadType() const { return ACTIVE_PARAMETER_SETS; }
 
-  SEIActiveParameterSets() 
+  SEIActiveParameterSets()
     : activeVPSId            (0)
     , m_selfContainedCvsFlag (false)
@@ -134,5 +152,5 @@
   virtual ~SEIActiveParameterSets() {}
 
-  Int activeVPSId; 
+  Int activeVPSId;
   Bool m_selfContainedCvsFlag;
   Bool m_noParameterSetUpdateFlag;
@@ -145,4 +163,5 @@
 public:
   PayloadType payloadType() const { return BUFFERING_PERIOD; }
+  void copyTo (SEIBufferingPeriod& target);
 
   SEIBufferingPeriod()
@@ -174,4 +193,5 @@
 public:
   PayloadType payloadType() const { return PICTURE_TIMING; }
+  void copyTo (SEIPictureTiming& target);
 
   SEIPictureTiming()
@@ -180,17 +200,7 @@
   , m_duplicateFlag           (false)
   , m_picDpbOutputDuDelay     (0)
-  , m_numNalusInDuMinus1      (NULL)
-  , m_duCpbRemovalDelayMinus1 (NULL)
   {}
   virtual ~SEIPictureTiming()
   {
-    if( m_numNalusInDuMinus1 != NULL )
-    {
-      delete m_numNalusInDuMinus1;
-    }
-    if( m_duCpbRemovalDelayMinus1  != NULL )
-    {
-      delete m_duCpbRemovalDelayMinus1;
-    }
   }
 
@@ -205,6 +215,6 @@
   Bool  m_duCommonCpbRemovalDelayFlag;
   UInt  m_duCommonCpbRemovalDelayMinus1;
-  UInt* m_numNalusInDuMinus1;
-  UInt* m_duCpbRemovalDelayMinus1;
+  std::vector<UInt> m_numNalusInDuMinus1;
+  std::vector<UInt> m_duCpbRemovalDelayMinus1;
 };
 
@@ -239,4 +249,5 @@
   Bool m_brokenLinkFlag;
 };
+
 class SEIFramePacking : public SEI
 {
@@ -267,4 +278,17 @@
 };
 
+class SEISegmentedRectFramePacking : public SEI
+{
+public:
+  PayloadType payloadType() const { return SEGM_RECT_FRAME_PACKING; }
+
+  SEISegmentedRectFramePacking() {}
+  virtual ~SEISegmentedRectFramePacking() {}
+
+  Bool m_arrangementCancelFlag;
+  Int  m_contentInterpretationType;
+  Bool m_arrangementPersistenceFlag;
+};
+
 class SEIDisplayOrientation : public SEI
 {
@@ -314,4 +338,17 @@
 
   Bool m_gdrForegroundFlag;
+};
+
+class SEINoDisplay : public SEI
+{
+public:
+  PayloadType payloadType() const { return NO_DISPLAY; }
+
+  SEINoDisplay()
+    : m_noDisplay(false)
+  {}
+  virtual ~SEINoDisplay() {}
+
+  Bool m_noDisplay;
 };
 
@@ -358,5 +395,5 @@
   Int    m_exposureIndexIdc;
   Int    m_exposureIndexValue;
-  Int    m_exposureCompensationValueSignFlag;
+  Bool   m_exposureCompensationValueSignFlag;
   Int    m_exposureCompensationValueNumerator;
   Int    m_exposureCompensationValueDenomIdc;
@@ -368,5 +405,73 @@
 };
 
-#if H_MV
+class SEIKneeFunctionInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return KNEE_FUNCTION_INFO; }
+  SEIKneeFunctionInfo() {}
+  virtual ~SEIKneeFunctionInfo() {}
+
+  Int   m_kneeId;
+  Bool  m_kneeCancelFlag;
+  Bool  m_kneePersistenceFlag;
+  Int   m_kneeInputDrange;
+  Int   m_kneeInputDispLuminance;
+  Int   m_kneeOutputDrange;
+  Int   m_kneeOutputDispLuminance;
+  Int   m_kneeNumKneePointsMinus1;
+  std::vector<Int> m_kneeInputKneePoint;
+  std::vector<Int> m_kneeOutputKneePoint;
+};
+
+class SEIChromaSamplingFilterHint : public SEI
+{
+public:
+  PayloadType payloadType() const {return CHROMA_SAMPLING_FILTER_HINT;}
+  SEIChromaSamplingFilterHint() {}
+  virtual ~SEIChromaSamplingFilterHint() {
+    if(m_verChromaFilterIdc == 1)
+    {
+      for(Int i = 0; i < m_numVerticalFilters; i ++)
+      {
+        free(m_verFilterCoeff[i]);
+      }
+      free(m_verFilterCoeff);
+      free(m_verTapLengthMinus1);
+    }
+    if(m_horChromaFilterIdc == 1)
+    {
+      for(Int i = 0; i < m_numHorizontalFilters; i ++)
+      {
+        free(m_horFilterCoeff[i]);
+      }
+      free(m_horFilterCoeff);
+      free(m_horTapLengthMinus1);
+    }
+  }
+
+  Int   m_verChromaFilterIdc;
+  Int   m_horChromaFilterIdc;
+  Bool  m_verFilteringProcessFlag;
+  Int   m_targetFormatIdc;
+  Bool  m_perfectReconstructionFlag;
+  Int   m_numVerticalFilters;
+  Int*  m_verTapLengthMinus1;
+  Int** m_verFilterCoeff;
+  Int   m_numHorizontalFilters;
+  Int*  m_horTapLengthMinus1;
+  Int** m_horFilterCoeff;
+};
+
+class SEIMasteringDisplayColourVolume : public SEI
+{
+public:
+    PayloadType payloadType() const { return MASTERING_DISPLAY_COLOUR_VOLUME; }
+    SEIMasteringDisplayColourVolume() {}
+    virtual ~SEIMasteringDisplayColourVolume(){}
+    
+    TComSEIMasteringDisplay values;
+};
+
+#if NH_MV
 class SEISubBitstreamProperty : public SEI
 {
@@ -392,5 +497,5 @@
 SEIMessages getSeisByType(SEIMessages &seiList, SEI::PayloadType seiType);
 
-/// remove a selection of SEI messages by payload type from the original list and return them in a new list. 
+/// remove a selection of SEI messages by payload type from the original list and return them in a new list.
 SEIMessages extractSeisByType(SEIMessages &seiList, SEI::PayloadType seiType);
 
@@ -404,10 +509,8 @@
 
   SEIScalableNesting() {}
+
   virtual ~SEIScalableNesting()
   {
-    if (!m_callerOwnsSEIs)
-    {
-      deleteSEIs(m_nestedSEIs);
-    }
+    deleteSEIs(m_nestedSEIs);
   }
 
@@ -422,9 +525,79 @@
   UInt  m_nestingNoOpMaxTemporalIdPlus1;             //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
   UInt  m_nestingNumLayersMinus1;                    //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
-  UChar m_nestingLayerId[MAX_NESTING_NUM_LAYER];     //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0. This can e.g. be a static array of 64 unsigned char values
-
-  Bool  m_callerOwnsSEIs;
+  UChar m_nestingLayerId[MAX_NESTING_NUM_LAYER];     //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0. This can e.g. be a static array of 64 UChar values
+
   SEIMessages m_nestedSEIs;
 };
 
+class SEITimeCode : public SEI
+{
+public:
+  PayloadType payloadType() const { return TIME_CODE; }
+  SEITimeCode() {}
+  virtual ~SEITimeCode(){}
+
+  UInt numClockTs;
+  TComSEITimeSet timeSetArray[MAX_TIMECODE_SEI_SETS];
+};
+
+//definition according to P1005_v1;
+class SEITempMotionConstrainedTileSets: public SEI
+{
+  struct TileSetData
+  {
+    protected:
+      std::vector<Int> m_top_left_tile_index;  //[tileSetIdx][tileIdx];
+      std::vector<Int> m_bottom_right_tile_index;
+
+    public:
+      Int     m_mcts_id;  
+      Bool    m_display_tile_set_flag;
+      Int     m_num_tile_rects_in_set; //_minus1;
+      Bool    m_exact_sample_value_match_flag;
+      Bool    m_mcts_tier_level_idc_present_flag;
+      Bool    m_mcts_tier_flag;
+      Int     m_mcts_level_idc;
+
+      Void setNumberOfTileRects(const Int number)
+      {
+        m_top_left_tile_index    .resize(number);
+        m_bottom_right_tile_index.resize(number);
+      }
+
+      Int  getNumberOfTileRects() const
+      {
+        assert(m_top_left_tile_index.size() == m_bottom_right_tile_index.size());
+        return Int(m_top_left_tile_index.size());
+      }
+
+            Int &topLeftTileIndex    (const Int tileRectIndex)       { return m_top_left_tile_index    [tileRectIndex]; }
+            Int &bottomRightTileIndex(const Int tileRectIndex)       { return m_bottom_right_tile_index[tileRectIndex]; }
+      const Int &topLeftTileIndex    (const Int tileRectIndex) const { return m_top_left_tile_index    [tileRectIndex]; }
+      const Int &bottomRightTileIndex(const Int tileRectIndex) const { return m_bottom_right_tile_index[tileRectIndex]; }
+  };
+
+protected:
+  std::vector<TileSetData> m_tile_set_data;
+
+public:
+
+  Bool    m_mc_all_tiles_exact_sample_value_match_flag;
+  Bool    m_each_tile_one_tile_set_flag;
+  Bool    m_limited_tile_set_display_flag;
+  Bool    m_max_mcs_tier_level_idc_present_flag;
+  Bool    m_max_mcts_tier_flag;
+  Int     m_max_mcts_level_idc;
+
+  PayloadType payloadType() const { return TEMP_MOTION_CONSTRAINED_TILE_SETS; }
+
+  Void setNumberOfTileSets(const Int number)       { m_tile_set_data.resize(number);     }
+  Int  getNumberOfTileSets()                 const { return Int(m_tile_set_data.size()); }
+
+        TileSetData &tileSetData (const Int index)       { return m_tile_set_data[index]; }
+  const TileSetData &tileSetData (const Int index) const { return m_tile_set_data[index]; }
+
+};
+
+#endif
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitCounter.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitCounter.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,6 +36,6 @@
 */
 
-#ifndef __COMBITCOUNTER__
-#define __COMBITCOUNTER__
+#ifndef __TCOMBITCOUNTER__
+#define __TCOMBITCOUNTER__
 
 #if _MSC_VER > 1000
@@ -57,12 +57,14 @@
 protected:
   UInt  m_uiBitCounter;
-  
+
 public:
   TComBitCounter()            {}
   virtual ~TComBitCounter()   {}
-  
+
   Void        write                 ( UInt /*uiBits*/, UInt uiNumberOfBits )  { m_uiBitCounter += uiNumberOfBits; }
   Void        resetBits             ()                                    { m_uiBitCounter = 0;               }
   UInt getNumberOfWrittenBits() const { return m_uiBitCounter; }
+  Int         getNumBitsUntilByteAligned() const                              { return (8 - m_uiBitCounter) & 0x7;}
+
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -53,5 +53,4 @@
 TComOutputBitstream::TComOutputBitstream()
 {
-  m_fifo = new vector<uint8_t>;
   clear();
 }
@@ -59,19 +58,24 @@
 TComOutputBitstream::~TComOutputBitstream()
 {
-  delete m_fifo;
-}
-
-TComInputBitstream::TComInputBitstream(std::vector<uint8_t>* buf)
-{
-  m_fifo = buf;
-  m_fifo_idx = 0;
-  m_held_bits = 0;
-  m_num_held_bits = 0;
-  m_numBitsRead = 0;
-}
-
-TComInputBitstream::~TComInputBitstream()
-{
-}
+}
+
+
+TComInputBitstream::TComInputBitstream()
+: m_fifo()
+, m_emulationPreventionByteLocation()
+, m_fifo_idx(0)
+, m_num_held_bits(0)
+, m_held_bits(0)
+, m_numBitsRead(0)
+{ }
+
+TComInputBitstream::TComInputBitstream(const TComInputBitstream &src)
+: m_fifo(src.m_fifo)
+, m_emulationPreventionByteLocation(src.m_emulationPreventionByteLocation)
+, m_fifo_idx(src.m_fifo_idx)
+, m_num_held_bits(src.m_num_held_bits)
+, m_held_bits(src.m_held_bits)
+, m_numBitsRead(src.m_numBitsRead)
+{ }
 
 // ====================================================================================================================
@@ -79,17 +83,25 @@
 // ====================================================================================================================
 
+Void TComInputBitstream::resetToStart()
+{
+  m_fifo_idx=0;
+  m_num_held_bits=0;
+  m_held_bits=0;
+  m_numBitsRead=0;
+}
+
 Char* TComOutputBitstream::getByteStream() const
 {
-  return (Char*) &m_fifo->front();
+  return (Char*) &m_fifo.front();
 }
 
 UInt TComOutputBitstream::getByteStreamLength()
 {
-  return UInt(m_fifo->size());
-}
-
-void TComOutputBitstream::clear()
-{
-  m_fifo->clear();
+  return UInt(m_fifo.size());
+}
+
+Void TComOutputBitstream::clear()
+{
+  m_fifo.clear();
   m_held_bits = 0;
   m_num_held_bits = 0;
@@ -130,8 +142,8 @@
   switch (num_total_bits >> 3)
   {
-  case 4: m_fifo->push_back(write_bits >> 24);
-  case 3: m_fifo->push_back(write_bits >> 16);
-  case 2: m_fifo->push_back(write_bits >> 8);
-  case 1: m_fifo->push_back(write_bits);
+  case 4: m_fifo.push_back(write_bits >> 24);
+  case 3: m_fifo.push_back(write_bits >> 16);
+  case 2: m_fifo.push_back(write_bits >> 8);
+  case 1: m_fifo.push_back(write_bits);
   }
 
@@ -153,5 +165,5 @@
     return;
   }
-  m_fifo->push_back(m_held_bits);
+  m_fifo.push_back(m_held_bits);
   m_held_bits = 0;
   m_num_held_bits = 0;
@@ -217,9 +229,9 @@
 
 /**
- * read #uiNumberOfBits# from bitstream without updating the bitstream
- * state, storing the result in #ruiBits#.
+ * read uiNumberOfBits from bitstream without updating the bitstream
+ * state, storing the result in ruiBits.
  *
- * If reading #uiNumberOfBits# would overrun the bitstream buffer,
- * the bitsream is effectively padded with sufficient zero-bits to
+ * If reading uiNumberOfBits would overrun the bitstream buffer,
+ * the bitstream is effectively padded with sufficient zero-bits to
  * avoid the overrun.
  */
@@ -243,5 +255,5 @@
 {
   assert( uiNumberOfBits <= 32 );
-  
+
   m_numBitsRead += uiNumberOfBits;
 
@@ -279,12 +291,12 @@
   UInt aligned_word = 0;
   UInt num_bytes_to_load = (uiNumberOfBits - 1) >> 3;
-  assert(m_fifo_idx + num_bytes_to_load < m_fifo->size());
+  assert(m_fifo_idx + num_bytes_to_load < m_fifo.size());
 
   switch (num_bytes_to_load)
   {
-  case 3: aligned_word  = (*m_fifo)[m_fifo_idx++] << 24;
-  case 2: aligned_word |= (*m_fifo)[m_fifo_idx++] << 16;
-  case 1: aligned_word |= (*m_fifo)[m_fifo_idx++] <<  8;
-  case 0: aligned_word |= (*m_fifo)[m_fifo_idx++];
+  case 3: aligned_word  = m_fifo[m_fifo_idx++] << 24;
+  case 2: aligned_word |= m_fifo[m_fifo_idx++] << 16;
+  case 1: aligned_word |= m_fifo[m_fifo_idx++] <<  8;
+  case 0: aligned_word |= m_fifo[m_fifo_idx++];
   }
 
@@ -306,38 +318,40 @@
  * into this at byte position pos.
  */
-void TComOutputBitstream::insertAt(const TComOutputBitstream& src, UInt pos)
+Void TComOutputBitstream::insertAt(const TComOutputBitstream& src, UInt pos)
 {
   UInt src_bits = src.getNumberOfWrittenBits();
   assert(0 == src_bits % 8);
 
-  vector<uint8_t>::iterator at = this->m_fifo->begin() + pos;
-  this->m_fifo->insert(at, src.m_fifo->begin(), src.m_fifo->end());
-}
-
-Void TComInputBitstream::readOutTrailingBits ()
-{
+  vector<uint8_t>::iterator at = m_fifo.begin() + pos;
+  m_fifo.insert(at, src.m_fifo.begin(), src.m_fifo.end());
+}
+
+UInt TComInputBitstream::readOutTrailingBits ()
+{
+  UInt count=0;
   UInt uiBits = 0;
 
   while ( ( getNumBitsLeft() > 0 ) && (getNumBitsUntilByteAligned()!=0) )
   {
+    count++;
     read ( 1, uiBits );
   }
-}
-
-TComOutputBitstream& TComOutputBitstream::operator= (const TComOutputBitstream& src)
-{
-  vector<uint8_t>::iterator at = this->m_fifo->begin();
-  this->m_fifo->insert(at, src.m_fifo->begin(), src.m_fifo->end());
-
-  this->m_num_held_bits             = src.m_num_held_bits;
-  this->m_held_bits                 = src.m_held_bits;
-
-  return *this;
-}
+  return count;
+}
+//
+//TComOutputBitstream& TComOutputBitstream::operator= (const TComOutputBitstream& src)
+//{
+//  vector<uint8_t>::iterator at = m_fifo.begin();
+//  m_fifo.insert(at, src.m_fifo.begin(), src.m_fifo.end());
+//
+//  m_num_held_bits             = src.m_num_held_bits;
+//  m_held_bits                 = src.m_held_bits;
+//
+//  return *this;
+//}
 
 /**
- - extract substream from the current bitstream
- .
- \param  pcBitstream  bitstream which contains substreams
+ Extract substream from the current bitstream.
+
  \param  uiNumBits    number of bits to transfer
  */
@@ -345,31 +359,40 @@
 {
   UInt uiNumBytes = uiNumBits/8;
-  std::vector<uint8_t>* buf = new std::vector<uint8_t>;
-  UInt uiByte;
+  TComInputBitstream *pResult = new TComInputBitstream;
+
+  std::vector<uint8_t> &buf = pResult->getFifo();
+  buf.reserve((uiNumBits+7)>>3);
+
+  if (m_num_held_bits == 0)
+  {
+    std::size_t currentOutputBufferSize=buf.size();
+    const UInt uiNumBytesToReadFromFifo = std::min<UInt>(uiNumBytes, (UInt)m_fifo.size() - m_fifo_idx);
+    buf.resize(currentOutputBufferSize+uiNumBytes);
+    memcpy(&(buf[currentOutputBufferSize]), &(m_fifo[m_fifo_idx]), uiNumBytesToReadFromFifo); m_fifo_idx+=uiNumBytesToReadFromFifo;
+    if (uiNumBytesToReadFromFifo != uiNumBytes)
+    {
+      memset(&(buf[currentOutputBufferSize+uiNumBytesToReadFromFifo]), 0, uiNumBytes - uiNumBytesToReadFromFifo);
+    }
+  }
+  else
+  {
   for (UInt ui = 0; ui < uiNumBytes; ui++)
   {
+      UInt uiByte;
     read(8, uiByte);
-    buf->push_back(uiByte);
+      buf.push_back(uiByte);
+    }
   }
   if (uiNumBits&0x7)
   {
-    uiByte = 0;
+    UInt uiByte = 0;
     read(uiNumBits&0x7, uiByte);
     uiByte <<= 8-(uiNumBits&0x7);
-    buf->push_back(uiByte);
-  }
-  return new TComInputBitstream(buf);
-}
-
-/**
- - delete internal fifo
- */
-Void TComInputBitstream::deleteFifo()
-{
-  delete m_fifo;
-  m_fifo = NULL;
-}
-
-Void TComInputBitstream::readByteAlignment()
+    buf.push_back(uiByte);
+  }
+  return pResult;
+}
+
+UInt TComInputBitstream::readByteAlignment()
 {
   UInt code = 0;
@@ -384,4 +407,5 @@
     assert(code == 0);
   }
+  return numBits+1;
 }
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitStream.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComBitStream.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,6 +36,6 @@
 */
 
-#ifndef __COMBITSTREAM__
-#define __COMBITSTREAM__
+#ifndef __TCOMBITSTREAM__
+#define __TCOMBITSTREAM__
 
 #if _MSC_VER > 1000
@@ -46,5 +46,4 @@
 #include <vector>
 #include <stdio.h>
-#include <assert.h>
 #include "CommonDef.h"
 
@@ -65,4 +64,5 @@
   virtual Void        resetBits             ()                                    = 0;
   virtual UInt getNumberOfWrittenBits() const = 0;
+  virtual Int         getNumBitsUntilByteAligned() const = 0;
   virtual ~TComBitIf() {}
 };
@@ -81,10 +81,9 @@
    *    NB, this pointer is only valid until the next push_back()/clear()
    */
-  std::vector<uint8_t> *m_fifo;
+  std::vector<uint8_t> m_fifo;
 
   UInt m_num_held_bits; /// number of bits not flushed to bytestream.
   UChar m_held_bits; /// the bits held and not flushed to bytestream.
                              /// this value is always msb-aligned, bigendian.
-
 public:
   // create / destroy
@@ -106,5 +105,5 @@
 
   /** this function should never be called */
-  void resetBits() { assert(0); }
+  Void resetBits() { assert(0); }
 
   // utility functions
@@ -132,23 +131,23 @@
    * achieve byte alignment.
    */
-  Int getNumBitsUntilByteAligned() { return (8 - m_num_held_bits) & 0x7; }
+  Int getNumBitsUntilByteAligned() const { return (8 - m_num_held_bits) & 0x7; }
 
   /**
    * Return the number of bits that have been written since the last clear()
    */
-  UInt getNumberOfWrittenBits() const { return UInt(m_fifo->size()) * 8 + m_num_held_bits; }
-
-  void insertAt(const TComOutputBitstream& src, UInt pos);
+  UInt getNumberOfWrittenBits() const { return UInt(m_fifo.size()) * 8 + m_num_held_bits; }
+
+  Void insertAt(const TComOutputBitstream& src, UInt pos);
 
   /**
    * Return a reference to the internal fifo
    */
-  std::vector<uint8_t>& getFIFO() { return *m_fifo; }
+  std::vector<uint8_t>& getFIFO() { return m_fifo; }
 
   UChar getHeldBits  ()          { return m_held_bits;          }
 
-  TComOutputBitstream& operator= (const TComOutputBitstream& src);
+  //TComOutputBitstream& operator= (const TComOutputBitstream& src);
   /** Return a reference to the internal fifo */
-  std::vector<uint8_t>& getFIFO() const { return *m_fifo; }
+  const std::vector<uint8_t>& getFIFO() const { return m_fifo; }
 
   Void          addSubstream    ( TComOutputBitstream* pcSubstream );
@@ -165,8 +164,8 @@
 class TComInputBitstream
 {
-  std::vector<uint8_t> *m_fifo; /// FIFO for storage of complete bytes
+protected:
+  std::vector<uint8_t> m_fifo; /// FIFO for storage of complete bytes
   std::vector<UInt> m_emulationPreventionByteLocation;
 
-protected:
   UInt m_fifo_idx; /// Read index into m_fifo
 
@@ -177,10 +176,11 @@
 public:
   /**
-   * Create a new bitstream reader object that reads from #buf#.  Ownership
-   * of #buf# remains with the callee, although the constructed object
-   * will hold a reference to #buf#
-   */
-  TComInputBitstream(std::vector<uint8_t>* buf);
-  ~TComInputBitstream();
+   * Create a new bitstream reader object that reads from buf.
+   */
+  TComInputBitstream();
+  virtual ~TComInputBitstream() { }
+  TComInputBitstream(const TComInputBitstream &src);
+
+  Void resetToStart();
 
   // interface for decoding
@@ -189,6 +189,6 @@
   Void        readByte        ( UInt &ruiBits )
   {
-    assert(m_fifo_idx < m_fifo->size());
-    ruiBits = (*m_fifo)[m_fifo_idx++];
+    assert(m_fifo_idx < m_fifo.size());
+    ruiBits = m_fifo[m_fifo_idx++];
   }
 
@@ -196,8 +196,8 @@
   {
     assert(m_fifo_idx > 0);
-    byte = (*m_fifo)[m_fifo_idx - 1];
+    byte = m_fifo[m_fifo_idx - 1];
   }
-  
-  Void        readOutTrailingBits ();
+
+  UInt        readOutTrailingBits ();
   UChar getHeldBits  ()          { return m_held_bits;          }
   TComOutputBitstream& operator= (const TComOutputBitstream& src);
@@ -211,16 +211,18 @@
   UInt     readByte() { UInt tmp; readByte( tmp ); return tmp; }
   UInt getNumBitsUntilByteAligned() { return m_num_held_bits & (0x7); }
-  UInt getNumBitsLeft() { return 8*((UInt)m_fifo->size() - m_fifo_idx) + m_num_held_bits; }
+  UInt getNumBitsLeft() { return 8*((UInt)m_fifo.size() - m_fifo_idx) + m_num_held_bits; }
   TComInputBitstream *extractSubstream( UInt uiNumBits ); // Read the nominated number of bits, and return as a bitstream.
-  Void                deleteFifo(); // Delete internal fifo of bitstream.
   UInt  getNumBitsRead() { return m_numBitsRead; }
-  Void readByteAlignment();
+  UInt readByteAlignment();
 
   Void      pushEmulationPreventionByteLocation ( UInt pos )                  { m_emulationPreventionByteLocation.push_back( pos ); }
   UInt      numEmulationPreventionBytesRead     ()                            { return (UInt) m_emulationPreventionByteLocation.size();    }
-  std::vector<UInt>  getEmulationPreventionByteLocation  ()                   { return m_emulationPreventionByteLocation;           }
+  const std::vector<UInt> &getEmulationPreventionByteLocation  () const              { return m_emulationPreventionByteLocation;           }
   UInt      getEmulationPreventionByteLocation  ( UInt idx )                  { return m_emulationPreventionByteLocation[ idx ];    }
   Void      clearEmulationPreventionByteLocation()                            { m_emulationPreventionByteLocation.clear();          }
-  Void      setEmulationPreventionByteLocation  ( std::vector<UInt> vec )     { m_emulationPreventionByteLocation = vec;            }
+  Void      setEmulationPreventionByteLocation  ( const std::vector<UInt> &vec )     { m_emulationPreventionByteLocation = vec;            }
+
+  const std::vector<uint8_t> &getFifo() const { return m_fifo; }
+        std::vector<uint8_t> &getFifo()       { return m_fifo; }
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -41,5 +41,5 @@
 //! \{
 
-const UChar TComCABACTables::sm_aucLPSTable[64][4] =
+const UChar TComCABACTables::sm_aucLPSTable[1 << CONTEXT_STATE_BITS][4] =
 {
   { 128, 176, 208, 240},
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCABACTables.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCABACTables.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,8 +36,9 @@
 */
 
-#ifndef __TCOM_CABAC_TABLES__
-#define __TCOM_CABAC_TABLES__
+#ifndef __TCOMCABACTABLES__
+#define __TCOMCABACTABLES__
 
 #include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComRom.h"
 
 //! \ingroup TLibCommon
@@ -51,5 +52,5 @@
 {
 public:
-  const static UChar  sm_aucLPSTable[64][4];
+  const static UChar  sm_aucLPSTable[1 << CONTEXT_STATE_BITS][4];
   const static UChar  sm_aucRenormTable[32];
 };
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComChromaFormat.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComChromaFormat.cpp	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComChromaFormat.cpp	(revision 1200)
@@ -0,0 +1,163 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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.
+ */
+
+
+#include "TComChromaFormat.h"
+#include "TComPic.h"
+#include "TComDataCU.h"
+#include "TComTrQuant.h"
+#include "TComTU.h"
+
+
+
+
+//----------------------------------------------------------------------------------------------------------------------
+
+InputColourSpaceConversion stringToInputColourSpaceConvert(const std::string &value, const Bool bIsForward)
+{
+  if (value.empty() || value=="UNCHANGED")
+  {
+    return IPCOLOURSPACE_UNCHANGED;
+  }
+  if (bIsForward)
+  {
+    if (value=="YCbCrtoYYY")
+    {
+      return IPCOLOURSPACE_YCbCrtoYYY;
+    }
+    if (value=="YCbCrtoYCrCb")
+    {
+      return IPCOLOURSPACE_YCbCrtoYCrCb;
+    }
+    if (value=="RGBtoGBR")
+    {
+      return IPCOLOURSPACE_RGBtoGBR;
+    }
+  }
+  else
+  {
+    if (value=="YCrCbtoYCbCr")
+    {
+      return IPCOLOURSPACE_YCbCrtoYCrCb;
+    }
+    if (value=="GBRtoRGB")
+    {
+      return IPCOLOURSPACE_RGBtoGBR;
+    }
+  }
+  return NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS;
+}
+
+std::string getListOfColourSpaceConverts(const Bool bIsForward)
+{
+  if (bIsForward)
+  {
+    return "UNCHANGED, YCbCrtoYCrCb, YCbCrtoYYY or RGBtoGBR";
+  }
+  else
+  {
+    return "UNCHANGED, YCrCbtoYCbCr or GBRtoRGB";
+  }
+}
+
+
+//----------------------------------------------------------------------------------------------------------------------
+
+Void getTUEntropyCodingParameters(      TUEntropyCodingParameters &result,
+                                        TComTU                    &rTu,
+                                  const ComponentID                component)
+{
+  //------------------------------------------------
+
+  //set the local parameters
+
+        TComDataCU    *const pcCU            = rTu.getCU();
+  const TComRectangle &      area            = rTu.getRect(component);
+  const UInt                 uiAbsPartIdx    = rTu.GetAbsPartIdxTU(component);
+  const UInt                 log2BlockWidth  = g_aucConvertToBit[area.width]  + 2;
+  const UInt                 log2BlockHeight = g_aucConvertToBit[area.height] + 2;
+  const ChannelType          channelType     = toChannelType(component);
+
+  result.scanType = COEFF_SCAN_TYPE(pcCU->getCoefScanIdx(uiAbsPartIdx, area.width, area.height, component));
+
+  //------------------------------------------------
+
+  //set the group layout
+
+  result.widthInGroups  = area.width  >> MLS_CG_LOG2_WIDTH;
+  result.heightInGroups = area.height >> MLS_CG_LOG2_HEIGHT;
+
+  //------------------------------------------------
+
+  //set the scan orders
+
+  const UInt log2WidthInGroups  = g_aucConvertToBit[result.widthInGroups  * 4];
+  const UInt log2HeightInGroups = g_aucConvertToBit[result.heightInGroups * 4];
+
+  result.scan   = g_scanOrder[ SCAN_GROUPED_4x4 ][ result.scanType ][ log2BlockWidth    ][ log2BlockHeight    ];
+  result.scanCG = g_scanOrder[ SCAN_UNGROUPED   ][ result.scanType ][ log2WidthInGroups ][ log2HeightInGroups ];
+
+  //------------------------------------------------
+
+  //set the significance map context selection parameters
+
+  if (pcCU->getSlice()->getSPS()->getSpsRangeExtension().getTransformSkipContextEnabledFlag()
+      && (pcCU->getCUTransquantBypass(uiAbsPartIdx) || (pcCU->getTransformSkip(uiAbsPartIdx, component) != 0)))
+  {
+    result.firstSignificanceMapContext = significanceMapContextSetStart[channelType][CONTEXT_TYPE_SINGLE];
+  }
+  else
+  {
+    if ((area.width == 4) && (area.height == 4))
+    {
+      result.firstSignificanceMapContext = significanceMapContextSetStart[channelType][CONTEXT_TYPE_4x4];
+    }
+    else if ((area.width == 8) && (area.height == 8))
+    {
+      result.firstSignificanceMapContext = significanceMapContextSetStart[channelType][CONTEXT_TYPE_8x8];
+      if (result.scanType != SCAN_DIAG)
+      {
+        result.firstSignificanceMapContext += nonDiagonalScan8x8ContextOffset[channelType];
+      }
+    }
+    else
+    {
+      result.firstSignificanceMapContext = significanceMapContextSetStart[channelType][CONTEXT_TYPE_NxN];
+    }
+  }
+
+  //------------------------------------------------
+}
+
+
+//----------------------------------------------------------------------------------------------------------------------
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComChromaFormat.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComChromaFormat.h	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComChromaFormat.h	(revision 1200)
@@ -0,0 +1,277 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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 __TCOMCHROMAFORMAT__
+#define __TCOMCHROMAFORMAT__
+
+#include "CommonDef.h"
+#include "TComRectangle.h"
+#include "ContextTables.h"
+#include "TComRom.h"
+#include <iostream>
+#include <vector>
+#include <assert.h>
+#include "Debug.h"
+
+//======================================================================================================================
+//Chroma format utility functions  =====================================================================================
+//======================================================================================================================
+
+class TComDataCU;
+
+
+static inline ChannelType toChannelType             (const ComponentID id)                         { return (id==COMPONENT_Y)? CHANNEL_TYPE_LUMA : CHANNEL_TYPE_CHROMA; }
+static inline Bool        isLuma                    (const ComponentID id)                         { return (id==COMPONENT_Y);                                          }
+static inline Bool        isLuma                    (const ChannelType id)                         { return (id==CHANNEL_TYPE_LUMA);                                    }
+static inline Bool        isChroma                  (const ComponentID id)                         { return (id!=COMPONENT_Y);                                          }
+static inline Bool        isChroma                  (const ChannelType id)                         { return (id!=CHANNEL_TYPE_LUMA);                                    }
+static inline UInt        getChannelTypeScaleX      (const ChannelType id, const ChromaFormat fmt) { return (isLuma(id) || (fmt==CHROMA_444)) ? 0 : 1;                  }
+static inline UInt        getChannelTypeScaleY      (const ChannelType id, const ChromaFormat fmt) { return (isLuma(id) || (fmt!=CHROMA_420)) ? 0 : 1;                  }
+static inline UInt        getComponentScaleX        (const ComponentID id, const ChromaFormat fmt) { return getChannelTypeScaleX(toChannelType(id), fmt);               }
+static inline UInt        getComponentScaleY        (const ComponentID id, const ChromaFormat fmt) { return getChannelTypeScaleY(toChannelType(id), fmt);               }
+static inline UInt        getNumberValidChannelTypes(const ChromaFormat fmt)                       { return (fmt==CHROMA_400) ? 1 : MAX_NUM_CHANNEL_TYPE;               }
+static inline UInt        getNumberValidComponents  (const ChromaFormat fmt)                       { return (fmt==CHROMA_400) ? 1 : MAX_NUM_COMPONENT;                  }
+static inline Bool        isChromaEnabled           (const ChromaFormat fmt)                       { return  fmt!=CHROMA_400;                                           }
+static inline ComponentID getFirstComponentOfChannel(const ChannelType id)                         { return (isLuma(id) ? COMPONENT_Y : COMPONENT_Cb);                  }
+
+InputColourSpaceConversion stringToInputColourSpaceConvert(const std::string &value, const Bool bIsForward);
+std::string getListOfColourSpaceConverts(const Bool bIsForward);
+
+//------------------------------------------------
+
+static inline UInt getTotalSamples(const UInt width, const UInt height, const ChromaFormat format)
+{
+  const UInt samplesPerChannel = width * height;
+
+  switch (format)
+  {
+    case CHROMA_400: return  samplesPerChannel;           break;
+    case CHROMA_420: return (samplesPerChannel * 3) >> 1; break;
+    case CHROMA_422: return  samplesPerChannel * 2;       break;
+    case CHROMA_444: return  samplesPerChannel * 3;       break;
+    default:
+      std::cerr << "ERROR: Unrecognised chroma format in getTotalSamples()" << std::endl;
+      exit(1);
+      break;
+  }
+
+  return MAX_UINT;
+}
+
+//------------------------------------------------
+
+static inline UInt getTotalBits(const UInt width, const UInt height, const ChromaFormat format, const Int bitDepths[MAX_NUM_CHANNEL_TYPE])
+{
+  const UInt samplesPerChannel = width * height;
+
+  switch (format)
+  {
+    case CHROMA_400: return  samplesPerChannel *  bitDepths[CHANNEL_TYPE_LUMA];                                              break;
+    case CHROMA_420: return (samplesPerChannel * (bitDepths[CHANNEL_TYPE_LUMA]*2 +   bitDepths[CHANNEL_TYPE_CHROMA]) ) >> 1; break;
+    case CHROMA_422: return  samplesPerChannel * (bitDepths[CHANNEL_TYPE_LUMA]   +   bitDepths[CHANNEL_TYPE_CHROMA]);        break;
+    case CHROMA_444: return  samplesPerChannel * (bitDepths[CHANNEL_TYPE_LUMA]   + 2*bitDepths[CHANNEL_TYPE_CHROMA]);        break;
+    default:
+      std::cerr << "ERROR: Unrecognised chroma format in getTotalSamples()" << std::endl;
+      exit(1);
+      break;
+  }
+
+  return MAX_UINT;
+}
+
+
+//------------------------------------------------
+
+// In HM, a CU only has one chroma intra prediction direction, that corresponds to the top left luma intra prediction
+// even if the NxN PU split occurs when 4 sub-TUs exist for chroma.
+// Use this function to allow NxN PU splitting for chroma.
+
+static inline Bool enable4ChromaPUsInIntraNxNCU(const ChromaFormat chFmt)
+{
+  return (chFmt == CHROMA_444);
+}
+
+
+//------------------------------------------------
+
+//returns the part index of the luma region that is co-located with the specified chroma region
+
+static inline UInt
+getChromasCorrespondingPULumaIdx(const UInt lumaZOrderIdxInCtu,
+                                 const ChromaFormat chFmt,
+                                 const Int partsPerMinCU  // 1<<(2*(sps->getMaxTotalCUDepth() - sps->getLog2DiffMaxMinCodingBlockSize()))
+                                 )
+{
+  return enable4ChromaPUsInIntraNxNCU(chFmt) ? lumaZOrderIdxInCtu : lumaZOrderIdxInCtu & (~(partsPerMinCU-1));
+}
+
+//------------------------------------------------
+
+// If chroma format is 4:2:2 and a chroma-square-sub-tu is possible for the smallest TU, then increase the depth by 1 to allow for more parts.
+
+static inline UInt getMaxCUDepthOffset(const ChromaFormat chFmt, const UInt quadtreeTULog2MinSize)
+{
+  return (chFmt==CHROMA_422 && quadtreeTULog2MinSize>2) ? 1 : 0;
+}
+
+//======================================================================================================================
+//Intra prediction  ====================================================================================================
+//======================================================================================================================
+
+static inline Bool filterIntraReferenceSamples (const ChannelType chType, const ChromaFormat chFmt, const Bool intraReferenceSmoothingDisabled)
+{
+  return (!intraReferenceSmoothingDisabled) && (isLuma(chType) || (chFmt == CHROMA_444));
+}
+
+
+//======================================================================================================================
+//Transform and Quantisation  ==========================================================================================
+//======================================================================================================================
+
+static inline Bool TUCompRectHasAssociatedTransformSkipFlag(const TComRectangle &rectSamples, const UInt transformSkipLog2MaxSize)
+{
+  return (rectSamples.width <= (1<<transformSkipLog2MaxSize));
+}
+
+
+//------------------------------------------------
+
+static inline Int getTransformShift(const Int channelBitDepth, const UInt uiLog2TrSize, const Int maxLog2TrDynamicRange)
+{
+  return maxLog2TrDynamicRange - channelBitDepth - uiLog2TrSize;
+}
+
+
+//------------------------------------------------
+
+static inline Int getScaledChromaQP(Int unscaledChromaQP, const ChromaFormat chFmt)
+{
+  return g_aucChromaScale[chFmt][Clip3(0, (chromaQPMappingTableSize - 1), unscaledChromaQP)];
+}
+
+
+//======================================================================================================================
+//Scaling lists  =======================================================================================================
+//======================================================================================================================
+
+static inline Int getScalingListType(const PredMode predMode, const ComponentID compID)
+{
+  return ((predMode != MODE_INTER) ? 0 : MAX_NUM_COMPONENT) + compID;
+}
+
+
+//------------------------------------------------
+
+
+//======================================================================================================================
+//Context variable selection  ==========================================================================================
+//======================================================================================================================
+
+//context variable source tables
+
+static const UInt significanceMapContextStartTable[MAX_NUM_CHANNEL_TYPE] = {FIRST_SIG_FLAG_CTX_LUMA, FIRST_SIG_FLAG_CTX_CHROMA};
+static const UInt contextSetStartTable            [MAX_NUM_CHANNEL_TYPE] = {FIRST_CTX_SET_LUMA,      FIRST_CTX_SET_CHROMA     };
+static const UInt CBFContextStartTable            [MAX_NUM_CHANNEL_TYPE] = {FIRST_CBF_CTX_LUMA,      FIRST_CBF_CTX_CHROMA     };
+
+
+//------------------------------------------------
+
+//Function for last-significant-coefficient context selection parameters
+
+static inline Void getLastSignificantContextParameters (const ComponentID  component,
+                                                        const Int          width,
+                                                        const Int          height,
+                                                              Int         &result_offsetX,
+                                                              Int         &result_offsetY,
+                                                              Int         &result_shiftX,
+                                                              Int         &result_shiftY)
+{
+  const UInt convertedWidth  = g_aucConvertToBit[width];
+  const UInt convertedHeight = g_aucConvertToBit[height];
+
+  result_offsetX = (isChroma(component)) ? 0               : ((convertedWidth  * 3) + ((convertedWidth  + 1) >> 2));
+  result_offsetY = (isChroma(component)) ? 0               : ((convertedHeight * 3) + ((convertedHeight + 1) >> 2));
+  result_shiftX  = (isChroma(component)) ? convertedWidth  : ((convertedWidth  + 3) >> 2);
+  result_shiftY  = (isChroma(component)) ? convertedHeight : ((convertedHeight + 3) >> 2);
+}
+
+
+//------------------------------------------------
+
+//Function for significance map context index offset selection
+
+static inline UInt getSignificanceMapContextOffset (const ComponentID component)
+{
+  return significanceMapContextStartTable[toChannelType(component)];
+}
+
+
+//------------------------------------------------
+
+// Function for greater-than-one map/greater-than-two map context set selection
+
+static inline UInt getContextSetIndex (const ComponentID  component,
+                                       const UInt         subsetIndex,
+                                       const Bool         foundACoefficientGreaterThan1)
+{
+  const UInt notFirstSubsetOffset     = (isLuma(component) && (subsetIndex > 0)) ? 2 : 0;
+  const UInt foundAGreaterThan1Offset = foundACoefficientGreaterThan1            ? 1 : 0;
+
+  return contextSetStartTable[toChannelType(component)] + notFirstSubsetOffset + foundAGreaterThan1Offset;
+}
+
+
+//------------------------------------------------
+
+//Function for CBF context index offset
+
+static inline UInt getCBFContextOffset (const ComponentID component)
+{
+  return CBFContextStartTable[toChannelType(component)];
+}
+
+
+//======================================================================================================================
+//Entropy coding parameters ============================================================================================
+//======================================================================================================================
+
+Void getTUEntropyCodingParameters(      TUEntropyCodingParameters &result,
+                                  class TComTU                    &rTu,
+                                  const ComponentID                component);
+
+
+//======================================================================================================================
+//End  =================================================================================================================
+//======================================================================================================================
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCodingStatistics.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCodingStatistics.h	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComCodingStatistics.h	(revision 1200)
@@ -0,0 +1,485 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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 __TCOMCODINGSTATISTICS__
+#define __TCOMCODINGSTATISTICS__
+
+#include "CommonDef.h"
+#include <stdio.h>
+#include <string>
+#include <map>
+#include <math.h>
+#include "TComChromaFormat.h"
+
+static const Int64 TCOMCODINGSTATISTICS_ENTROPYSCALE=32768;
+
+
+enum TComCodingStatisticsType
+{
+  STATS__NAL_UNIT_TOTAL_BODY,// This is a special case and is not included in the total sums.
+  STATS__NAL_UNIT_PACKING,
+  STATS__EMULATION_PREVENTION_3_BYTES,
+  STATS__NAL_UNIT_HEADER_BITS,
+  STATS__CABAC_INITIALISATION,
+  STATS__CABAC_BITS__TQ_BYPASS_FLAG,
+  STATS__CABAC_BITS__SKIP_FLAG,
+  STATS__CABAC_BITS__MERGE_FLAG,
+  STATS__CABAC_BITS__MERGE_INDEX,
+  STATS__CABAC_BITS__MVP_IDX,
+  STATS__CABAC_BITS__SPLIT_FLAG,
+  STATS__CABAC_BITS__PART_SIZE,
+  STATS__CABAC_BITS__PRED_MODE,
+  STATS__CABAC_BITS__INTRA_DIR_ANG,
+  STATS__CABAC_BITS__INTER_DIR,
+  STATS__CABAC_BITS__REF_FRM_IDX,
+  STATS__CABAC_BITS__MVD,
+  STATS__CABAC_BITS__MVD_EP,
+  STATS__CABAC_BITS__TRANSFORM_SUBDIV_FLAG,
+  STATS__CABAC_BITS__QT_ROOT_CBF,
+  STATS__CABAC_BITS__DELTA_QP_EP,
+  STATS__CABAC_BITS__CHROMA_QP_ADJUSTMENT,
+  STATS__CABAC_BITS__QT_CBF,
+  STATS__CABAC_BITS__CROSS_COMPONENT_PREDICTION,
+  STATS__CABAC_BITS__TRANSFORM_SKIP_FLAGS,
+
+  STATS__CABAC_BITS__LAST_SIG_X_Y,
+  STATS__CABAC_BITS__SIG_COEFF_GROUP_FLAG,
+  STATS__CABAC_BITS__SIG_COEFF_MAP_FLAG,
+  STATS__CABAC_BITS__GT1_FLAG,
+  STATS__CABAC_BITS__GT2_FLAG,
+  STATS__CABAC_BITS__SIGN_BIT,
+  STATS__CABAC_BITS__ESCAPE_BITS,
+
+  STATS__CABAC_BITS__SAO,
+  STATS__CABAC_TRM_BITS,
+  STATS__CABAC_FIXED_BITS,
+  STATS__CABAC_PCM_ALIGN_BITS,
+  STATS__CABAC_PCM_CODE_BITS,
+  STATS__BYTE_ALIGNMENT_BITS,
+  STATS__TRAILING_BITS,
+  STATS__EXPLICIT_RDPCM_BITS,
+  STATS__CABAC_EP_BIT_ALIGNMENT,
+  STATS__CABAC_BITS__ALIGNED_SIGN_BIT,
+  STATS__CABAC_BITS__ALIGNED_ESCAPE_BITS,
+  STATS__NUM_STATS
+};
+
+static inline const Char* getName(TComCodingStatisticsType name)
+{
+  static const Char *statNames[]=
+  {
+    "NAL_UNIT_TOTAL_BODY", // This is a special case and is not included in the total sums.
+    "NAL_UNIT_PACKING",
+    "EMULATION_PREVENTION_3_BYTES",
+    "NAL_UNIT_HEADER_BITS",
+    "CABAC_INITIALISATION-and-rounding",
+    "CABAC_BITS__TQ_BYPASS_FLAG",
+    "CABAC_BITS__SKIP_FLAG",
+    "CABAC_BITS__MERGE_FLAG",
+    "CABAC_BITS__MERGE_INDEX",
+    "CABAC_BITS__MVP_IDX",
+    "CABAC_BITS__SPLIT_FLAG",
+    "CABAC_BITS__PART_SIZE",
+    "CABAC_BITS__PRED_MODE",
+    "CABAC_BITS__INTRA_DIR_ANG",
+    "CABAC_BITS__INTER_DIR",
+    "CABAC_BITS__REF_FRM_IDX",
+    "CABAC_BITS__MVD",
+    "CABAC_BITS__MVD_EP",
+    "CABAC_BITS__TRANSFORM_SUBDIV_FLAG",
+    "CABAC_BITS__QT_ROOT_CBF",
+    "CABAC_BITS__DELTA_QP_EP",
+    "CABAC_BITS__CHROMA_QP_ADJUSTMENT",
+    "CABAC_BITS__QT_CBF",
+    "CABAC_BITS__CROSS_COMPONENT_PREDICTION",
+    "CABAC_BITS__TRANSFORM_SKIP_FLAGS",
+    "CABAC_BITS__LAST_SIG_X_Y",
+    "CABAC_BITS__SIG_COEFF_GROUP_FLAG",
+    "CABAC_BITS__SIG_COEFF_MAP_FLAG",
+    "CABAC_BITS__GT1_FLAG",
+    "CABAC_BITS__GT2_FLAG",
+    "CABAC_BITS__SIGN_BIT",
+    "CABAC_BITS__ESCAPE_BITS",
+    "CABAC_BITS__SAO",
+    "CABAC_TRM_BITS",
+    "CABAC_FIXED_BITS",
+    "CABAC_PCM_ALIGN_BITS",
+    "CABAC_PCM_CODE_BITS",
+    "BYTE_ALIGNMENT_BITS",
+    "TRAILING_BITS",
+    "EXPLICIT_RDPCM_BITS",
+    "CABAC_EP_BIT_ALIGNMENT",
+    "CABAC_BITS__ALIGNED_SIGN_BIT",
+    "CABAC_BITS__ALIGNED_ESCAPE_BITS"
+  };
+  assert(STATS__NUM_STATS == sizeof(statNames)/sizeof(Char *) && name < STATS__NUM_STATS);
+  return statNames[name];
+}
+
+static inline Bool isAlignedBins(TComCodingStatisticsType statT) { return statT==STATS__CABAC_BITS__ALIGNED_SIGN_BIT || statT==STATS__CABAC_BITS__ALIGNED_ESCAPE_BITS; }
+
+static const UInt CODING_STATS_NUM_WIDTHS=7;
+static const UInt CODING_STATS_NUM_SUBCLASSES=CODING_STATS_NUM_WIDTHS*(1+MAX_NUM_COMPONENT+MAX_NUM_CHANNEL_TYPE);
+
+class TComCodingStatisticsClassType
+{
+public:
+
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t)
+    : type(t), subClass(0)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const UInt log2w )
+    : type(t), subClass(log2w)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const Int log2w )
+    : type(t), subClass(log2w)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const ComponentID cid )
+    : type(t), subClass((cid+1)*CODING_STATS_NUM_WIDTHS)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const ChannelType chid )
+    : type(t), subClass((chid+MAX_NUM_COMPONENT+1)*CODING_STATS_NUM_WIDTHS)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const UInt log2w, const ComponentID cid )
+    : type(t), subClass((cid+1)*CODING_STATS_NUM_WIDTHS + log2w)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const UInt log2w, const ChannelType chid )
+    : type(t), subClass((chid+MAX_NUM_COMPONENT+1)*CODING_STATS_NUM_WIDTHS + log2w)
+  { }
+
+  static UInt GetSubClassWidth(const UInt subClass)
+  {
+    return subClass%CODING_STATS_NUM_WIDTHS;
+  }
+
+  static const Char *GetSubClassString(const UInt subClass)
+  {
+    assert (subClass<CODING_STATS_NUM_SUBCLASSES);
+    static const Char *strings[1+MAX_NUM_COMPONENT+MAX_NUM_CHANNEL_TYPE]={"-", "Y", "Cb", "Cr", "Luma", "Chroma"};
+    return strings[subClass/CODING_STATS_NUM_WIDTHS];
+  }
+
+  TComCodingStatisticsType type;
+  UInt subClass;
+};
+
+
+
+class TComCodingStatistics
+{
+  public:
+
+
+    struct StatLogValue
+    {
+      UInt values[512+1];
+      StatLogValue()
+      {
+        const Double es=Double(TCOMCODINGSTATISTICS_ENTROPYSCALE);
+        values[0]=0;
+        for(UInt i=1; i<sizeof(values)/sizeof(UInt); i++)
+        {
+          values[i]=UInt(    log(Double(i))*es/log(2.0)  );
+        }
+      }
+    };
+
+    struct SStat
+    {
+      SStat() : bits(0), count(0), sum(0) { }
+      Int64 bits;
+      Int64 count;
+      Int64 sum;
+      Void clear() { bits=0; count=0; sum=0; }
+
+      SStat &operator+=(const SStat &src)
+      { bits+=src.bits; count+=src.count; sum+=src.sum; return *this; }
+    };
+
+    class TComCodingStatisticsData
+    {
+      private:
+        SStat statistics[STATS__NUM_STATS+1][CODING_STATS_NUM_SUBCLASSES];
+        SStat statistics_ep[STATS__NUM_STATS+1][CODING_STATS_NUM_SUBCLASSES ];
+        std::map<std::string, SStat> mappings_ep;
+        friend class TComCodingStatistics;
+    };
+
+  private:
+
+    TComCodingStatisticsData data;
+
+    TComCodingStatistics() : data()
+    { }
+
+    static Void OutputLine(const Char *pName, const Char sep, UInt width, const Char *pSubClassStr, const SStat &sCABAC, const SStat &sEP)
+    {
+      if (width==0)
+      {
+        OutputLine(pName, sep, "-", pSubClassStr, sCABAC, sEP);
+      }
+      else
+      {
+        printf("%c%-45s%c  %6d %6s %12lld %12lld %12lld %12lld %12lld %12lld %12lld (%12lld)%c\n",
+          sep=='~'?'[':' ', pName, sep, 1<<width, pSubClassStr,
+              sCABAC.count, sCABAC.sum, sCABAC.bits, sEP.count, sEP.sum, sEP.bits, sCABAC.bits+sEP.bits, (sCABAC.bits+sEP.bits)/8, sep=='~'?']':' ');
+      }
+    }
+    static Void OutputLine(const Char *pName, const Char sep, const Char *pWidthString, const Char *pSubClassStr, const SStat &sCABAC, const SStat &sEP)
+    {
+      printf("%c%-45s%c  %6s %6s %12lld %12lld %12lld %12lld %12lld %12lld %12lld (%12lld)%c\n",
+          sep=='~'?'[':' ', pName, sep, pWidthString, pSubClassStr,
+              sCABAC.count, sCABAC.sum, sCABAC.bits, sEP.count, sEP.sum, sEP.bits, sCABAC.bits+sEP.bits, (sCABAC.bits+sEP.bits)/8, sep=='~'?']':' ');
+    }
+    static Void OutputLine(const Char *pName, const Char sep, const Char *pWidthString, const Char *pSubClassStr,  const SStat &sEP)
+    {
+      printf("%c%-45s%c  %6s %6s %12s %12s %12s %12lld %12lld %12lld %12lld (%12lld)%c\n",
+          sep=='~'?'[':' ', pName, sep, pWidthString, pSubClassStr,
+              "", "", "", sEP.count, sEP.sum, sEP.bits, sEP.bits, (sEP.bits)/8, sep=='~'?']':' ');
+    }
+
+    static Void OutputDashedLine(const Char *pText)
+    {
+      printf("--%s",pText);
+      UInt tot=0;
+      for(;pText[tot]!=0; tot++);
+
+      tot+=2;
+      for (; tot<168; tot++)
+      {
+        printf("-");
+      }
+      printf("\n");
+    }
+
+    ~TComCodingStatistics()
+    {
+      const Int64 es=TCOMCODINGSTATISTICS_ENTROPYSCALE;
+
+      Int64 cr=0; // CABAC remainder, which is added to "STATS__CABAC_INITIALISATION"
+      {
+        Int64 totalCABACbits=0, roundedCABACbits=0;
+        for(Int i=STATS__NAL_UNIT_PACKING; i<STATS__NUM_STATS; i++)
+        {
+          for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c++)
+          {
+            totalCABACbits+=data.statistics[i][c].bits;
+            roundedCABACbits+=data.statistics[i][c].bits/es;
+          }
+        }
+        Int64 remainder=totalCABACbits - roundedCABACbits*es;
+        cr=(remainder+es/2)/es;
+      }
+
+      printf("Note %s will be excluded from the total as it should be the sum of all the other entries (except for %s)\n", getName(STATS__NAL_UNIT_TOTAL_BODY), getName(STATS__NAL_UNIT_PACKING));
+      printf(" %-45s-   Width   Type  CABAC Count    CABAC Sum   CABAC bits     EP Count       EP Sum      EP bits   Total bits ( Total bytes)\n", "Decoder statistics");
+
+      OutputDashedLine("");
+      SStat cabacTotalBits, epTotalBits;
+      SStat statTotals_cabac[CODING_STATS_NUM_SUBCLASSES];
+      SStat statTotals_ep[CODING_STATS_NUM_SUBCLASSES];
+
+      for(Int i=0; i<STATS__NUM_STATS; i++)
+      {
+        SStat cabacSubTotal, epSubTotal;
+        Bool bHadClassifiedEntry=false;
+        const Char *pName=getName(TComCodingStatisticsType(i));
+
+        for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c++)
+        {
+          SStat &sCABACorig=data.statistics[i][c];
+          SStat &sEP=data.statistics_ep[i][c];
+
+          if (sCABACorig.bits==0 && sEP.bits==0)
+          {
+            continue;
+          }
+
+          SStat sCABAC;
+          {
+            Int64 thisCABACbits=sCABACorig.bits/es;
+            if (i==STATS__CABAC_INITIALISATION && sCABACorig.bits!=0)
+            {
+              thisCABACbits+=cr;
+              cr=0;
+            }
+            sCABAC.bits=thisCABACbits;
+            sCABAC.count=sCABACorig.count;
+            sCABAC.sum=sCABACorig.sum;
+          }
+          UInt width=TComCodingStatisticsClassType::GetSubClassWidth(c);
+          OutputLine(pName, ':', width, TComCodingStatisticsClassType::GetSubClassString(c), sCABAC, sEP);
+          cabacSubTotal+=sCABAC;
+          epSubTotal+=sEP;
+          if (i!=STATS__NAL_UNIT_TOTAL_BODY)
+          {
+            cabacTotalBits+=sCABAC;
+            epTotalBits+=sEP;
+            statTotals_cabac[c]+=sCABAC;
+            statTotals_ep[c]+=sEP;
+          }
+          bHadClassifiedEntry=bHadClassifiedEntry||(c!=0);
+        }
+        if (bHadClassifiedEntry)
+        {
+          OutputLine(pName, '~', "~~ST~~", "~~ST~~", cabacSubTotal, epSubTotal);
+        }
+        if (i==STATS__NAL_UNIT_TOTAL_BODY)
+        {
+          OutputDashedLine("");
+        }
+      }
+      OutputDashedLine("");
+      OutputLine("CABAC Sub-total", '~', "~~ST~~", "~~ST~~", cabacTotalBits, epTotalBits);
+
+      OutputDashedLine("CAVLC HEADER BITS");
+      SStat cavlcTotalBits;
+      for(std::map<std::string, SStat>::iterator it=data.mappings_ep.begin(); it!=data.mappings_ep.end(); it++)
+      {
+        SStat s=it->second;
+        cavlcTotalBits+=s;
+        OutputLine(it->first.c_str(), ':', "-", "-", s);
+      }
+
+      OutputDashedLine("");
+      OutputLine("CAVLC Header Sub-total", '~', "~~ST~~", "~~ST~~", cavlcTotalBits);
+
+      // Now output the breakdowns
+      OutputDashedLine("CABAC Break down by size");
+      for(UInt s=0; s<CODING_STATS_NUM_WIDTHS; s++)
+      {
+        SStat subTotalCabac, subTotalEP;
+        for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c+=CODING_STATS_NUM_WIDTHS)
+        {
+          subTotalCabac+=statTotals_cabac[c+s];
+          subTotalEP+=statTotals_ep[c+s];
+        }
+        if (subTotalCabac.bits!=0 || subTotalEP.bits!=0)
+        {
+          OutputLine("CABAC by size Sub-total", '=', s, "All", subTotalCabac, subTotalEP);
+        }
+      }
+      OutputDashedLine("Break down by component/Channel type");
+      for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c+=CODING_STATS_NUM_WIDTHS)
+      {
+        SStat subTotalCabac, subTotalEP;
+        for(UInt s=0; s<CODING_STATS_NUM_WIDTHS; s++)
+        {
+          subTotalCabac+=statTotals_cabac[c+s];
+          subTotalEP+=statTotals_ep[c+s];
+        }
+        if (subTotalCabac.bits!=0 || subTotalEP.bits!=0)
+        {
+          OutputLine("CABAC by type Sub-total", '=', "-", TComCodingStatisticsClassType::GetSubClassString(c), subTotalCabac, subTotalEP);
+        }
+      }
+      OutputDashedLine("Break down by size and component/Channel type");
+      for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c+=CODING_STATS_NUM_WIDTHS)
+      {
+        for(UInt s=0; s<CODING_STATS_NUM_WIDTHS; s++)
+        {
+          SStat subTotalCabac, subTotalEP;
+          subTotalCabac+=statTotals_cabac[c+s];
+          subTotalEP+=statTotals_ep[c+s];
+          if (subTotalCabac.bits!=0 || subTotalEP.bits!=0)
+          {
+            OutputLine("CABAC by size and type Sub-total", '=', s, TComCodingStatisticsClassType::GetSubClassString(c), subTotalCabac, subTotalEP);
+          }
+        }
+      }
+
+      OutputDashedLine("");
+      OutputLine("CABAC Sub-total", '~', "~~ST~~", "~~ST~~", cabacTotalBits, epTotalBits);
+      OutputLine("CAVLC Header Sub-total", '~', "~~ST~~", "~~ST~~", cavlcTotalBits);
+      OutputDashedLine("GRAND TOTAL");
+      epTotalBits+=cavlcTotalBits;
+      OutputLine("TOTAL", '~', "~~GT~~", "~~GT~~", cabacTotalBits, epTotalBits);
+    }
+
+
+  public:
+    static TComCodingStatistics& GetSingletonInstance()
+    {
+      static TComCodingStatistics inst;
+      return inst;
+    }
+
+    static const TComCodingStatisticsData &GetStatistics()         { return GetSingletonInstance().data; }
+    static Void SetStatistics(const TComCodingStatisticsData &src) { GetSingletonInstance().data=src; }
+
+    static SStat &GetStatisticEP(const TComCodingStatisticsClassType &stat) { return GetSingletonInstance().data.statistics_ep[stat.type][stat.subClass]; }
+
+    static SStat &GetStatisticEP(const std::string &str) { return GetSingletonInstance().data.mappings_ep[str]; }
+
+    static SStat &GetStatisticEP(const Char *pKey) {return GetStatisticEP(std::string(pKey)); }
+
+    static Void IncrementStatisticEP(const TComCodingStatisticsClassType &stat, const Int numBits, const Int value)
+    {
+      SStat &s=GetStatisticEP(stat);
+      s.bits+=numBits;
+      s.count++;
+      s.sum+=value;
+    }
+
+    static Void IncrementStatisticEP(const std::string &str, const Int numBits, const Int value)
+    {
+      SStat &s=GetStatisticEP(str);
+      s.bits+=numBits;
+      s.count++;
+      s.sum+=value;
+    }
+
+    static Void IncrementStatisticEP(const Char *pKey, const Int numBits, const Int value)
+    {
+      SStat &s=GetStatisticEP(pKey);
+      s.bits+=numBits;
+      s.count++;
+      s.sum+=value;
+    }
+
+    StatLogValue values;
+
+    static Void UpdateCABACStat(const TComCodingStatisticsClassType &stat, UInt uiRangeBefore, UInt uiRangeAfter, Int val)
+    {
+      TComCodingStatistics &inst=GetSingletonInstance();
+      // doing rangeBefore*p(x)=rangeAfter
+      // p(x)=rangeAfter/rangeBefore
+      // entropy = -log2(p(x))=-log(p(x))/log(2) = -(log rangeAfter - log rangeBefore) / log(2) = (log rangeBefore / log 2 - log rangeAfter / log 2)
+      SStat &s=inst.data.statistics[stat.type][stat.subClass];
+      s.bits+=inst.values.values[uiRangeBefore]-inst.values.values[uiRangeAfter];
+      s.count++;
+      s.sum+=val;
+    }
+};
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,14 +38,9 @@
 
 #include "TComDataCU.h"
+#include "TComTU.h"
 #include "TComPic.h"
 
 //! \ingroup TLibCommon
 //! \{
-
-#if ADAPTIVE_QP_SELECTION
-Int * TComDataCU::m_pcGlbArlCoeffY  = NULL;
-Int * TComDataCU::m_pcGlbArlCoeffCb = NULL;
-Int * TComDataCU::m_pcGlbArlCoeffCr = NULL;
-#endif
 
 // ====================================================================================================================
@@ -58,5 +53,5 @@
   m_pcSlice            = NULL;
   m_puhDepth           = NULL;
-  
+
   m_skipFlag           = NULL;
 #if H_3D
@@ -70,45 +65,42 @@
   m_puhHeight          = NULL;
   m_phQP               = NULL;
+  m_ChromaQpAdj        = NULL;
   m_pbMergeFlag        = NULL;
   m_puhMergeIndex      = NULL;
-  m_puhLumaIntraDir    = NULL;
-  m_puhChromaIntraDir  = NULL;
+  for(UInt i=0; i<MAX_NUM_CHANNEL_TYPE; i++)
+  {
+    m_puhIntraDir[i]     = NULL;
+  }
   m_puhInterDir        = NULL;
   m_puhTrIdx           = NULL;
-  m_puhTransformSkip[0] = NULL;
-  m_puhTransformSkip[1] = NULL;
-  m_puhTransformSkip[2] = NULL;
-  m_puhCbf[0]          = NULL;
-  m_puhCbf[1]          = NULL;
-  m_puhCbf[2]          = NULL;
-  m_pcTrCoeffY         = NULL;
-  m_pcTrCoeffCb        = NULL;
-  m_pcTrCoeffCr        = NULL;
-#if ADAPTIVE_QP_SELECTION  
+
+  for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    m_puhCbf[comp]                        = NULL;
+    m_crossComponentPredictionAlpha[comp] = NULL;
+    m_puhTransformSkip[comp]              = NULL;
+    m_pcTrCoeff[comp]                     = NULL;
+#if ADAPTIVE_QP_SELECTION
+    m_pcArlCoeff[comp]                    = NULL;
+#endif
+    m_pcIPCMSample[comp]                  = NULL;
+    m_explicitRdpcmMode[comp]             = NULL;
+  }
+#if ADAPTIVE_QP_SELECTION
   m_ArlCoeffIsAliasedAllocation = false;
-  m_pcArlCoeffY        = NULL;
-  m_pcArlCoeffCb       = NULL;
-  m_pcArlCoeffCr       = NULL;
-#endif
-  
+#endif
   m_pbIPCMFlag         = NULL;
-  m_pcIPCMSampleY      = NULL;
-  m_pcIPCMSampleCb     = NULL;
-  m_pcIPCMSampleCr     = NULL;
-
-  m_pcPattern          = NULL;
-  
-  m_pcCUAboveLeft      = NULL;
-  m_pcCUAboveRight     = NULL;
-  m_pcCUAbove          = NULL;
-  m_pcCULeft           = NULL;
-  
-  m_apcCUColocated[0]  = NULL;
-  m_apcCUColocated[1]  = NULL;
-  
-  m_apiMVPIdx[0]       = NULL;
-  m_apiMVPIdx[1]       = NULL;
-  m_apiMVPNum[0]       = NULL;
-  m_apiMVPNum[1]       = NULL;
+
+  m_pCtuAboveLeft      = NULL;
+  m_pCtuAboveRight     = NULL;
+  m_pCtuAbove          = NULL;
+  m_pCtuLeft           = NULL;
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = NULL;
+    m_apiMVPIdx[i]       = NULL;
+    m_apiMVPNum[i]       = NULL;
+  }
 
 #if H_3D_DIM
@@ -130,7 +122,7 @@
 #endif
 #endif
+
   m_bDecSubCu          = false;
-  m_sliceStartCU        = 0;
-  m_sliceSegmentStartCU = 0;
+
 #if H_3D_NBDV
   m_pDvInfo              = NULL;
@@ -153,4 +145,5 @@
   m_pbDBBPFlag         = NULL;
 #endif
+
 }
 
@@ -159,17 +152,17 @@
 }
 
-Void TComDataCU::create(UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+Void TComDataCU::create( ChromaFormat chromaFormatIDC, UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
 #if ADAPTIVE_QP_SELECTION
-                        , Bool bGlobalRMARLBuffer
-#endif                                              
+                        , TCoeff *pParentARLBuffer
+#endif
                         )
 {
   m_bDecSubCu = bDecSubCu;
-  
+
   m_pcPic              = NULL;
   m_pcSlice            = NULL;
   m_uiNumPartition     = uiNumPartition;
   m_unitSize = unitSize;
-  
+
   if ( !bDecSubCu )
   {
@@ -179,4 +172,5 @@
     m_puhHeight          = (UChar*    )xMalloc(UChar,    uiNumPartition);
 
+    m_ChromaQpAdj        = new UChar[ uiNumPartition ];
     m_skipFlag           = new Bool[ uiNumPartition ];
 #if H_3D
@@ -185,7 +179,8 @@
 #endif
     m_pePartSize         = new Char[ uiNumPartition ];
-    memset( m_pePartSize, SIZE_NONE,uiNumPartition * sizeof( *m_pePartSize ) );
+    memset( m_pePartSize, NUMBER_OF_PART_SIZES,uiNumPartition * sizeof( *m_pePartSize ) );
     m_pePredMode         = new Char[ uiNumPartition ];
     m_CUTransquantBypass = new Bool[ uiNumPartition ];
+
     m_pbMergeFlag        = (Bool*  )xMalloc(Bool,   uiNumPartition);
     m_puhMergeIndex      = (UChar* )xMalloc(UChar,  uiNumPartition);
@@ -196,63 +191,62 @@
     m_pbSPIVMPFlag       = (Bool*  )xMalloc(Bool,   uiNumPartition);
 #endif
-    m_puhLumaIntraDir    = (UChar* )xMalloc(UChar,  uiNumPartition);
-    m_puhChromaIntraDir  = (UChar* )xMalloc(UChar,  uiNumPartition);
+
+    for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+    {
+      m_puhIntraDir[ch] = (UChar* )xMalloc(UChar,  uiNumPartition);
+    }
     m_puhInterDir        = (UChar* )xMalloc(UChar,  uiNumPartition);
-    
+
     m_puhTrIdx           = (UChar* )xMalloc(UChar,  uiNumPartition);
-    m_puhTransformSkip[0] = (UChar* )xMalloc(UChar,  uiNumPartition);
-    m_puhTransformSkip[1] = (UChar* )xMalloc(UChar,  uiNumPartition);
-    m_puhTransformSkip[2] = (UChar* )xMalloc(UChar,  uiNumPartition);
-
-    m_puhCbf[0]          = (UChar* )xMalloc(UChar,  uiNumPartition);
-    m_puhCbf[1]          = (UChar* )xMalloc(UChar,  uiNumPartition);
-    m_puhCbf[2]          = (UChar* )xMalloc(UChar,  uiNumPartition);
-    
-    m_apiMVPIdx[0]       = new Char[ uiNumPartition ];
-    m_apiMVPIdx[1]       = new Char[ uiNumPartition ];
-    m_apiMVPNum[0]       = new Char[ uiNumPartition ];
-    m_apiMVPNum[1]       = new Char[ uiNumPartition ];
-    memset( m_apiMVPIdx[0], -1,uiNumPartition * sizeof( Char ) );
-    memset( m_apiMVPIdx[1], -1,uiNumPartition * sizeof( Char ) );
-    
-    m_pcTrCoeffY         = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight);
-    m_pcTrCoeffCb        = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight/4);
-    m_pcTrCoeffCr        = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight/4);
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      m_apiMVPIdx[rpl]       = new Char[ uiNumPartition ];
+      m_apiMVPNum[rpl]       = new Char[ uiNumPartition ];
+      memset( m_apiMVPIdx[rpl], -1,uiNumPartition * sizeof( Char ) );
+    }
+
 #if H_3D_NBDV 
     m_pDvInfo            = (DisInfo* )xMalloc(DisInfo,  uiNumPartition);
 #endif
-    memset( m_pcTrCoeffY, 0,uiWidth*uiHeight * sizeof( TCoeff ) );
-    memset( m_pcTrCoeffCb, 0,uiWidth*uiHeight/4 * sizeof( TCoeff ) );
-    memset( m_pcTrCoeffCr, 0,uiWidth*uiHeight/4 * sizeof( TCoeff ) );
-#if ADAPTIVE_QP_SELECTION    
-    if( bGlobalRMARLBuffer )
-    {
-      if( m_pcGlbArlCoeffY == NULL )
-      {
-        m_pcGlbArlCoeffY   = (Int*)xMalloc(Int, uiWidth*uiHeight);
-        m_pcGlbArlCoeffCb  = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
-        m_pcGlbArlCoeffCr  = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
-      }
-      m_pcArlCoeffY        = m_pcGlbArlCoeffY;
-      m_pcArlCoeffCb       = m_pcGlbArlCoeffCb;
-      m_pcArlCoeffCr       = m_pcGlbArlCoeffCr;
-      m_ArlCoeffIsAliasedAllocation = true;
-    }
-    else
-    {
-      m_pcArlCoeffY        = (Int*)xMalloc(Int, uiWidth*uiHeight);
-      m_pcArlCoeffCb       = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
-      m_pcArlCoeffCr       = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
-    }
-#endif
-    
+
+
+    for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+    {
+      const ComponentID compID = ComponentID(comp);
+      const UInt chromaShift = getComponentScaleX(compID, chromaFormatIDC) + getComponentScaleY(compID, chromaFormatIDC);
+      const UInt totalSize   = (uiWidth * uiHeight) >> chromaShift;
+
+      m_crossComponentPredictionAlpha[compID] = (Char*  )xMalloc(Char,   uiNumPartition);
+      m_puhTransformSkip[compID]              = (UChar* )xMalloc(UChar,  uiNumPartition);
+      m_explicitRdpcmMode[compID]             = (UChar* )xMalloc(UChar,  uiNumPartition);
+      m_puhCbf[compID]                        = (UChar* )xMalloc(UChar,  uiNumPartition);
+      m_pcTrCoeff[compID]                     = (TCoeff*)xMalloc(TCoeff, totalSize);
+      memset( m_pcTrCoeff[compID], 0, (totalSize * sizeof( TCoeff )) );
+
+#if ADAPTIVE_QP_SELECTION
+      if( pParentARLBuffer != 0 )
+      {
+        m_pcArlCoeff[compID] = pParentARLBuffer;
+        m_ArlCoeffIsAliasedAllocation = true;
+        pParentARLBuffer += totalSize;
+      }
+      else
+      {
+        m_pcArlCoeff[compID] = (TCoeff*)xMalloc(TCoeff, totalSize);
+        m_ArlCoeffIsAliasedAllocation = false;
+      }
+#endif
+      m_pcIPCMSample[compID] = (Pel*   )xMalloc(Pel , totalSize);
+    }
+
     m_pbIPCMFlag         = (Bool*  )xMalloc(Bool, uiNumPartition);
-    m_pcIPCMSampleY      = (Pel*   )xMalloc(Pel , uiWidth*uiHeight);
-    m_pcIPCMSampleCb     = (Pel*   )xMalloc(Pel , uiWidth*uiHeight/4);
-    m_pcIPCMSampleCr     = (Pel*   )xMalloc(Pel , uiWidth*uiHeight/4);
-
-    m_acCUMvField[0].create( uiNumPartition );
-    m_acCUMvField[1].create( uiNumPartition );
-    
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acCUMvField[i].create( uiNumPartition );
+    }
+
 #if H_3D_ARP
     m_puhARPW            = new UChar[ uiNumPartition];
@@ -282,61 +276,100 @@
     m_pbDBBPFlag         = (Bool*  )xMalloc(Bool,   uiNumPartition);
 #endif
+
   }
   else
   {
-    m_acCUMvField[0].setNumPartition(uiNumPartition );
-    m_acCUMvField[1].setNumPartition(uiNumPartition );
-  }
-  m_sliceStartCU        = (UInt*  )xMalloc(UInt, uiNumPartition);
-  m_sliceSegmentStartCU = (UInt*  )xMalloc(UInt, uiNumPartition);
-  
-  // create pattern memory
-  m_pcPattern            = (TComPattern*)xMalloc(TComPattern, 1);
-
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acCUMvField[i].setNumPartition(uiNumPartition );
+    }
+  }
 
   // create motion vector fields
-  
-  m_pcCUAboveLeft      = NULL;
-  m_pcCUAboveRight     = NULL;
-  m_pcCUAbove          = NULL;
-  m_pcCULeft           = NULL;
-  
-  m_apcCUColocated[0]  = NULL;
-  m_apcCUColocated[1]  = NULL;
+
+  m_pCtuAboveLeft      = NULL;
+  m_pCtuAboveRight     = NULL;
+  m_pCtuAbove          = NULL;
+  m_pCtuLeft           = NULL;
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = NULL;
+  }
 }
 
 Void TComDataCU::destroy()
 {
-  m_pcPic              = NULL;
-  m_pcSlice            = NULL;
-  
-  if ( m_pcPattern )
-  { 
-    xFree(m_pcPattern);
-    m_pcPattern = NULL;
-  }
-  
   // encoder-side buffer free
   if ( !m_bDecSubCu )
   {
-    if ( m_phQP               ) { xFree(m_phQP);                m_phQP              = NULL; }
-    if ( m_puhDepth           ) { xFree(m_puhDepth);            m_puhDepth          = NULL; }
-    if ( m_puhWidth           ) { xFree(m_puhWidth);            m_puhWidth          = NULL; }
-    if ( m_puhHeight          ) { xFree(m_puhHeight);           m_puhHeight         = NULL; }
-
-    if ( m_skipFlag           ) { delete[] m_skipFlag;          m_skipFlag          = NULL; }
+    if ( m_phQP )
+    {
+      xFree(m_phQP);
+      m_phQP = NULL;
+    }
+    if ( m_puhDepth )
+    {
+      xFree(m_puhDepth);
+      m_puhDepth = NULL;
+    }
+    if ( m_puhWidth )
+    {
+      xFree(m_puhWidth);
+      m_puhWidth = NULL;
+    }
+    if ( m_puhHeight )
+    {
+      xFree(m_puhHeight);
+      m_puhHeight = NULL;
+    }
+
+    if ( m_skipFlag )
+    {
+      delete[] m_skipFlag;
+      m_skipFlag = NULL;
+    }
+
 #if H_3D
     if ( m_bDISFlag           ) { delete[] m_bDISFlag;   m_bDISFlag     = NULL; }
     if ( m_uiDISType         ) { xFree(m_uiDISType);  m_uiDISType    = NULL; }
 #endif
-    if ( m_pePartSize         ) { delete[] m_pePartSize;        m_pePartSize        = NULL; }
-    if ( m_pePredMode         ) { delete[] m_pePredMode;        m_pePredMode        = NULL; }
-    if ( m_CUTransquantBypass ) { delete[] m_CUTransquantBypass;m_CUTransquantBypass = NULL; }
-    if ( m_puhCbf[0]          ) { xFree(m_puhCbf[0]);           m_puhCbf[0]         = NULL; }
-    if ( m_puhCbf[1]          ) { xFree(m_puhCbf[1]);           m_puhCbf[1]         = NULL; }
-    if ( m_puhCbf[2]          ) { xFree(m_puhCbf[2]);           m_puhCbf[2]         = NULL; }
-    if ( m_puhInterDir        ) { xFree(m_puhInterDir);         m_puhInterDir       = NULL; }
-    if ( m_pbMergeFlag        ) { xFree(m_pbMergeFlag);         m_pbMergeFlag       = NULL; }
-    if ( m_puhMergeIndex      ) { xFree(m_puhMergeIndex);       m_puhMergeIndex     = NULL; }
+
+    if ( m_pePartSize )
+    {
+      delete[] m_pePartSize;
+      m_pePartSize = NULL;
+    }
+    if ( m_pePredMode )
+    {
+      delete[] m_pePredMode;
+      m_pePredMode = NULL;
+    }
+    if ( m_ChromaQpAdj )
+    {
+      delete[] m_ChromaQpAdj;
+      m_ChromaQpAdj = NULL;
+    }
+    if ( m_CUTransquantBypass )
+    {
+      delete[] m_CUTransquantBypass;
+      m_CUTransquantBypass = NULL;
+    }
+    if ( m_puhInterDir )
+    {
+      xFree(m_puhInterDir);
+      m_puhInterDir = NULL;
+    }
+    if ( m_pbMergeFlag )
+    {
+      xFree(m_pbMergeFlag);
+      m_pbMergeFlag = NULL;
+    }
+    if ( m_puhMergeIndex )
+    {
+      xFree(m_puhMergeIndex);
+      m_puhMergeIndex  = NULL;
+    }
+
 #if H_3D_VSP
     if ( m_piVSPFlag          ) { xFree(m_piVSPFlag);           m_piVSPFlag         = NULL; }
@@ -345,32 +378,89 @@
     if ( m_pbSPIVMPFlag       ) { xFree(m_pbSPIVMPFlag);           m_pbSPIVMPFlag         = NULL; }
 #endif
-    if ( m_puhLumaIntraDir    ) { xFree(m_puhLumaIntraDir);     m_puhLumaIntraDir   = NULL; }
-    if ( m_puhChromaIntraDir  ) { xFree(m_puhChromaIntraDir);   m_puhChromaIntraDir = NULL; }
-    if ( m_puhTrIdx           ) { xFree(m_puhTrIdx);            m_puhTrIdx          = NULL; }
-    if ( m_puhTransformSkip[0]) { xFree(m_puhTransformSkip[0]); m_puhTransformSkip[0] = NULL; }
-    if ( m_puhTransformSkip[1]) { xFree(m_puhTransformSkip[1]); m_puhTransformSkip[1] = NULL; }
-    if ( m_puhTransformSkip[2]) { xFree(m_puhTransformSkip[2]); m_puhTransformSkip[2] = NULL; }
-    if ( m_pcTrCoeffY         ) { xFree(m_pcTrCoeffY);          m_pcTrCoeffY        = NULL; }
-    if ( m_pcTrCoeffCb        ) { xFree(m_pcTrCoeffCb);         m_pcTrCoeffCb       = NULL; }
-    if ( m_pcTrCoeffCr        ) { xFree(m_pcTrCoeffCr);         m_pcTrCoeffCr       = NULL; }
+
+
+    for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+    {
+      xFree(m_puhIntraDir[ch]);
+      m_puhIntraDir[ch] = NULL;
+    }
+
+    if ( m_puhTrIdx )
+    {
+      xFree(m_puhTrIdx);
+      m_puhTrIdx = NULL;
+    }
+
+    for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+    {
+      if ( m_crossComponentPredictionAlpha[comp] )
+      {
+        xFree(m_crossComponentPredictionAlpha[comp]);
+        m_crossComponentPredictionAlpha[comp] = NULL;
+      }
+      if ( m_puhTransformSkip[comp] )
+      {
+        xFree(m_puhTransformSkip[comp]);
+        m_puhTransformSkip[comp] = NULL;
+      }
+      if ( m_puhCbf[comp] )
+      {
+        xFree(m_puhCbf[comp]);
+        m_puhCbf[comp] = NULL;
+      }
+      if ( m_pcTrCoeff[comp] )
+      {
+        xFree(m_pcTrCoeff[comp]);
+        m_pcTrCoeff[comp] = NULL;
+      }
+      if ( m_explicitRdpcmMode[comp] )
+      {
+        xFree(m_explicitRdpcmMode[comp]);
+        m_explicitRdpcmMode[comp] = NULL;
+      }
+
 #if ADAPTIVE_QP_SELECTION
-    if (!m_ArlCoeffIsAliasedAllocation)
-    {
-      xFree(m_pcArlCoeffY); m_pcArlCoeffY = 0;
-      xFree(m_pcArlCoeffCb); m_pcArlCoeffCb = 0;
-      xFree(m_pcArlCoeffCr); m_pcArlCoeffCr = 0;
-    }
-    if ( m_pcGlbArlCoeffY     ) { xFree(m_pcGlbArlCoeffY);      m_pcGlbArlCoeffY    = NULL; }
-    if ( m_pcGlbArlCoeffCb    ) { xFree(m_pcGlbArlCoeffCb);     m_pcGlbArlCoeffCb   = NULL; }
-    if ( m_pcGlbArlCoeffCr    ) { xFree(m_pcGlbArlCoeffCr);     m_pcGlbArlCoeffCr   = NULL; }
-#endif
-    if ( m_pbIPCMFlag         ) { xFree(m_pbIPCMFlag   );       m_pbIPCMFlag        = NULL; }
-    if ( m_pcIPCMSampleY      ) { xFree(m_pcIPCMSampleY);       m_pcIPCMSampleY     = NULL; }
-    if ( m_pcIPCMSampleCb     ) { xFree(m_pcIPCMSampleCb);      m_pcIPCMSampleCb    = NULL; }
-    if ( m_pcIPCMSampleCr     ) { xFree(m_pcIPCMSampleCr);      m_pcIPCMSampleCr    = NULL; }
-    if ( m_apiMVPIdx[0]       ) { delete[] m_apiMVPIdx[0];      m_apiMVPIdx[0]      = NULL; }
-    if ( m_apiMVPIdx[1]       ) { delete[] m_apiMVPIdx[1];      m_apiMVPIdx[1]      = NULL; }
-    if ( m_apiMVPNum[0]       ) { delete[] m_apiMVPNum[0];      m_apiMVPNum[0]      = NULL; }
-    if ( m_apiMVPNum[1]       ) { delete[] m_apiMVPNum[1];      m_apiMVPNum[1]      = NULL; }
+      if (!m_ArlCoeffIsAliasedAllocation)
+      {
+        if ( m_pcArlCoeff[comp] )
+        {
+          xFree(m_pcArlCoeff[comp]);
+          m_pcArlCoeff[comp] = NULL;
+        }
+      }
+#endif
+
+      if ( m_pcIPCMSample[comp] )
+      {
+        xFree(m_pcIPCMSample[comp]);
+        m_pcIPCMSample[comp] = NULL;
+      }
+    }
+    if ( m_pbIPCMFlag )
+    {
+      xFree(m_pbIPCMFlag );
+      m_pbIPCMFlag = NULL;
+    }
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      if ( m_apiMVPIdx[rpl] )
+      {
+        delete[] m_apiMVPIdx[rpl];
+        m_apiMVPIdx[rpl] = NULL;
+      }
+      if ( m_apiMVPNum[rpl] )
+      {
+        delete[] m_apiMVPNum[rpl];
+        m_apiMVPNum[rpl] = NULL;
+      }
+    }
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      m_acCUMvField[rpl].destroy();
+    }
 #if H_3D_NBDV 
     if ( m_pDvInfo            ) { xFree(m_pDvInfo);             m_pDvInfo           = NULL; }
@@ -384,6 +474,4 @@
     if ( m_pbICFlag           ) { xFree(m_pbICFlag);            m_pbICFlag          = NULL; }
 #endif
-    m_acCUMvField[0].destroy();
-    m_acCUMvField[1].destroy();
 
 #if H_3D_DIM
@@ -408,23 +496,58 @@
     if ( m_pbDBBPFlag         ) { xFree(m_pbDBBPFlag);          m_pbDBBPFlag        = NULL; }
 #endif
-  }
-  m_pcCUAboveLeft       = NULL;
-  m_pcCUAboveRight      = NULL;
-  m_pcCUAbove           = NULL;
-  m_pcCULeft            = NULL;
-  
-  m_apcCUColocated[0]   = NULL;
-  m_apcCUColocated[1]   = NULL;
-
-  if( m_sliceStartCU )
-  {
-    xFree(m_sliceStartCU);
-    m_sliceStartCU=NULL;
-  }
-  if(m_sliceSegmentStartCU )
-  {
-    xFree(m_sliceSegmentStartCU);
-    m_sliceSegmentStartCU=NULL;
-  }
+
+  }
+
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+
+  m_pCtuAboveLeft      = NULL;
+  m_pCtuAboveRight     = NULL;
+  m_pCtuAbove          = NULL;
+  m_pCtuLeft           = NULL;
+
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = NULL;
+  }
+
+}
+
+Bool TComDataCU::CUIsFromSameTile            ( const TComDataCU *pCU /* Can be NULL */) const
+{
+  return pCU!=NULL &&
+         pCU->getSlice() != NULL &&
+         m_pcPic->getPicSym()->getTileIdxMap( pCU->getCtuRsAddr() ) == m_pcPic->getPicSym()->getTileIdxMap(getCtuRsAddr());
+}
+
+Bool TComDataCU::CUIsFromSameSliceAndTile    ( const TComDataCU *pCU /* Can be NULL */) const
+{
+  return pCU!=NULL &&
+         pCU->getSlice() != NULL &&
+         pCU->getSlice()->getSliceCurStartCtuTsAddr() == getSlice()->getSliceCurStartCtuTsAddr() &&
+         m_pcPic->getPicSym()->getTileIdxMap( pCU->getCtuRsAddr() ) == m_pcPic->getPicSym()->getTileIdxMap(getCtuRsAddr())
+         ;
+}
+
+Bool TComDataCU::CUIsFromSameSliceTileAndWavefrontRow( const TComDataCU *pCU /* Can be NULL */) const
+{
+  return CUIsFromSameSliceAndTile(pCU)
+         && (!getSlice()->getPPS()->getEntropyCodingSyncEnabledFlag() || getPic()->getCtu(getCtuRsAddr())->getCUPelY() == getPic()->getCtu(pCU->getCtuRsAddr())->getCUPelY());
+}
+
+Bool TComDataCU::isLastSubCUOfCtu(const UInt absPartIdx)
+{
+  const TComSPS &sps=*(getSlice()->getSPS());
+
+  const UInt picWidth = sps.getPicWidthInLumaSamples();
+  const UInt picHeight = sps.getPicHeightInLumaSamples();
+  const UInt granularityWidth = sps.getMaxCUWidth();
+
+  const UInt cuPosX = getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[absPartIdx] ];
+  const UInt cuPosY = getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[absPartIdx] ];
+
+  return (((cuPosX+getWidth( absPartIdx))%granularityWidth==0||(cuPosX+getWidth( absPartIdx)==picWidth ))
+       && ((cuPosY+getHeight(absPartIdx))%granularityWidth==0||(cuPosY+getHeight(absPartIdx)==picHeight)));
 }
 
@@ -438,64 +561,41 @@
 
 /**
- - initialize top-level CU
- - internal buffers are already created
- - set values before encoding a CU
- .
- \param  pcPic     picture (TComPic) class pointer
- \param  iCUAddr   CU address
+ Initialize top-level CU: create internal buffers and set initial values before encoding the CTU.
+ 
+ \param  pcPic       picture (TComPic) class pointer
+ \param  ctuRsAddr   CTU address in raster scan order
  */
-Void TComDataCU::initCU( TComPic* pcPic, UInt iCUAddr )
-{
-
+Void TComDataCU::initCtu( TComPic* pcPic, UInt ctuRsAddr )
+{
+
+  const UInt maxCUWidth = pcPic->getPicSym()->getSPS().getMaxCUWidth();
+  const UInt maxCUHeight= pcPic->getPicSym()->getSPS().getMaxCUHeight();
   m_pcPic              = pcPic;
   m_pcSlice            = pcPic->getSlice(pcPic->getCurrSliceIdx());
-  m_uiCUAddr           = iCUAddr;
-  m_uiCUPelX           = ( iCUAddr % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth;
-  m_uiCUPelY           = ( iCUAddr / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight;
-  m_uiAbsIdxInLCU      = 0;
+  m_ctuRsAddr          = ctuRsAddr;
+  m_uiCUPelX           = ( ctuRsAddr % pcPic->getFrameWidthInCtus() ) * maxCUWidth;
+  m_uiCUPelY           = ( ctuRsAddr / pcPic->getFrameWidthInCtus() ) * maxCUHeight;
+  m_absZIdxInCtu       = 0;
   m_dTotalCost         = MAX_DOUBLE;
   m_uiTotalDistortion  = 0;
   m_uiTotalBits        = 0;
   m_uiTotalBins        = 0;
-  m_uiNumPartition     = pcPic->getNumPartInCU();
-  
-  for(Int i=0; i<pcPic->getNumPartInCU(); i++)
-  {
-    if(pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr)*pcPic->getNumPartInCU()+i>=getSlice()->getSliceCurStartCUAddr())
-    {
-      m_sliceStartCU[i]=getSlice()->getSliceCurStartCUAddr();
-    }
-    else
-    {
-      m_sliceStartCU[i]=pcPic->getCU(getAddr())->m_sliceStartCU[i];
-    }
-  }
-  for(Int i=0; i<pcPic->getNumPartInCU(); i++)
-  {
-    if(pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr)*pcPic->getNumPartInCU()+i>=getSlice()->getSliceSegmentCurStartCUAddr())
-    {
-      m_sliceSegmentStartCU[i]=getSlice()->getSliceSegmentCurStartCUAddr();
-    }
-    else
-    {
-      m_sliceSegmentStartCU[i]=pcPic->getCU(getAddr())->m_sliceSegmentStartCU[i];
-    }
-  }
-
-  Int partStartIdx = getSlice()->getSliceSegmentCurStartCUAddr() - pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr) * pcPic->getNumPartInCU();
-
-  Int numElements = min<Int>( partStartIdx, m_uiNumPartition );
-  for ( Int ui = 0; ui < numElements; ui++ )
-  {
-    TComDataCU * pcFrom = pcPic->getCU(getAddr());
-    m_skipFlag[ui]   = pcFrom->getSkipFlag(ui);
+  m_uiNumPartition     = pcPic->getNumPartitionsInCtu();
+
+  memset( m_skipFlag          , false,                      m_uiNumPartition * sizeof( *m_skipFlag ) );
+
 #if H_3D
     m_bDISFlag[ui]   = pcFrom->getDISFlag(ui);
     m_uiDISType[ui]  = pcFrom->getDISType(ui);
 #endif
-    m_pePartSize[ui] = pcFrom->getPartitionSize(ui);
-    m_pePredMode[ui] = pcFrom->getPredictionMode(ui);
-    m_CUTransquantBypass[ui] = pcFrom->getCUTransquantBypass(ui);
-    m_puhDepth[ui] = pcFrom->getDepth(ui);
+
+  memset( m_pePartSize        , NUMBER_OF_PART_SIZES,       m_uiNumPartition * sizeof( *m_pePartSize ) );
+  memset( m_pePredMode        , NUMBER_OF_PREDICTION_MODES, m_uiNumPartition * sizeof( *m_pePredMode ) );
+  memset( m_CUTransquantBypass, false,                      m_uiNumPartition * sizeof( *m_CUTransquantBypass) );
+  memset( m_puhDepth          , 0,                          m_uiNumPartition * sizeof( *m_puhDepth ) );
+  memset( m_puhTrIdx          , 0,                          m_uiNumPartition * sizeof( *m_puhTrIdx ) );
+  memset( m_puhWidth          , maxCUWidth,                 m_uiNumPartition * sizeof( *m_puhWidth ) );
+  memset( m_puhHeight         , maxCUHeight,                m_uiNumPartition * sizeof( *m_puhHeight ) );
+
 #if H_3D_ARP
     m_puhARPW   [ui] = pcFrom->getARPW( ui );
@@ -505,17 +605,22 @@
 #endif
 
-    m_puhWidth  [ui] = pcFrom->getWidth(ui);
-    m_puhHeight [ui] = pcFrom->getHeight(ui);
-    m_puhTrIdx  [ui] = pcFrom->getTransformIdx(ui);
-    m_puhTransformSkip[0][ui] = pcFrom->getTransformSkip(ui,TEXT_LUMA);
-    m_puhTransformSkip[1][ui] = pcFrom->getTransformSkip(ui,TEXT_CHROMA_U);
-    m_puhTransformSkip[2][ui] = pcFrom->getTransformSkip(ui,TEXT_CHROMA_V);
-    m_apiMVPIdx[0][ui] = pcFrom->m_apiMVPIdx[0][ui];;
-    m_apiMVPIdx[1][ui] = pcFrom->m_apiMVPIdx[1][ui];
-    m_apiMVPNum[0][ui] = pcFrom->m_apiMVPNum[0][ui];
-    m_apiMVPNum[1][ui] = pcFrom->m_apiMVPNum[1][ui];
-    m_phQP[ui]=pcFrom->m_phQP[ui];
-    m_pbMergeFlag[ui]=pcFrom->m_pbMergeFlag[ui];
-    m_puhMergeIndex[ui]=pcFrom->m_puhMergeIndex[ui];
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    memset( m_apiMVPIdx[rpl]  , -1,                         m_uiNumPartition * sizeof( *m_apiMVPIdx[rpl] ) );
+    memset( m_apiMVPNum[rpl]  , -1,                         m_uiNumPartition * sizeof( *m_apiMVPNum[rpl] ) );
+  }
+  memset( m_phQP              , getSlice()->getSliceQp(),   m_uiNumPartition * sizeof( *m_phQP ) );
+  memset( m_ChromaQpAdj       , 0,                          m_uiNumPartition * sizeof( *m_ChromaQpAdj ) );
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    memset( m_crossComponentPredictionAlpha[comp] , 0,                     m_uiNumPartition * sizeof( *m_crossComponentPredictionAlpha[comp] ) );
+    memset( m_puhTransformSkip[comp]              , 0,                     m_uiNumPartition * sizeof( *m_puhTransformSkip[comp]) );
+    memset( m_puhCbf[comp]                        , 0,                     m_uiNumPartition * sizeof( *m_puhCbf[comp] ) );
+    memset( m_explicitRdpcmMode[comp]             , NUMBER_OF_RDPCM_MODES, m_uiNumPartition * sizeof( *m_explicitRdpcmMode[comp] ) );
+  }
+  memset( m_pbMergeFlag       , false,                    m_uiNumPartition * sizeof( *m_pbMergeFlag ) );
+  memset( m_puhMergeIndex     , 0,                        m_uiNumPartition * sizeof( *m_puhMergeIndex ) );
+
 #if H_3D_VSP
     m_piVSPFlag[ui] = pcFrom->m_piVSPFlag[ui];
@@ -524,11 +629,4 @@
     m_pbSPIVMPFlag[ui] = pcFrom->m_pbSPIVMPFlag[ui];
 #endif
-    m_puhLumaIntraDir[ui]=pcFrom->m_puhLumaIntraDir[ui];
-    m_puhChromaIntraDir[ui]=pcFrom->m_puhChromaIntraDir[ui];
-    m_puhInterDir[ui]=pcFrom->m_puhInterDir[ui];
-    m_puhCbf[0][ui]=pcFrom->m_puhCbf[0][ui];
-    m_puhCbf[1][ui]=pcFrom->m_puhCbf[1][ui];
-    m_puhCbf[2][ui]=pcFrom->m_puhCbf[2][ui];
-    m_pbIPCMFlag[ui] = pcFrom->m_pbIPCMFlag[ui];
 #if H_3D_DIM_SDC
     m_pbSDCFlag[ui] = pcFrom->m_pbSDCFlag[ui];
@@ -537,33 +635,8 @@
     m_pbDBBPFlag[ui] = pcFrom->m_pbDBBPFlag[ui];
 #endif
-  }
-  
-  Int firstElement = max<Int>( partStartIdx, 0 );
-  numElements = m_uiNumPartition - firstElement;
-  
-  if ( numElements > 0 )
-  {
-    memset( m_skipFlag          + firstElement, false,                    numElements * sizeof( *m_skipFlag ) );
 #if H_3D
     memset( m_bDISFlag          + firstElement, false,                    numElements * sizeof( *m_bDISFlag ) );
     memset( m_uiDISType         + firstElement,     0,                    numElements * sizeof( *m_uiDISType) );
 #endif
-    memset( m_pePartSize        + firstElement, SIZE_NONE,                numElements * sizeof( *m_pePartSize ) );
-    memset( m_pePredMode        + firstElement, MODE_NONE,                numElements * sizeof( *m_pePredMode ) );
-    memset( m_CUTransquantBypass+ firstElement, false,                    numElements * sizeof( *m_CUTransquantBypass) );
-    memset( m_puhDepth          + firstElement, 0,                        numElements * sizeof( *m_puhDepth ) );
-    memset( m_puhTrIdx          + firstElement, 0,                        numElements * sizeof( *m_puhTrIdx ) );
-    memset( m_puhTransformSkip[0] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[0]) );
-    memset( m_puhTransformSkip[1] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[1]) );
-    memset( m_puhTransformSkip[2] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[2]) );
-    memset( m_puhWidth          + firstElement, g_uiMaxCUWidth,           numElements * sizeof( *m_puhWidth ) );
-    memset( m_puhHeight         + firstElement, g_uiMaxCUHeight,          numElements * sizeof( *m_puhHeight ) );
-    memset( m_apiMVPIdx[0]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPIdx[0] ) );
-    memset( m_apiMVPIdx[1]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPIdx[1] ) );
-    memset( m_apiMVPNum[0]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPNum[0] ) );
-    memset( m_apiMVPNum[1]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPNum[1] ) );
-    memset( m_phQP              + firstElement, getSlice()->getSliceQp(), numElements * sizeof( *m_phQP ) );
-    memset( m_pbMergeFlag       + firstElement, false,                    numElements * sizeof( *m_pbMergeFlag ) );
-    memset( m_puhMergeIndex     + firstElement, 0,                        numElements * sizeof( *m_puhMergeIndex ) );
 #if H_3D_VSP
     memset( m_piVSPFlag         + firstElement, 0,                        numElements * sizeof( *m_piVSPFlag ) );
@@ -572,11 +645,10 @@
     memset( m_pbSPIVMPFlag      + firstElement, 0,                        numElements * sizeof( *m_pbSPIVMPFlag ) );
 #endif
-    memset( m_puhLumaIntraDir   + firstElement, DC_IDX,                   numElements * sizeof( *m_puhLumaIntraDir ) );
-    memset( m_puhChromaIntraDir + firstElement, 0,                        numElements * sizeof( *m_puhChromaIntraDir ) );
-    memset( m_puhInterDir       + firstElement, 0,                        numElements * sizeof( *m_puhInterDir ) );
-    memset( m_puhCbf[0]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[0] ) );
-    memset( m_puhCbf[1]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[1] ) );
-    memset( m_puhCbf[2]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[2] ) );
-    memset( m_pbIPCMFlag        + firstElement, false,                    numElements * sizeof( *m_pbIPCMFlag ) );
+
+  for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    memset( m_puhIntraDir[ch] , ((ch==0) ? DC_IDX : 0),   m_uiNumPartition * sizeof( *(m_puhIntraDir[ch]) ) );
+  }
+
 #if H_3D_ARP
     memset( m_puhARPW           + firstElement, 0,                        numElements * sizeof( UChar )         );
@@ -610,101 +682,77 @@
     memset( m_pbDBBPFlag        + firstElement, false,                    numElements * sizeof( *m_pbDBBPFlag ) );
 #endif
-  }
-  
-  UInt uiTmp = g_uiMaxCUWidth*g_uiMaxCUHeight;
-  if ( 0 >= partStartIdx ) 
-  {
-    m_acCUMvField[0].clearMvField();
-    m_acCUMvField[1].clearMvField();
-    memset( m_pcTrCoeffY , 0, sizeof( TCoeff ) * uiTmp );
+
+  memset( m_puhInterDir       , 0,                        m_uiNumPartition * sizeof( *m_puhInterDir ) );
+  memset( m_pbIPCMFlag        , false,                    m_uiNumPartition * sizeof( *m_pbIPCMFlag ) );
+
+  const UInt numCoeffY    = maxCUWidth*maxCUHeight;
+  for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    const UInt componentShift = m_pcPic->getComponentScaleX(ComponentID(comp)) + m_pcPic->getComponentScaleY(ComponentID(comp));
+    memset( m_pcTrCoeff[comp], 0, sizeof(TCoeff)* numCoeffY>>componentShift );
 #if ADAPTIVE_QP_SELECTION
-    memset( m_pcArlCoeffY , 0, sizeof( Int ) * uiTmp );  
-#endif
-    memset( m_pcIPCMSampleY , 0, sizeof( Pel ) * uiTmp );
-    uiTmp  >>= 2;
-    memset( m_pcTrCoeffCb, 0, sizeof( TCoeff ) * uiTmp );
-    memset( m_pcTrCoeffCr, 0, sizeof( TCoeff ) * uiTmp );
-#if ADAPTIVE_QP_SELECTION  
-    memset( m_pcArlCoeffCb, 0, sizeof( Int ) * uiTmp );
-    memset( m_pcArlCoeffCr, 0, sizeof( Int ) * uiTmp );
-#endif
-    memset( m_pcIPCMSampleCb , 0, sizeof( Pel ) * uiTmp );
-    memset( m_pcIPCMSampleCr , 0, sizeof( Pel ) * uiTmp );
-  }
-  else 
-  {
-    TComDataCU * pcFrom = pcPic->getCU(getAddr());
-    m_acCUMvField[0].copyFrom(&pcFrom->m_acCUMvField[0],m_uiNumPartition,0);
-    m_acCUMvField[1].copyFrom(&pcFrom->m_acCUMvField[1],m_uiNumPartition,0);
-    for(Int i=0; i<uiTmp; i++)
-    {
-      m_pcTrCoeffY[i]=pcFrom->m_pcTrCoeffY[i];
-#if ADAPTIVE_QP_SELECTION
-      m_pcArlCoeffY[i]=pcFrom->m_pcArlCoeffY[i];
-#endif
-      m_pcIPCMSampleY[i]=pcFrom->m_pcIPCMSampleY[i];
-    }
-    for(Int i=0; i<(uiTmp>>2); i++)
-    {
-      m_pcTrCoeffCb[i]=pcFrom->m_pcTrCoeffCb[i];
-      m_pcTrCoeffCr[i]=pcFrom->m_pcTrCoeffCr[i];
-#if ADAPTIVE_QP_SELECTION
-      m_pcArlCoeffCb[i]=pcFrom->m_pcArlCoeffCb[i];
-      m_pcArlCoeffCr[i]=pcFrom->m_pcArlCoeffCr[i];
-#endif
-      m_pcIPCMSampleCb[i]=pcFrom->m_pcIPCMSampleCb[i];
-      m_pcIPCMSampleCr[i]=pcFrom->m_pcIPCMSampleCr[i];
-    }
+    memset( m_pcArlCoeff[comp], 0, sizeof(TCoeff)* numCoeffY>>componentShift );
+#endif
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acCUMvField[i].clearMvField();
   }
 
   // Setting neighbor CU
-  m_pcCULeft        = NULL;
-  m_pcCUAbove       = NULL;
-  m_pcCUAboveLeft   = NULL;
-  m_pcCUAboveRight  = NULL;
-
-  m_apcCUColocated[0] = NULL;
-  m_apcCUColocated[1] = NULL;
-
-  UInt uiWidthInCU = pcPic->getFrameWidthInCU();
-  if ( m_uiCUAddr % uiWidthInCU )
-  {
-    m_pcCULeft = pcPic->getCU( m_uiCUAddr - 1 );
-  }
-
-  if ( m_uiCUAddr / uiWidthInCU )
-  {
-    m_pcCUAbove = pcPic->getCU( m_uiCUAddr - uiWidthInCU );
-  }
-
-  if ( m_pcCULeft && m_pcCUAbove )
-  {
-    m_pcCUAboveLeft = pcPic->getCU( m_uiCUAddr - uiWidthInCU - 1 );
-  }
-
-  if ( m_pcCUAbove && ( (m_uiCUAddr%uiWidthInCU) < (uiWidthInCU-1) )  )
-  {
-    m_pcCUAboveRight = pcPic->getCU( m_uiCUAddr - uiWidthInCU + 1 );
-  }
-
-  if ( getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
-  {
-    m_apcCUColocated[0] = getSlice()->getRefPic( REF_PIC_LIST_0, 0)->getCU( m_uiCUAddr );
-  }
-
-  if ( getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
-  {
-    m_apcCUColocated[1] = getSlice()->getRefPic( REF_PIC_LIST_1, 0)->getCU( m_uiCUAddr );
-  }
-}
-
-/** initialize prediction data with enabling sub-LCU-level delta QP
-*\param  uiDepth  depth of the current CU
-*\param  qp     qp for the current CU
-*- set CU width and CU height according to depth
-*- set qp value according to input qp 
-*- set last-coded qp value according to input last-coded qp 
+  m_pCtuLeft        = NULL;
+  m_pCtuAbove       = NULL;
+  m_pCtuAboveLeft   = NULL;
+  m_pCtuAboveRight  = NULL;
+
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = NULL;
+  }
+
+  UInt frameWidthInCtus = pcPic->getFrameWidthInCtus();
+  if ( m_ctuRsAddr % frameWidthInCtus )
+  {
+    m_pCtuLeft = pcPic->getCtu( m_ctuRsAddr - 1 );
+  }
+
+  if ( m_ctuRsAddr / frameWidthInCtus )
+  {
+    m_pCtuAbove = pcPic->getCtu( m_ctuRsAddr - frameWidthInCtus );
+  }
+
+  if ( m_pCtuLeft && m_pCtuAbove )
+  {
+    m_pCtuAboveLeft = pcPic->getCtu( m_ctuRsAddr - frameWidthInCtus - 1 );
+  }
+
+  if ( m_pCtuAbove && ( (m_ctuRsAddr%frameWidthInCtus) < (frameWidthInCtus-1) )  )
+  {
+    m_pCtuAboveRight = pcPic->getCtu( m_ctuRsAddr - frameWidthInCtus + 1 );
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    if ( getSlice()->getNumRefIdx( rpl ) > 0 )
+    {
+      m_apcCUColocated[rpl] = getSlice()->getRefPic( rpl, 0)->getCtu( m_ctuRsAddr );
+    }
+  }
+}
+
+
+/** Initialize prediction data with enabling sub-CTU-level delta QP.
+*   - set CU width and CU height according to depth
+*   - set qp value according to input qp
+*   - set last-coded qp value according to input last-coded qp
+*
+* \param  uiDepth            depth of the current CU
+* \param  qp                 qp for the current CU
+* \param  bTransquantBypass  true for transquant bypass
 */
-Void TComDataCU::initEstData( UInt uiDepth, Int qp, Bool bTransquantBypass )
+Void TComDataCU::initEstData( const UInt uiDepth, const Int qp, const Bool bTransquantBypass )
 {
   m_dTotalCost         = MAX_DOUBLE;
@@ -713,34 +761,38 @@
   m_uiTotalBins        = 0;
 
-  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
-  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  const UChar uhWidth  = getSlice()->getSPS()->getMaxCUWidth()  >> uiDepth;
+  const UChar uhHeight = getSlice()->getSPS()->getMaxCUHeight() >> uiDepth;
 
   for (UInt ui = 0; ui < m_uiNumPartition; ui++)
   {
-    if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU+ui >= getSlice()->getSliceSegmentCurStartCUAddr())
-    {
-      m_apiMVPIdx[0][ui] = -1;
-      m_apiMVPIdx[1][ui] = -1;
-      m_apiMVPNum[0][ui] = -1;
-      m_apiMVPNum[1][ui] = -1;
-      m_puhDepth  [ui] = uiDepth;
-      m_puhWidth  [ui] = uhWidth;
-      m_puhHeight [ui] = uhHeight;
-      m_puhTrIdx  [ui] = 0;
-      m_puhTransformSkip[0][ui] = 0;
-      m_puhTransformSkip[1][ui] = 0;
-      m_puhTransformSkip[2][ui] = 0;
-      m_skipFlag[ui]   = false;
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      m_apiMVPIdx[rpl][ui]  = -1;
+      m_apiMVPNum[rpl][ui]  = -1;
+    }
+    m_puhDepth  [ui]    = uiDepth;
+    m_puhWidth  [ui]    = uhWidth;
+    m_puhHeight [ui]    = uhHeight;
+    m_puhTrIdx  [ui]    = 0;
+    for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+    {
+      m_crossComponentPredictionAlpha[comp][ui] = 0;
+      m_puhTransformSkip             [comp][ui] = 0;
+      m_explicitRdpcmMode            [comp][ui] = NUMBER_OF_RDPCM_MODES;
+    }
+    m_skipFlag[ui]      = false;
 #if H_3D
       m_bDISFlag[ui]   = false;
       m_uiDISType[ui]  = 0;
 #endif
-      m_pePartSize[ui] = SIZE_NONE;
-      m_pePredMode[ui] = MODE_NONE;
-      m_CUTransquantBypass[ui] = bTransquantBypass;
-      m_pbIPCMFlag[ui] = 0;
-      m_phQP[ui] = qp;
-      m_pbMergeFlag[ui] = 0;
-      m_puhMergeIndex[ui] = 0;
+    m_pePartSize[ui]    = NUMBER_OF_PART_SIZES;
+    m_pePredMode[ui]    = NUMBER_OF_PREDICTION_MODES;
+    m_CUTransquantBypass[ui] = bTransquantBypass;
+    m_pbIPCMFlag[ui]    = 0;
+    m_phQP[ui]          = qp;
+    m_ChromaQpAdj[ui]   = 0;
+    m_pbMergeFlag[ui]   = 0;
+    m_puhMergeIndex[ui] = 0;
 #if H_3D_VSP
       m_piVSPFlag[ui] = 0;
@@ -749,10 +801,15 @@
       m_pbSPIVMPFlag[ui] = 0;
 #endif
-      m_puhLumaIntraDir[ui] = DC_IDX;
-      m_puhChromaIntraDir[ui] = 0;
-      m_puhInterDir[ui] = 0;
-      m_puhCbf[0][ui] = 0;
-      m_puhCbf[1][ui] = 0;
-      m_puhCbf[2][ui] = 0;
+
+    for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+    {
+      m_puhIntraDir[ch][ui] = ((ch==0) ? DC_IDX : 0);
+    }
+
+    m_puhInterDir[ui] = 0;
+    for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+    {
+      m_puhCbf[comp][ui] = 0;
+    }
 #if H_3D_ARP
       m_puhARPW[ui] = 0;
@@ -786,28 +843,22 @@
       m_pbDBBPFlag[ui] = false;
 #endif
-    }
-  }
-
-  if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU >= getSlice()->getSliceSegmentCurStartCUAddr())
-  {
-    m_acCUMvField[0].clearMvField();
-    m_acCUMvField[1].clearMvField();
-    UInt uiTmp = uhWidth*uhHeight;
-    
-    memset( m_pcTrCoeffY,    0, uiTmp * sizeof( *m_pcTrCoeffY    ) );
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acCUMvField[i].clearMvField();
+  }
+
+  const UInt numCoeffY = uhWidth*uhHeight;
+
+  for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    const ComponentID component = ComponentID(comp);
+    const UInt numCoeff = numCoeffY >> (getPic()->getComponentScaleX(component) + getPic()->getComponentScaleY(component));
+    memset( m_pcTrCoeff[comp],    0, numCoeff * sizeof( TCoeff ) );
 #if ADAPTIVE_QP_SELECTION
-    memset( m_pcArlCoeffY ,  0, uiTmp * sizeof( *m_pcArlCoeffY   ) );
-#endif
-    memset( m_pcIPCMSampleY, 0, uiTmp * sizeof( *m_pcIPCMSampleY ) );
-
-    uiTmp>>=2;
-    memset( m_pcTrCoeffCb,    0, uiTmp * sizeof( *m_pcTrCoeffCb    ) );
-    memset( m_pcTrCoeffCr,    0, uiTmp * sizeof( *m_pcTrCoeffCr    ) );
-#if ADAPTIVE_QP_SELECTION  
-    memset( m_pcArlCoeffCb,   0, uiTmp * sizeof( *m_pcArlCoeffCb   ) );
-    memset( m_pcArlCoeffCr,   0, uiTmp * sizeof( *m_pcArlCoeffCr   ) );
-#endif
-    memset( m_pcIPCMSampleCb, 0, uiTmp * sizeof( *m_pcIPCMSampleCb ) );
-    memset( m_pcIPCMSampleCr, 0, uiTmp * sizeof( *m_pcIPCMSampleCr ) );
+    memset( m_pcArlCoeff[comp],   0, numCoeff * sizeof( TCoeff ) );
+#endif
+    memset( m_pcIPCMSample[comp], 0, numCoeff * sizeof( Pel) );
   }
 }
@@ -822,10 +873,13 @@
 
   m_pcPic              = pcCU->getPic();
-  m_pcSlice            = m_pcPic->getSlice(m_pcPic->getCurrSliceIdx());
-  m_uiCUAddr           = pcCU->getAddr();
-  m_uiAbsIdxInLCU      = pcCU->getZorderIdxInCU() + uiPartOffset;
-
-  m_uiCUPelX           = pcCU->getCUPelX() + ( g_uiMaxCUWidth>>uiDepth  )*( uiPartUnitIdx &  1 );
-  m_uiCUPelY           = pcCU->getCUPelY() + ( g_uiMaxCUHeight>>uiDepth  )*( uiPartUnitIdx >> 1 );
+  m_pcSlice            = pcCU->getSlice();
+  m_ctuRsAddr          = pcCU->getCtuRsAddr();
+  m_absZIdxInCtu       = pcCU->getZorderIdxInCtu() + uiPartOffset;
+
+  const UChar uhWidth  = getSlice()->getSPS()->getMaxCUWidth()  >> uiDepth;
+  const UChar uhHeight = getSlice()->getSPS()->getMaxCUHeight() >> uiDepth;
+
+  m_uiCUPelX           = pcCU->getCUPelX() + ( uhWidth )*( uiPartUnitIdx &  1 );
+  m_uiCUPelY           = pcCU->getCUPelY() + ( uhHeight)*( uiPartUnitIdx >> 1 );
 
   m_dTotalCost         = MAX_DOUBLE;
@@ -837,8 +891,7 @@
   Int iSizeInUchar = sizeof( UChar  ) * m_uiNumPartition;
   Int iSizeInBool  = sizeof( Bool   ) * m_uiNumPartition;
-
   Int sizeInChar = sizeof( Char  ) * m_uiNumPartition;
+
   memset( m_phQP,              qp,  sizeInChar );
-
   memset( m_pbMergeFlag,        0, iSizeInBool  );
   memset( m_puhMergeIndex,      0, iSizeInUchar );
@@ -849,22 +902,25 @@
   memset( m_pbSPIVMPFlag,       0, sizeof( Bool  ) * m_uiNumPartition );
 #endif
-  memset( m_puhLumaIntraDir,    DC_IDX, iSizeInUchar );
-  memset( m_puhChromaIntraDir,  0, iSizeInUchar );
+
+  for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    memset( m_puhIntraDir[ch],  ((ch==0) ? DC_IDX : 0), iSizeInUchar );
+  }
+
   memset( m_puhInterDir,        0, iSizeInUchar );
   memset( m_puhTrIdx,           0, iSizeInUchar );
-  memset( m_puhTransformSkip[0], 0, iSizeInUchar );
-  memset( m_puhTransformSkip[1], 0, iSizeInUchar );
-  memset( m_puhTransformSkip[2], 0, iSizeInUchar );
-  memset( m_puhCbf[0],          0, iSizeInUchar );
-  memset( m_puhCbf[1],          0, iSizeInUchar );
-  memset( m_puhCbf[2],          0, iSizeInUchar );
-  memset( m_puhDepth,     uiDepth, iSizeInUchar );
+
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    memset( m_crossComponentPredictionAlpha[comp], 0, iSizeInUchar );
+    memset( m_puhTransformSkip[comp],              0, iSizeInUchar );
+    memset( m_puhCbf[comp],                        0, iSizeInUchar );
+    memset( m_explicitRdpcmMode[comp],             NUMBER_OF_RDPCM_MODES, iSizeInUchar );
+  }
 #if H_3D_ARP
   memset( m_puhARPW,            0, iSizeInUchar  );
 #endif
 
-
-  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
-  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  memset( m_puhDepth,     uiDepth, iSizeInUchar );
   memset( m_puhWidth,          uhWidth,  iSizeInUchar );
   memset( m_puhHeight,         uhHeight, iSizeInUchar );
@@ -904,36 +960,20 @@
     m_uiDISType[ui]  = 0;
 #endif
-    m_pePartSize[ui] = SIZE_NONE;
-    m_pePredMode[ui] = MODE_NONE;
+
+    m_pePartSize[ui] = NUMBER_OF_PART_SIZES;
+    m_pePredMode[ui] = NUMBER_OF_PREDICTION_MODES;
     m_CUTransquantBypass[ui] = false;
-    m_apiMVPIdx[0][ui] = -1;
-    m_apiMVPIdx[1][ui] = -1;
-    m_apiMVPNum[0][ui] = -1;
-    m_apiMVPNum[1][ui] = -1;
-    if(m_pcPic->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU+ui<getSlice()->getSliceSegmentCurStartCUAddr())
-    {
-      m_apiMVPIdx[0][ui] = pcCU->m_apiMVPIdx[0][uiPartOffset+ui];
-      m_apiMVPIdx[1][ui] = pcCU->m_apiMVPIdx[1][uiPartOffset+ui];;
-      m_apiMVPNum[0][ui] = pcCU->m_apiMVPNum[0][uiPartOffset+ui];;
-      m_apiMVPNum[1][ui] = pcCU->m_apiMVPNum[1][uiPartOffset+ui];;
-      m_puhDepth  [ui] = pcCU->getDepth(uiPartOffset+ui);
-      m_puhWidth  [ui] = pcCU->getWidth(uiPartOffset+ui);
-      m_puhHeight  [ui] = pcCU->getHeight(uiPartOffset+ui);
-      m_puhTrIdx  [ui] = pcCU->getTransformIdx(uiPartOffset+ui);
-      m_puhTransformSkip[0][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_LUMA);
-      m_puhTransformSkip[1][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_CHROMA_U);
-      m_puhTransformSkip[2][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_CHROMA_V);
-      m_skipFlag[ui]   = pcCU->getSkipFlag(uiPartOffset+ui);
+    m_ChromaQpAdj[ui] = 0;
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      m_apiMVPIdx[rpl][ui] = -1;
+      m_apiMVPNum[rpl][ui] = -1;
+    }
 #if H_3D
       m_bDISFlag[ui]    = pcCU->getDISFlag(uiPartOffset+ui);
       m_uiDISType[ui]   = pcCU->getDISType(uiPartOffset+ui);
 #endif
-      m_pePartSize[ui] = pcCU->getPartitionSize(uiPartOffset+ui);
-      m_pePredMode[ui] = pcCU->getPredictionMode(uiPartOffset+ui);
-      m_CUTransquantBypass[ui] = pcCU->getCUTransquantBypass(uiPartOffset+ui);
-      m_pbIPCMFlag[ui]=pcCU->m_pbIPCMFlag[uiPartOffset+ui];
-      m_phQP[ui] = pcCU->m_phQP[uiPartOffset+ui];
-      m_pbMergeFlag[ui]=pcCU->m_pbMergeFlag[uiPartOffset+ui];
-      m_puhMergeIndex[ui]=pcCU->m_puhMergeIndex[uiPartOffset+ui];
 #if H_3D_VSP
       m_piVSPFlag[ui]=pcCU->m_piVSPFlag[uiPartOffset+ui];
@@ -943,11 +983,4 @@
       m_pbSPIVMPFlag[ui]=pcCU->m_pbSPIVMPFlag[uiPartOffset+ui];
 #endif
-      m_puhLumaIntraDir[ui]=pcCU->m_puhLumaIntraDir[uiPartOffset+ui];
-      m_puhChromaIntraDir[ui]=pcCU->m_puhChromaIntraDir[uiPartOffset+ui];
-      m_puhInterDir[ui]=pcCU->m_puhInterDir[uiPartOffset+ui];
-      m_puhCbf[0][ui]=pcCU->m_puhCbf[0][uiPartOffset+ui];
-      m_puhCbf[1][ui]=pcCU->m_puhCbf[1][uiPartOffset+ui];
-      m_puhCbf[2][ui]=pcCU->m_puhCbf[2][uiPartOffset+ui];
-
 #if H_3D_ARP
       m_puhARPW           [ui] = pcCU->getARPW( uiPartOffset+ui );
@@ -977,77 +1010,40 @@
       m_pbDBBPFlag[ui]=pcCU->m_pbDBBPFlag[uiPartOffset+ui];
 #endif
-    }
-  }
-  UInt uiTmp = uhWidth*uhHeight;
-  memset( m_pcTrCoeffY , 0, sizeof(TCoeff)*uiTmp );
-#if ADAPTIVE_QP_SELECTION  
-  memset( m_pcArlCoeffY , 0, sizeof(Int)*uiTmp );
-#endif
-  memset( m_pcIPCMSampleY , 0, sizeof( Pel ) * uiTmp );
-  uiTmp >>= 2;
-  memset( m_pcTrCoeffCb, 0, sizeof(TCoeff)*uiTmp );
-  memset( m_pcTrCoeffCr, 0, sizeof(TCoeff)*uiTmp );
+  }
+
+  const UInt numCoeffY    = uhWidth*uhHeight;
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    const UInt componentShift = m_pcPic->getComponentScaleX(ComponentID(ch)) + m_pcPic->getComponentScaleY(ComponentID(ch));
+    memset( m_pcTrCoeff[ch],  0, sizeof(TCoeff)*(numCoeffY>>componentShift) );
 #if ADAPTIVE_QP_SELECTION
-  memset( m_pcArlCoeffCb, 0, sizeof(Int)*uiTmp );
-  memset( m_pcArlCoeffCr, 0, sizeof(Int)*uiTmp );
-#endif
-  memset( m_pcIPCMSampleCb , 0, sizeof( Pel ) * uiTmp );
-  memset( m_pcIPCMSampleCr , 0, sizeof( Pel ) * uiTmp );
-  m_acCUMvField[0].clearMvField();
-  m_acCUMvField[1].clearMvField();
-
-  if(m_pcPic->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU<getSlice()->getSliceSegmentCurStartCUAddr())
-  {
-    // Part of this CU contains data from an older slice. Now copy in that data.
-    UInt uiMaxCuWidth=pcCU->getSlice()->getSPS()->getMaxCUWidth();
-    UInt uiMaxCuHeight=pcCU->getSlice()->getSPS()->getMaxCUHeight();
-    TComDataCU * bigCU = getPic()->getCU(getAddr());
-    Int minui = uiPartOffset;
-    minui = -minui;
-    pcCU->m_acCUMvField[0].copyTo(&m_acCUMvField[0],minui,uiPartOffset,m_uiNumPartition);
-    pcCU->m_acCUMvField[1].copyTo(&m_acCUMvField[1],minui,uiPartOffset,m_uiNumPartition);
-    UInt uiCoffOffset = uiMaxCuWidth*uiMaxCuHeight*m_uiAbsIdxInLCU/pcCU->getPic()->getNumPartInCU();
-    uiTmp = uhWidth*uhHeight;
-    for(Int i=0; i<uiTmp; i++)
-    {
-      m_pcTrCoeffY[i]=bigCU->m_pcTrCoeffY[uiCoffOffset+i];
-#if ADAPTIVE_QP_SELECTION
-      m_pcArlCoeffY[i]=bigCU->m_pcArlCoeffY[uiCoffOffset+i];
-#endif
-      m_pcIPCMSampleY[i]=bigCU->m_pcIPCMSampleY[uiCoffOffset+i];
-    }
-    uiTmp>>=2;
-    uiCoffOffset>>=2;
-    for(Int i=0; i<uiTmp; i++)
-    {
-      m_pcTrCoeffCr[i]=bigCU->m_pcTrCoeffCr[uiCoffOffset+i];
-      m_pcTrCoeffCb[i]=bigCU->m_pcTrCoeffCb[uiCoffOffset+i];
-#if ADAPTIVE_QP_SELECTION
-      m_pcArlCoeffCr[i]=bigCU->m_pcArlCoeffCr[uiCoffOffset+i];
-      m_pcArlCoeffCb[i]=bigCU->m_pcArlCoeffCb[uiCoffOffset+i];
-#endif
-      m_pcIPCMSampleCb[i]=bigCU->m_pcIPCMSampleCb[uiCoffOffset+i];
-      m_pcIPCMSampleCr[i]=bigCU->m_pcIPCMSampleCr[uiCoffOffset+i];
-    }
-  }
-
-  m_pcCULeft        = pcCU->getCULeft();
-  m_pcCUAbove       = pcCU->getCUAbove();
-  m_pcCUAboveLeft   = pcCU->getCUAboveLeft();
-  m_pcCUAboveRight  = pcCU->getCUAboveRight();
-
-  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
-  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
-  memcpy(m_sliceStartCU,pcCU->m_sliceStartCU+uiPartOffset,sizeof(UInt)*m_uiNumPartition);
-  memcpy(m_sliceSegmentStartCU,pcCU->m_sliceSegmentStartCU+uiPartOffset,sizeof(UInt)*m_uiNumPartition);
+    memset( m_pcArlCoeff[ch], 0, sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#endif
+    memset( m_pcIPCMSample[ch], 0, sizeof(Pel)* (numCoeffY>>componentShift) );
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acCUMvField[i].clearMvField();
+  }
+
+  m_pCtuLeft        = pcCU->getCtuLeft();
+  m_pCtuAbove       = pcCU->getCtuAbove();
+  m_pCtuAboveLeft   = pcCU->getCtuAboveLeft();
+  m_pCtuAboveRight  = pcCU->getCtuAboveRight();
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i] = pcCU->getCUColocated(RefPicList(i));
+  }
 }
 
 Void TComDataCU::setOutsideCUPart( UInt uiAbsPartIdx, UInt uiDepth )
 {
-  UInt uiNumPartition = m_uiNumPartition >> (uiDepth << 1);
-  UInt uiSizeInUchar = sizeof( UChar  ) * uiNumPartition;
-
-  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
-  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  const UInt     uiNumPartition = m_uiNumPartition >> (uiDepth << 1);
+  const UInt     uiSizeInUchar  = sizeof( UChar  ) * uiNumPartition;
+  const TComSPS &sps            = *(getSlice()->getSPS());
+  const UChar    uhWidth        = sps.getMaxCUWidth()  >> uiDepth;
+  const UChar    uhHeight       = sps.getMaxCUHeight() >> uiDepth;
   memset( m_puhDepth    + uiAbsPartIdx,     uiDepth,  uiSizeInUchar );
   memset( m_puhWidth    + uiAbsPartIdx,     uhWidth,  uiSizeInUchar );
@@ -1059,16 +1055,16 @@
 // --------------------------------------------------------------------------------------------------------------------
 
-Void TComDataCU::copySubCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+Void TComDataCU::copySubCU( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
   UInt uiPart = uiAbsPartIdx;
-  
+
   m_pcPic              = pcCU->getPic();
   m_pcSlice            = pcCU->getSlice();
-  m_uiCUAddr           = pcCU->getAddr();
-  m_uiAbsIdxInLCU      = uiAbsPartIdx;
-  
+  m_ctuRsAddr          = pcCU->getCtuRsAddr();
+  m_absZIdxInCtu       = uiAbsPartIdx;
+
   m_uiCUPelX           = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
   m_uiCUPelY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  
+
   m_skipFlag=pcCU->getSkipFlag()          + uiPart;
 #if H_3D
@@ -1076,12 +1072,14 @@
   m_uiDISType    = pcCU->getDISType()     + uiPart;
 #endif
+
   m_phQP=pcCU->getQP()                    + uiPart;
+  m_ChromaQpAdj = pcCU->getChromaQpAdj()  + uiPart;
   m_pePartSize = pcCU->getPartitionSize() + uiPart;
   m_pePredMode=pcCU->getPredictionMode()  + uiPart;
   m_CUTransquantBypass  = pcCU->getCUTransquantBypass()+uiPart;
-  
 #if H_3D_NBDV
   m_pDvInfo             = pcCU->getDvInfo()           + uiPart;
 #endif
+
   m_pbMergeFlag         = pcCU->getMergeFlag()        + uiPart;
   m_puhMergeIndex       = pcCU->getMergeIndex()       + uiPart;
@@ -1098,15 +1096,20 @@
   m_pbICFlag            = pcCU->getICFlag()           + uiPart;
 #endif
-  m_puhLumaIntraDir     = pcCU->getLumaIntraDir()     + uiPart;
-  m_puhChromaIntraDir   = pcCU->getChromaIntraDir()   + uiPart;
+
+  for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_puhIntraDir[ch]   = pcCU->getIntraDir(ChannelType(ch)) + uiPart;
+  }
+
   m_puhInterDir         = pcCU->getInterDir()         + uiPart;
   m_puhTrIdx            = pcCU->getTransformIdx()     + uiPart;
-  m_puhTransformSkip[0] = pcCU->getTransformSkip(TEXT_LUMA)     + uiPart;
-  m_puhTransformSkip[1] = pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPart;
-  m_puhTransformSkip[2] = pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPart;
-
-  m_puhCbf[0]= pcCU->getCbf(TEXT_LUMA)            + uiPart;
-  m_puhCbf[1]= pcCU->getCbf(TEXT_CHROMA_U)        + uiPart;
-  m_puhCbf[2]= pcCU->getCbf(TEXT_CHROMA_V)        + uiPart;
+
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    m_crossComponentPredictionAlpha[comp] = pcCU->getCrossComponentPredictionAlpha(ComponentID(comp)) + uiPart;
+    m_puhTransformSkip[comp]              = pcCU->getTransformSkip(ComponentID(comp))                 + uiPart;
+    m_puhCbf[comp]                        = pcCU->getCbf(ComponentID(comp))                           + uiPart;
+    m_explicitRdpcmMode[comp]             = pcCU->getExplicitRdpcmMode(ComponentID(comp))             + uiPart;
+  }
 #if H_3D_DIM
   for( Int i = 0; i < DIM_NUM_TYPE; i++ )
@@ -1130,49 +1133,48 @@
   m_pbDBBPFlag              = pcCU->getDBBPFlag()         + uiPart;
 #endif
+
   m_puhDepth=pcCU->getDepth()                     + uiPart;
   m_puhWidth=pcCU->getWidth()                     + uiPart;
   m_puhHeight=pcCU->getHeight()                   + uiPart;
-  
-  m_apiMVPIdx[0]=pcCU->getMVPIdx(REF_PIC_LIST_0)  + uiPart;
-  m_apiMVPIdx[1]=pcCU->getMVPIdx(REF_PIC_LIST_1)  + uiPart;
-  m_apiMVPNum[0]=pcCU->getMVPNum(REF_PIC_LIST_0)  + uiPart;
-  m_apiMVPNum[1]=pcCU->getMVPNum(REF_PIC_LIST_1)  + uiPart;
-  
+
   m_pbIPCMFlag         = pcCU->getIPCMFlag()        + uiPart;
 
-  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
-  m_pcCUAboveRight     = pcCU->getCUAboveRight();
-  m_pcCUAbove          = pcCU->getCUAbove();
-  m_pcCULeft           = pcCU->getCULeft();
-  
-  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
-  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
-  
+  m_pCtuAboveLeft      = pcCU->getCtuAboveLeft();
+  m_pCtuAboveRight     = pcCU->getCtuAboveRight();
+  m_pCtuAbove          = pcCU->getCtuAbove();
+  m_pCtuLeft           = pcCU->getCtuLeft();
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_apcCUColocated[rpl] = pcCU->getCUColocated(rpl);
+    m_apiMVPIdx[rpl]=pcCU->getMVPIdx(rpl)  + uiPart;
+    m_apiMVPNum[rpl]=pcCU->getMVPNum(rpl)  + uiPart;
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_acCUMvField[rpl].linkToWithOffset( pcCU->getCUMvField(rpl), uiPart );
+  }
+
   UInt uiMaxCuWidth=pcCU->getSlice()->getSPS()->getMaxCUWidth();
   UInt uiMaxCuHeight=pcCU->getSlice()->getSPS()->getMaxCUHeight();
-  
-  UInt uiCoffOffset = uiMaxCuWidth*uiMaxCuHeight*uiAbsPartIdx/pcCU->getPic()->getNumPartInCU();
-  
-  m_pcTrCoeffY = pcCU->getCoeffY() + uiCoffOffset;
+
+  UInt uiCoffOffset = uiMaxCuWidth*uiMaxCuHeight*uiAbsPartIdx/pcCU->getPic()->getNumPartitionsInCtu();
+
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    const ComponentID component = ComponentID(ch);
+    const UInt componentShift   = m_pcPic->getComponentScaleX(component) + m_pcPic->getComponentScaleY(component);
+    const UInt offset           = uiCoffOffset >> componentShift;
+    m_pcTrCoeff[ch] = pcCU->getCoeff(component) + offset;
 #if ADAPTIVE_QP_SELECTION
-  m_pcArlCoeffY= pcCU->getArlCoeffY() + uiCoffOffset;  
-#endif
-  m_pcIPCMSampleY = pcCU->getPCMSampleY() + uiCoffOffset;
-
-  uiCoffOffset >>=2;
-  m_pcTrCoeffCb=pcCU->getCoeffCb() + uiCoffOffset;
-  m_pcTrCoeffCr=pcCU->getCoeffCr() + uiCoffOffset;
-#if ADAPTIVE_QP_SELECTION  
-  m_pcArlCoeffCb=pcCU->getArlCoeffCb() + uiCoffOffset;
-  m_pcArlCoeffCr=pcCU->getArlCoeffCr() + uiCoffOffset;
-#endif
-  m_pcIPCMSampleCb = pcCU->getPCMSampleCb() + uiCoffOffset;
-  m_pcIPCMSampleCr = pcCU->getPCMSampleCr() + uiCoffOffset;
-
-  m_acCUMvField[0].linkToWithOffset( pcCU->getCUMvField(REF_PIC_LIST_0), uiPart );
-  m_acCUMvField[1].linkToWithOffset( pcCU->getCUMvField(REF_PIC_LIST_1), uiPart );
-  memcpy(m_sliceStartCU,pcCU->m_sliceStartCU+uiPart,sizeof(UInt)*m_uiNumPartition);
-  memcpy(m_sliceSegmentStartCU,pcCU->m_sliceSegmentStartCU+uiPart,sizeof(UInt)*m_uiNumPartition);
-}
+    m_pcArlCoeff[ch] = pcCU->getArlCoeff(component) + offset;
+#endif
+    m_pcIPCMSample[ch] = pcCU->getPCMSample(component) + offset;
+  }
+}
+
 #if H_3D_NBDV
 Void TComDataCU::copyDVInfoFrom (TComDataCU* pcCU, UInt uiAbsPartIdx)
@@ -1181,4 +1183,5 @@
 }
 #endif
+
 // Copy inter prediction info from the biggest CU
 Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList 
@@ -1186,23 +1189,25 @@
   , Bool bNBDV
 #endif
-  )
+)
 {
   m_pcPic              = pcCU->getPic();
   m_pcSlice            = pcCU->getSlice();
-  m_uiCUAddr           = pcCU->getAddr();
-  m_uiAbsIdxInLCU      = uiAbsPartIdx;
-  
+  m_ctuRsAddr          = pcCU->getCtuRsAddr();
+  m_absZIdxInCtu       = uiAbsPartIdx;
+
   Int iRastPartIdx     = g_auiZscanToRaster[uiAbsPartIdx];
-  m_uiCUPelX           = pcCU->getCUPelX() + m_pcPic->getMinCUWidth ()*( iRastPartIdx % m_pcPic->getNumPartInWidth() );
-  m_uiCUPelY           = pcCU->getCUPelY() + m_pcPic->getMinCUHeight()*( iRastPartIdx / m_pcPic->getNumPartInWidth() );
-  
-  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
-  m_pcCUAboveRight     = pcCU->getCUAboveRight();
-  m_pcCUAbove          = pcCU->getCUAbove();
-  m_pcCULeft           = pcCU->getCULeft();
-  
-  m_apcCUColocated[0]  = pcCU->getCUColocated(REF_PIC_LIST_0);
-  m_apcCUColocated[1]  = pcCU->getCUColocated(REF_PIC_LIST_1);
-  
+  m_uiCUPelX           = pcCU->getCUPelX() + m_pcPic->getMinCUWidth ()*( iRastPartIdx % m_pcPic->getNumPartInCtuWidth() );
+  m_uiCUPelY           = pcCU->getCUPelY() + m_pcPic->getMinCUHeight()*( iRastPartIdx / m_pcPic->getNumPartInCtuWidth() );
+
+  m_pCtuAboveLeft      = pcCU->getCtuAboveLeft();
+  m_pCtuAboveRight     = pcCU->getCtuAboveRight();
+  m_pCtuAbove          = pcCU->getCtuAbove();
+  m_pCtuLeft           = pcCU->getCtuLeft();
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = pcCU->getCUColocated(RefPicList(i));
+  }
+
   m_skipFlag           = pcCU->getSkipFlag ()             + uiAbsPartIdx;
 #if H_3D
@@ -1210,4 +1215,5 @@
   m_uiDISType          = pcCU->getDISType()               + uiAbsPartIdx;
 #endif
+
   m_pePartSize         = pcCU->getPartitionSize ()        + uiAbsPartIdx;
 #if H_3D_NBDV
@@ -1222,11 +1228,12 @@
 #endif
   m_pePredMode         = pcCU->getPredictionMode()        + uiAbsPartIdx;
+  m_ChromaQpAdj        = pcCU->getChromaQpAdj()           + uiAbsPartIdx;
   m_CUTransquantBypass = pcCU->getCUTransquantBypass()    + uiAbsPartIdx;
   m_puhInterDir        = pcCU->getInterDir      ()        + uiAbsPartIdx;
-  
+
   m_puhDepth           = pcCU->getDepth ()                + uiAbsPartIdx;
   m_puhWidth           = pcCU->getWidth ()                + uiAbsPartIdx;
   m_puhHeight          = pcCU->getHeight()                + uiAbsPartIdx;
-  
+
   m_pbMergeFlag        = pcCU->getMergeFlag()             + uiAbsPartIdx;
   m_puhMergeIndex      = pcCU->getMergeIndex()            + uiAbsPartIdx;
@@ -1238,6 +1245,7 @@
   m_pbSPIVMPFlag       = pcCU->getSPIVMPFlag()            + uiAbsPartIdx;
 #endif
+
   m_apiMVPIdx[eRefPicList] = pcCU->getMVPIdx(eRefPicList) + uiAbsPartIdx;
-  m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;  
+  m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;
 #if H_3D_ARP
   m_puhARPW            = pcCU->getARPW()                  + uiAbsPartIdx;
@@ -1248,7 +1256,4 @@
 
   m_acCUMvField[ eRefPicList ].linkToWithOffset( pcCU->getCUMvField(eRefPicList), uiAbsPartIdx );
-
-  memcpy(m_sliceStartCU,pcCU->m_sliceStartCU+uiAbsPartIdx,sizeof(UInt)*m_uiNumPartition);
-  memcpy(m_sliceSegmentStartCU,pcCU->m_sliceSegmentStartCU+uiAbsPartIdx,sizeof(UInt)*m_uiNumPartition);
 #if H_3D_NBDV
   }
@@ -1257,4 +1262,5 @@
   m_pbICFlag           = pcCU->getICFlag()                + uiAbsPartIdx;
 #endif
+
 }
 
@@ -1264,15 +1270,17 @@
 {
   assert( uiPartUnitIdx<4 );
-  
+
   m_dTotalCost         += pcCU->getTotalCost();
   m_uiTotalDistortion  += pcCU->getTotalDistortion();
   m_uiTotalBits        += pcCU->getTotalBits();
-  
+
   UInt uiOffset         = pcCU->getTotalNumPart()*uiPartUnitIdx;
-  
+  const UInt numValidComp=pcCU->getPic()->getNumberValidComponents();
+  const UInt numValidChan=pcCU->getPic()->getChromaFormat()==CHROMA_400 ? 1:2;
+
   UInt uiNumPartition = pcCU->getTotalNumPart();
   Int iSizeInUchar  = sizeof( UChar ) * uiNumPartition;
   Int iSizeInBool   = sizeof( Bool  ) * uiNumPartition;
-  
+
   Int sizeInChar  = sizeof( Char ) * uiNumPartition;
   memcpy( m_skipFlag   + uiOffset, pcCU->getSkipFlag(),       sizeof( *m_skipFlag )   * uiNumPartition );
@@ -1284,4 +1292,5 @@
   memcpy( m_pePartSize + uiOffset, pcCU->getPartitionSize(),  sizeof( *m_pePartSize ) * uiNumPartition );
   memcpy( m_pePredMode + uiOffset, pcCU->getPredictionMode(), sizeof( *m_pePredMode ) * uiNumPartition );
+  memcpy( m_ChromaQpAdj + uiOffset, pcCU->getChromaQpAdj(),   sizeof( *m_ChromaQpAdj ) * uiNumPartition );
   memcpy( m_CUTransquantBypass + uiOffset, pcCU->getCUTransquantBypass(), sizeof( *m_CUTransquantBypass ) * uiNumPartition );
   memcpy( m_pbMergeFlag         + uiOffset, pcCU->getMergeFlag(),         iSizeInBool  );
@@ -1294,15 +1303,20 @@
   memcpy( m_pbSPIVMPFlag        + uiOffset, pcCU->getSPIVMPFlag(),        sizeof( Bool ) * uiNumPartition );
 #endif
-  memcpy( m_puhLumaIntraDir     + uiOffset, pcCU->getLumaIntraDir(),      iSizeInUchar );
-  memcpy( m_puhChromaIntraDir   + uiOffset, pcCU->getChromaIntraDir(),    iSizeInUchar );
+
+  for (UInt ch=0; ch<numValidChan; ch++)
+  {
+    memcpy( m_puhIntraDir[ch]   + uiOffset, pcCU->getIntraDir(ChannelType(ch)), iSizeInUchar );
+  }
+
   memcpy( m_puhInterDir         + uiOffset, pcCU->getInterDir(),          iSizeInUchar );
   memcpy( m_puhTrIdx            + uiOffset, pcCU->getTransformIdx(),      iSizeInUchar );
-  memcpy( m_puhTransformSkip[0] + uiOffset, pcCU->getTransformSkip(TEXT_LUMA),     iSizeInUchar );
-  memcpy( m_puhTransformSkip[1] + uiOffset, pcCU->getTransformSkip(TEXT_CHROMA_U), iSizeInUchar );
-  memcpy( m_puhTransformSkip[2] + uiOffset, pcCU->getTransformSkip(TEXT_CHROMA_V), iSizeInUchar );
-
-  memcpy( m_puhCbf[0] + uiOffset, pcCU->getCbf(TEXT_LUMA)    , iSizeInUchar );
-  memcpy( m_puhCbf[1] + uiOffset, pcCU->getCbf(TEXT_CHROMA_U), iSizeInUchar );
-  memcpy( m_puhCbf[2] + uiOffset, pcCU->getCbf(TEXT_CHROMA_V), iSizeInUchar );
+
+  for(UInt comp=0; comp<numValidComp; comp++)
+  {
+    memcpy( m_crossComponentPredictionAlpha[comp] + uiOffset, pcCU->getCrossComponentPredictionAlpha(ComponentID(comp)), iSizeInUchar );
+    memcpy( m_puhTransformSkip[comp]              + uiOffset, pcCU->getTransformSkip(ComponentID(comp))                , iSizeInUchar );
+    memcpy( m_puhCbf[comp]                        + uiOffset, pcCU->getCbf(ComponentID(comp))                          , iSizeInUchar );
+    memcpy( m_explicitRdpcmMode[comp]             + uiOffset, pcCU->getExplicitRdpcmMode(ComponentID(comp))            , iSizeInUchar );
+  }
 #if H_3D_DIM
   for( Int i = 0; i < DIM_NUM_TYPE; i++ )
@@ -1330,43 +1344,40 @@
   memcpy( m_puhWidth  + uiOffset, pcCU->getWidth(),  iSizeInUchar );
   memcpy( m_puhHeight + uiOffset, pcCU->getHeight(), iSizeInUchar );
-  
-  memcpy( m_apiMVPIdx[0] + uiOffset, pcCU->getMVPIdx(REF_PIC_LIST_0), iSizeInUchar );
-  memcpy( m_apiMVPIdx[1] + uiOffset, pcCU->getMVPIdx(REF_PIC_LIST_1), iSizeInUchar );
-  memcpy( m_apiMVPNum[0] + uiOffset, pcCU->getMVPNum(REF_PIC_LIST_0), iSizeInUchar );
-  memcpy( m_apiMVPNum[1] + uiOffset, pcCU->getMVPNum(REF_PIC_LIST_1), iSizeInUchar );
-  
+
   memcpy( m_pbIPCMFlag + uiOffset, pcCU->getIPCMFlag(), iSizeInBool );
 
-  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
-  m_pcCUAboveRight     = pcCU->getCUAboveRight();
-  m_pcCUAbove          = pcCU->getCUAbove();
-  m_pcCULeft           = pcCU->getCULeft();
-  
-  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
-  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
-  
-  m_acCUMvField[0].copyFrom( pcCU->getCUMvField( REF_PIC_LIST_0 ), pcCU->getTotalNumPart(), uiOffset );
-  m_acCUMvField[1].copyFrom( pcCU->getCUMvField( REF_PIC_LIST_1 ), pcCU->getTotalNumPart(), uiOffset );
-  
-  UInt uiTmp  = g_uiMaxCUWidth*g_uiMaxCUHeight >> (uiDepth<<1);
-  UInt uiTmp2 = uiPartUnitIdx*uiTmp;
-  memcpy( m_pcTrCoeffY  + uiTmp2, pcCU->getCoeffY(),  sizeof(TCoeff)*uiTmp );
+  m_pCtuAboveLeft      = pcCU->getCtuAboveLeft();
+  m_pCtuAboveRight     = pcCU->getCtuAboveRight();
+  m_pCtuAbove          = pcCU->getCtuAbove();
+  m_pCtuLeft           = pcCU->getCtuLeft();
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    memcpy( m_apiMVPIdx[rpl] + uiOffset, pcCU->getMVPIdx(rpl), iSizeInUchar );
+    memcpy( m_apiMVPNum[rpl] + uiOffset, pcCU->getMVPNum(rpl), iSizeInUchar );
+    m_apcCUColocated[rpl] = pcCU->getCUColocated(rpl);
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_acCUMvField[rpl].copyFrom( pcCU->getCUMvField( rpl ), pcCU->getTotalNumPart(), uiOffset );
+  }
+
+  const UInt numCoeffY = (pcCU->getSlice()->getSPS()->getMaxCUWidth()*pcCU->getSlice()->getSPS()->getMaxCUHeight()) >> (uiDepth<<1);
+  const UInt offsetY   = uiPartUnitIdx*numCoeffY;
+  for (UInt ch=0; ch<numValidComp; ch++)
+  {
+    const ComponentID component = ComponentID(ch);
+    const UInt componentShift   = m_pcPic->getComponentScaleX(component) + m_pcPic->getComponentScaleY(component);
+    const UInt offset           = offsetY>>componentShift;
+    memcpy( m_pcTrCoeff [ch] + offset, pcCU->getCoeff(component),    sizeof(TCoeff)*(numCoeffY>>componentShift) );
 #if ADAPTIVE_QP_SELECTION
-  memcpy( m_pcArlCoeffY  + uiTmp2, pcCU->getArlCoeffY(),  sizeof(Int)*uiTmp );
-#endif
-  memcpy( m_pcIPCMSampleY + uiTmp2 , pcCU->getPCMSampleY(), sizeof(Pel) * uiTmp );
-
-  uiTmp >>= 2; uiTmp2>>= 2;
-  memcpy( m_pcTrCoeffCb + uiTmp2, pcCU->getCoeffCb(), sizeof(TCoeff)*uiTmp );
-  memcpy( m_pcTrCoeffCr + uiTmp2, pcCU->getCoeffCr(), sizeof(TCoeff)*uiTmp );
-#if ADAPTIVE_QP_SELECTION
-  memcpy( m_pcArlCoeffCb + uiTmp2, pcCU->getArlCoeffCb(), sizeof(Int)*uiTmp );
-  memcpy( m_pcArlCoeffCr + uiTmp2, pcCU->getArlCoeffCr(), sizeof(Int)*uiTmp );
-#endif
-  memcpy( m_pcIPCMSampleCb + uiTmp2 , pcCU->getPCMSampleCb(), sizeof(Pel) * uiTmp );
-  memcpy( m_pcIPCMSampleCr + uiTmp2 , pcCU->getPCMSampleCr(), sizeof(Pel) * uiTmp );
-  m_uiTotalBins += pcCU->getTotalBins();
-  memcpy( m_sliceStartCU        + uiOffset, pcCU->m_sliceStartCU,        sizeof( UInt ) * uiNumPartition  );
-  memcpy( m_sliceSegmentStartCU + uiOffset, pcCU->m_sliceSegmentStartCU, sizeof( UInt ) * uiNumPartition  );
+    memcpy( m_pcArlCoeff[ch] + offset, pcCU->getArlCoeff(component), sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#endif
+    memcpy( m_pcIPCMSample[ch] + offset, pcCU->getPCMSample(component), sizeof(Pel)*(numCoeffY>>componentShift) );
+  }
+
 #if H_3D_ARP
   memcpy( m_puhARPW             + uiOffset, pcCU->getARPW(),              iSizeInUchar );
@@ -1375,4 +1386,6 @@
   memcpy( m_pbICFlag            + uiOffset, pcCU->getICFlag(),            iSizeInBool );
 #endif
+
+  m_uiTotalBins += pcCU->getTotalBins();
 }
 
@@ -1381,30 +1394,34 @@
 Void TComDataCU::copyToPic( UChar uhDepth )
 {
-  TComDataCU*& rpcCU = m_pcPic->getCU( m_uiCUAddr );
-  
-  rpcCU->getTotalCost()       = m_dTotalCost;
-  rpcCU->getTotalDistortion() = m_uiTotalDistortion;
-  rpcCU->getTotalBits()       = m_uiTotalBits;
-  
+  TComDataCU* pCtu = m_pcPic->getCtu( m_ctuRsAddr );
+  const UInt numValidComp=pCtu->getPic()->getNumberValidComponents();
+  const UInt numValidChan=pCtu->getPic()->getChromaFormat()==CHROMA_400 ? 1:2;
+
+  pCtu->getTotalCost()       = m_dTotalCost;
+  pCtu->getTotalDistortion() = m_uiTotalDistortion;
+  pCtu->getTotalBits()       = m_uiTotalBits;
+
   Int iSizeInUchar  = sizeof( UChar ) * m_uiNumPartition;
   Int iSizeInBool   = sizeof( Bool  ) * m_uiNumPartition;
-  
   Int sizeInChar  = sizeof( Char ) * m_uiNumPartition;
 
-  memcpy( rpcCU->getSkipFlag() + m_uiAbsIdxInLCU, m_skipFlag, sizeof( *m_skipFlag ) * m_uiNumPartition );
+  memcpy( pCtu->getSkipFlag() + m_absZIdxInCtu, m_skipFlag, sizeof( *m_skipFlag ) * m_uiNumPartition );
 #if H_3D
   memcpy( rpcCU->getDISFlag()  + m_uiAbsIdxInLCU, m_bDISFlag,    sizeof( *m_bDISFlag )  * m_uiNumPartition );
   memcpy( rpcCU->getDISType()  + m_uiAbsIdxInLCU, m_uiDISType,   sizeof( *m_uiDISType ) * m_uiNumPartition );
 #endif
-  memcpy( rpcCU->getQP() + m_uiAbsIdxInLCU, m_phQP, sizeInChar  );
+
+  memcpy( pCtu->getQP() + m_absZIdxInCtu, m_phQP, sizeInChar  );
 #if H_3D_NBDV
   memcpy( rpcCU->getDvInfo()         + m_uiAbsIdxInLCU, m_pDvInfo,    sizeof(* m_pDvInfo)     * m_uiNumPartition );
 #endif
-  memcpy( rpcCU->getPartitionSize()  + m_uiAbsIdxInLCU, m_pePartSize, sizeof( *m_pePartSize ) * m_uiNumPartition );
-  memcpy( rpcCU->getPredictionMode() + m_uiAbsIdxInLCU, m_pePredMode, sizeof( *m_pePredMode ) * m_uiNumPartition );
-  memcpy( rpcCU->getCUTransquantBypass()+ m_uiAbsIdxInLCU, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * m_uiNumPartition );
-  memcpy( rpcCU->getMergeFlag()         + m_uiAbsIdxInLCU, m_pbMergeFlag,         iSizeInBool  );
-  memcpy( rpcCU->getMergeIndex()        + m_uiAbsIdxInLCU, m_puhMergeIndex,       iSizeInUchar );
-#if H_3D_VSP
+
+  memcpy( pCtu->getPartitionSize()  + m_absZIdxInCtu, m_pePartSize, sizeof( *m_pePartSize ) * m_uiNumPartition );
+  memcpy( pCtu->getPredictionMode() + m_absZIdxInCtu, m_pePredMode, sizeof( *m_pePredMode ) * m_uiNumPartition );
+  memcpy( pCtu->getChromaQpAdj() + m_absZIdxInCtu, m_ChromaQpAdj, sizeof( *m_ChromaQpAdj ) * m_uiNumPartition );
+  memcpy( pCtu->getCUTransquantBypass()+ m_absZIdxInCtu, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * m_uiNumPartition );
+  memcpy( pCtu->getMergeFlag()         + m_absZIdxInCtu, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( pCtu->getMergeIndex()        + m_absZIdxInCtu, m_puhMergeIndex,       iSizeInUchar );
+  #if H_3D_VSP
   memcpy( rpcCU->getVSPFlag()           + m_uiAbsIdxInLCU, m_piVSPFlag,           sizeof( Char ) * m_uiNumPartition );
   memcpy( rpcCU->getDvInfo()            + m_uiAbsIdxInLCU, m_pDvInfo,             sizeof( *m_pDvInfo ) * m_uiNumPartition );
@@ -1413,16 +1430,21 @@
   memcpy( rpcCU->getSPIVMPFlag()        + m_uiAbsIdxInLCU, m_pbSPIVMPFlag,        sizeof( Bool ) * m_uiNumPartition );
 #endif
-  memcpy( rpcCU->getLumaIntraDir()      + m_uiAbsIdxInLCU, m_puhLumaIntraDir,     iSizeInUchar );
-  memcpy( rpcCU->getChromaIntraDir()    + m_uiAbsIdxInLCU, m_puhChromaIntraDir,   iSizeInUchar );
-  memcpy( rpcCU->getInterDir()          + m_uiAbsIdxInLCU, m_puhInterDir,         iSizeInUchar );
-  memcpy( rpcCU->getTransformIdx()      + m_uiAbsIdxInLCU, m_puhTrIdx,            iSizeInUchar );
-  memcpy( rpcCU->getTransformSkip(TEXT_LUMA)     + m_uiAbsIdxInLCU, m_puhTransformSkip[0], iSizeInUchar );
-  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_U) + m_uiAbsIdxInLCU, m_puhTransformSkip[1], iSizeInUchar );
-  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_V) + m_uiAbsIdxInLCU, m_puhTransformSkip[2], iSizeInUchar );
-
-  memcpy( rpcCU->getCbf(TEXT_LUMA)     + m_uiAbsIdxInLCU, m_puhCbf[0], iSizeInUchar );
-  memcpy( rpcCU->getCbf(TEXT_CHROMA_U) + m_uiAbsIdxInLCU, m_puhCbf[1], iSizeInUchar );
-  memcpy( rpcCU->getCbf(TEXT_CHROMA_V) + m_uiAbsIdxInLCU, m_puhCbf[2], iSizeInUchar );
-  
+
+for (UInt ch=0; ch<numValidChan; ch++)
+  {
+    memcpy( pCtu->getIntraDir(ChannelType(ch)) + m_absZIdxInCtu, m_puhIntraDir[ch], iSizeInUchar);
+  }
+
+  memcpy( pCtu->getInterDir()          + m_absZIdxInCtu, m_puhInterDir,         iSizeInUchar );
+  memcpy( pCtu->getTransformIdx()      + m_absZIdxInCtu, m_puhTrIdx,            iSizeInUchar );
+
+  for(UInt comp=0; comp<numValidComp; comp++)
+  {
+    memcpy( pCtu->getCrossComponentPredictionAlpha(ComponentID(comp)) + m_absZIdxInCtu, m_crossComponentPredictionAlpha[comp], iSizeInUchar );
+    memcpy( pCtu->getTransformSkip(ComponentID(comp))                 + m_absZIdxInCtu, m_puhTransformSkip[comp],              iSizeInUchar );
+    memcpy( pCtu->getCbf(ComponentID(comp))                           + m_absZIdxInCtu, m_puhCbf[comp],                        iSizeInUchar );
+    memcpy( pCtu->getExplicitRdpcmMode(ComponentID(comp))             + m_absZIdxInCtu, m_explicitRdpcmMode[comp],             iSizeInUchar );
+  }
+
 #if H_3D_DIM
   for( Int i = 0; i < DIM_NUM_TYPE; i++ )
@@ -1446,39 +1468,37 @@
   memcpy( rpcCU->getDBBPFlag()          + m_uiAbsIdxInLCU, m_pbDBBPFlag,          iSizeInBool  );
 #endif
-  
-  memcpy( rpcCU->getDepth()  + m_uiAbsIdxInLCU, m_puhDepth,  iSizeInUchar );
-  memcpy( rpcCU->getWidth()  + m_uiAbsIdxInLCU, m_puhWidth,  iSizeInUchar );
-  memcpy( rpcCU->getHeight() + m_uiAbsIdxInLCU, m_puhHeight, iSizeInUchar );
-  
-  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_0) + m_uiAbsIdxInLCU, m_apiMVPIdx[0], iSizeInUchar );
-  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_1) + m_uiAbsIdxInLCU, m_apiMVPIdx[1], iSizeInUchar );
-  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_0) + m_uiAbsIdxInLCU, m_apiMVPNum[0], iSizeInUchar );
-  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_1) + m_uiAbsIdxInLCU, m_apiMVPNum[1], iSizeInUchar );
-  
-  m_acCUMvField[0].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_0 ), m_uiAbsIdxInLCU );
-  m_acCUMvField[1].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_1 ), m_uiAbsIdxInLCU );
-  
-  memcpy( rpcCU->getIPCMFlag() + m_uiAbsIdxInLCU, m_pbIPCMFlag,         iSizeInBool  );
-
-  UInt uiTmp  = (g_uiMaxCUWidth*g_uiMaxCUHeight)>>(uhDepth<<1);
-  UInt uiTmp2 = m_uiAbsIdxInLCU*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
-  memcpy( rpcCU->getCoeffY()  + uiTmp2, m_pcTrCoeffY,  sizeof(TCoeff)*uiTmp  );
-#if ADAPTIVE_QP_SELECTION  
-  memcpy( rpcCU->getArlCoeffY()  + uiTmp2, m_pcArlCoeffY,  sizeof(Int)*uiTmp  );
-#endif
-  memcpy( rpcCU->getPCMSampleY() + uiTmp2 , m_pcIPCMSampleY, sizeof(Pel)*uiTmp );
-
-  uiTmp >>= 2; uiTmp2 >>= 2;
-  memcpy( rpcCU->getCoeffCb() + uiTmp2, m_pcTrCoeffCb, sizeof(TCoeff)*uiTmp  );
-  memcpy( rpcCU->getCoeffCr() + uiTmp2, m_pcTrCoeffCr, sizeof(TCoeff)*uiTmp  );
+
+  memcpy( pCtu->getDepth()  + m_absZIdxInCtu, m_puhDepth,  iSizeInUchar );
+  memcpy( pCtu->getWidth()  + m_absZIdxInCtu, m_puhWidth,  iSizeInUchar );
+  memcpy( pCtu->getHeight() + m_absZIdxInCtu, m_puhHeight, iSizeInUchar );
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    memcpy( pCtu->getMVPIdx(rpl) + m_absZIdxInCtu, m_apiMVPIdx[rpl], iSizeInUchar );
+    memcpy( pCtu->getMVPNum(rpl) + m_absZIdxInCtu, m_apiMVPNum[rpl], iSizeInUchar );
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_acCUMvField[rpl].copyTo( pCtu->getCUMvField( rpl ), m_absZIdxInCtu );
+  }
+
+  memcpy( pCtu->getIPCMFlag() + m_absZIdxInCtu, m_pbIPCMFlag,         iSizeInBool  );
+
+  const UInt numCoeffY    = (pCtu->getSlice()->getSPS()->getMaxCUWidth()*pCtu->getSlice()->getSPS()->getMaxCUHeight())>>(uhDepth<<1);
+  const UInt offsetY      = m_absZIdxInCtu*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
+  for (UInt comp=0; comp<numValidComp; comp++)
+  {
+    const ComponentID component = ComponentID(comp);
+    const UInt componentShift   = m_pcPic->getComponentScaleX(component) + m_pcPic->getComponentScaleY(component);
+    memcpy( pCtu->getCoeff(component)   + (offsetY>>componentShift), m_pcTrCoeff[component], sizeof(TCoeff)*(numCoeffY>>componentShift) );
 #if ADAPTIVE_QP_SELECTION
-  memcpy( rpcCU->getArlCoeffCb() + uiTmp2, m_pcArlCoeffCb, sizeof(Int)*uiTmp  );
-  memcpy( rpcCU->getArlCoeffCr() + uiTmp2, m_pcArlCoeffCr, sizeof(Int)*uiTmp  );
-#endif
-  memcpy( rpcCU->getPCMSampleCb() + uiTmp2 , m_pcIPCMSampleCb, sizeof( Pel ) * uiTmp );
-  memcpy( rpcCU->getPCMSampleCr() + uiTmp2 , m_pcIPCMSampleCr, sizeof( Pel ) * uiTmp );
-  rpcCU->getTotalBins() = m_uiTotalBins;
-  memcpy( rpcCU->m_sliceStartCU        + m_uiAbsIdxInLCU, m_sliceStartCU,        sizeof( UInt ) * m_uiNumPartition  );
-  memcpy( rpcCU->m_sliceSegmentStartCU + m_uiAbsIdxInLCU, m_sliceSegmentStartCU, sizeof( UInt ) * m_uiNumPartition  );
+    memcpy( pCtu->getArlCoeff(component) + (offsetY>>componentShift), m_pcArlCoeff[component], sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#endif
+    memcpy( pCtu->getPCMSample(component) + (offsetY>>componentShift), m_pcIPCMSample[component], sizeof(Pel)*(numCoeffY>>componentShift) );
+  }
+
 #if H_3D_ARP
   memcpy( rpcCU->getARPW()             + m_uiAbsIdxInLCU, m_puhARPW,             iSizeInUchar );
@@ -1487,33 +1507,13 @@
   memcpy( rpcCU->getICFlag()           + m_uiAbsIdxInLCU, m_pbICFlag,            iSizeInBool );
 #endif
-}
-
-Void TComDataCU::copyToPic( UChar uhDepth, UInt uiPartIdx, UInt uiPartDepth )
-{
-  TComDataCU*&  rpcCU       = m_pcPic->getCU( m_uiCUAddr );
-  UInt          uiQNumPart  = m_uiNumPartition>>(uiPartDepth<<1);
-  
-  UInt uiPartStart          = uiPartIdx*uiQNumPart;
-  UInt uiPartOffset         = m_uiAbsIdxInLCU + uiPartStart;
-  
-  rpcCU->getTotalCost()       = m_dTotalCost;
-  rpcCU->getTotalDistortion() = m_uiTotalDistortion;
-  rpcCU->getTotalBits()       = m_uiTotalBits;
-  
-  Int iSizeInUchar  = sizeof( UChar  ) * uiQNumPart;
-  Int iSizeInBool   = sizeof( Bool   ) * uiQNumPart;
-  
-  Int sizeInChar  = sizeof( Char ) * uiQNumPart;
-  memcpy( rpcCU->getSkipFlag()       + uiPartOffset, m_skipFlag,   sizeof( *m_skipFlag )   * uiQNumPart );
+
+  pCtu->getTotalBins() = m_uiTotalBins;
+}
+
 #if H_3D
   memcpy( rpcCU->getDISFlag()  + uiPartOffset, m_bDISFlag,    sizeof( *m_bDISFlag )   * uiQNumPart );
   memcpy( rpcCU->getDISType()  + uiPartOffset, m_uiDISType,   sizeof( *m_uiDISType )  * uiQNumPart );
 #endif
-  memcpy( rpcCU->getQP() + uiPartOffset, m_phQP, sizeInChar );
-  memcpy( rpcCU->getPartitionSize()  + uiPartOffset, m_pePartSize, sizeof( *m_pePartSize ) * uiQNumPart );
-  memcpy( rpcCU->getPredictionMode() + uiPartOffset, m_pePredMode, sizeof( *m_pePredMode ) * uiQNumPart );
-  memcpy( rpcCU->getCUTransquantBypass()+ uiPartOffset, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * uiQNumPart );
-  memcpy( rpcCU->getMergeFlag()         + uiPartOffset, m_pbMergeFlag,         iSizeInBool  );
-  memcpy( rpcCU->getMergeIndex()        + uiPartOffset, m_puhMergeIndex,       iSizeInUchar );
+
 #if H_3D_VSP
   memcpy( rpcCU->getVSPFlag()           + uiPartOffset, m_piVSPFlag,           sizeof(Char) * uiQNumPart );
@@ -1522,14 +1522,4 @@
   memcpy( rpcCU->getSPIVMPFlag()        + uiPartOffset, m_pbSPIVMPFlag,        sizeof(Bool) * uiQNumPart );
 #endif
-  memcpy( rpcCU->getLumaIntraDir()      + uiPartOffset, m_puhLumaIntraDir,     iSizeInUchar );
-  memcpy( rpcCU->getChromaIntraDir()    + uiPartOffset, m_puhChromaIntraDir,   iSizeInUchar );
-  memcpy( rpcCU->getInterDir()          + uiPartOffset, m_puhInterDir,         iSizeInUchar );
-  memcpy( rpcCU->getTransformIdx()      + uiPartOffset, m_puhTrIdx,            iSizeInUchar );
-  memcpy( rpcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, m_puhTransformSkip[0], iSizeInUchar );
-  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, m_puhTransformSkip[1], iSizeInUchar );
-  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, m_puhTransformSkip[2], iSizeInUchar );
-  memcpy( rpcCU->getCbf(TEXT_LUMA)     + uiPartOffset, m_puhCbf[0], iSizeInUchar );
-  memcpy( rpcCU->getCbf(TEXT_CHROMA_U) + uiPartOffset, m_puhCbf[1], iSizeInUchar );
-  memcpy( rpcCU->getCbf(TEXT_CHROMA_V) + uiPartOffset, m_puhCbf[2], iSizeInUchar );
 #if H_3D_DIM
   for( Int i = 0; i < DMM_NUM_TYPE; i++ )
@@ -1553,40 +1543,4 @@
   memcpy( rpcCU->getDBBPFlag()          + uiPartOffset, m_pbDBBPFlag,          iSizeInBool  );
 #endif
-  
-  memcpy( rpcCU->getDepth()  + uiPartOffset, m_puhDepth,  iSizeInUchar );
-  memcpy( rpcCU->getWidth()  + uiPartOffset, m_puhWidth,  iSizeInUchar );
-  memcpy( rpcCU->getHeight() + uiPartOffset, m_puhHeight, iSizeInUchar );
-  
-  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_0) + uiPartOffset, m_apiMVPIdx[0], iSizeInUchar );
-  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_1) + uiPartOffset, m_apiMVPIdx[1], iSizeInUchar );
-  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_0) + uiPartOffset, m_apiMVPNum[0], iSizeInUchar );
-  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_1) + uiPartOffset, m_apiMVPNum[1], iSizeInUchar );
-  m_acCUMvField[0].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_0 ), m_uiAbsIdxInLCU, uiPartStart, uiQNumPart );
-  m_acCUMvField[1].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_1 ), m_uiAbsIdxInLCU, uiPartStart, uiQNumPart );
-  
-  memcpy( rpcCU->getIPCMFlag() + uiPartOffset, m_pbIPCMFlag,         iSizeInBool  );
-
-  UInt uiTmp  = (g_uiMaxCUWidth*g_uiMaxCUHeight)>>((uhDepth+uiPartDepth)<<1);
-  UInt uiTmp2 = uiPartOffset*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
-  memcpy( rpcCU->getCoeffY()  + uiTmp2, m_pcTrCoeffY,  sizeof(TCoeff)*uiTmp  );
-#if ADAPTIVE_QP_SELECTION
-  memcpy( rpcCU->getArlCoeffY()  + uiTmp2, m_pcArlCoeffY,  sizeof(Int)*uiTmp  );
-#endif
- 
-  memcpy( rpcCU->getPCMSampleY() + uiTmp2 , m_pcIPCMSampleY, sizeof( Pel ) * uiTmp );
-
-  uiTmp >>= 2; uiTmp2 >>= 2;
-  memcpy( rpcCU->getCoeffCb() + uiTmp2, m_pcTrCoeffCb, sizeof(TCoeff)*uiTmp  );
-  memcpy( rpcCU->getCoeffCr() + uiTmp2, m_pcTrCoeffCr, sizeof(TCoeff)*uiTmp  );
-#if ADAPTIVE_QP_SELECTION
-  memcpy( rpcCU->getArlCoeffCb() + uiTmp2, m_pcArlCoeffCb, sizeof(Int)*uiTmp  );
-  memcpy( rpcCU->getArlCoeffCr() + uiTmp2, m_pcArlCoeffCr, sizeof(Int)*uiTmp  );
-#endif
-
-  memcpy( rpcCU->getPCMSampleCb() + uiTmp2 , m_pcIPCMSampleCb, sizeof( Pel ) * uiTmp );
-  memcpy( rpcCU->getPCMSampleCr() + uiTmp2 , m_pcIPCMSampleCr, sizeof( Pel ) * uiTmp );
-  rpcCU->getTotalBins() = m_uiTotalBins;
-  memcpy( rpcCU->m_sliceStartCU        + uiPartOffset, m_sliceStartCU,        sizeof( UInt ) * uiQNumPart  );
-  memcpy( rpcCU->m_sliceSegmentStartCU + uiPartOffset, m_sliceSegmentStartCU, sizeof( UInt ) * uiQNumPart  );
 #if H_3D_ARP
   memcpy( rpcCU->getARPW()             + uiPartOffset, m_puhARPW,             iSizeInUchar );
@@ -1595,5 +1549,5 @@
   memcpy( rpcCU->getICFlag()           + uiPartOffset, m_pbICFlag,            iSizeInBool );
 #endif
-}
+
 
 
@@ -1602,79 +1556,72 @@
 // --------------------------------------------------------------------------------------------------------------------
 
-TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx, 
-                                   UInt uiCurrPartUnitIdx, 
-                                   Bool bEnforceSliceRestriction, 
+TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx,
+                                   UInt uiCurrPartUnitIdx,
+                                   Bool bEnforceSliceRestriction,
                                    Bool bEnforceTileRestriction )
 {
   UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
-  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
-  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
-  
-  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_absZIdxInCtu];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, numPartInCtuWidth ) )
   {
     uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
-    if ( RasterAddress::isEqualCol( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
-    {
-      return m_pcPic->getCU( getAddr() );
+    if ( RasterAddress::isEqualCol( uiAbsPartIdx, uiAbsZorderCUIdx, numPartInCtuWidth ) )
+    {
+      return m_pcPic->getCtu( getCtuRsAddr() );
     }
     else
     {
-      uiLPartUnitIdx -= m_uiAbsIdxInLCU;
+      uiLPartUnitIdx -= m_absZIdxInCtu;
       return this;
     }
   }
-  
-  uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + uiNumPartInCUWidth - 1 ];
-
-
-  if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
-      ||
-       (bEnforceTileRestriction && ( m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))  )  )
-      )
+
+  uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + numPartInCtuWidth - 1 ];
+  if ( (bEnforceSliceRestriction && !CUIsFromSameSlice(m_pCtuLeft)) || (bEnforceTileRestriction && !CUIsFromSameTile(m_pCtuLeft)) )
   {
     return NULL;
   }
-  return m_pcCULeft;
-}
+  return m_pCtuLeft;
+}
+
 
 TComDataCU* TComDataCU::getPUAbove( UInt& uiAPartUnitIdx,
-                                    UInt uiCurrPartUnitIdx, 
-                                    Bool bEnforceSliceRestriction, 
-                                    Bool planarAtLCUBoundary ,
+                                    UInt uiCurrPartUnitIdx,
+                                    Bool bEnforceSliceRestriction,
+                                    Bool planarAtCtuBoundary,
                                     Bool bEnforceTileRestriction )
 {
   UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
-  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
-  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
-  
-  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
-  {
-    uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - uiNumPartInCUWidth ];
-    if ( RasterAddress::isEqualRow( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
-    {
-      return m_pcPic->getCU( getAddr() );
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_absZIdxInCtu];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, numPartInCtuWidth ) )
+  {
+    uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - numPartInCtuWidth ];
+    if ( RasterAddress::isEqualRow( uiAbsPartIdx, uiAbsZorderCUIdx, numPartInCtuWidth ) )
+    {
+      return m_pcPic->getCtu( getCtuRsAddr() );
     }
     else
     {
-      uiAPartUnitIdx -= m_uiAbsIdxInLCU;
+      uiAPartUnitIdx -= m_absZIdxInCtu;
       return this;
     }
   }
 
-  if(planarAtLCUBoundary)
+  if(planarAtCtuBoundary)
   {
     return NULL;
   }
-  
-  uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
-
-  if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
-      ||
-       (bEnforceTileRestriction &&(m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))))
-      )
+
+  uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + m_pcPic->getNumPartitionsInCtu() - numPartInCtuWidth ];
+
+  if ( (bEnforceSliceRestriction && !CUIsFromSameSlice(m_pCtuAbove)) || (bEnforceTileRestriction && !CUIsFromSameTile(m_pCtuAbove)) )
   {
     return NULL;
   }
-  return m_pcCUAbove;
+  return m_pCtuAbove;
 }
 
@@ -1682,295 +1629,163 @@
 {
   UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
-  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
-  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
-  
-  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, uiNumPartInCUWidth ) )
-  {
-    if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
-    {
-      uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - uiNumPartInCUWidth - 1 ];
-      if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
-      {
-        return m_pcPic->getCU( getAddr() );
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_absZIdxInCtu];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, numPartInCtuWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdx, numPartInCtuWidth ) )
+    {
+      uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - numPartInCtuWidth - 1 ];
+      if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdx, uiAbsZorderCUIdx, numPartInCtuWidth ) )
+      {
+        return m_pcPic->getCtu( getCtuRsAddr() );
       }
       else
       {
-        uiALPartUnitIdx -= m_uiAbsIdxInLCU;
+        uiALPartUnitIdx -= m_absZIdxInCtu;
         return this;
       }
     }
-    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + getPic()->getNumPartInCU() - uiNumPartInCUWidth - 1 ];
-    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL ||
-       m_pcCUAbove->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + getPic()->getNumPartitionsInCtu() - numPartInCtuWidth - 1 ];
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAbove) )
     {
       return NULL;
     }
-    return m_pcCUAbove;
-  }
-  
-  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
+    return m_pCtuAbove;
+  }
+
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, numPartInCtuWidth ) )
   {
     uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
-    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
-       m_pcCULeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuLeft) )
     {
       return NULL;
     }
-    return m_pcCULeft;
-  }
-  
-  uiALPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - 1 ];
-  if ( (bEnforceSliceRestriction && (m_pcCUAboveLeft==NULL || m_pcCUAboveLeft->getSlice()==NULL ||
-       m_pcCUAboveLeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveLeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
+    return m_pCtuLeft;
+  }
+
+  uiALPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartitionsInCtu() - 1 ];
+  if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAboveLeft) )
   {
     return NULL;
   }
-  return m_pcCUAboveLeft;
-}
-
-TComDataCU* TComDataCU::getPUAboveRight( UInt& uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
-{
-  UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
-  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1;
-  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
-  
-  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
-  {
-    uiARPartUnitIdx = MAX_UINT;
+  return m_pCtuAboveLeft;
+}
+
+TComDataCU* TComDataCU::getPUBelowLeft(UInt& uiBLPartUnitIdx,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction)
+{
+  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_absZIdxInCtu ] + ((m_puhHeight[0] / m_pcPic->getMinCUHeight()) - 1)*numPartInCtuWidth;
+
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples())
+  {
+    uiBLPartUnitIdx = MAX_UINT;
     return NULL;
   }
-  
-  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, uiNumPartInCUWidth - 1, uiNumPartInCUWidth ) )
-  {
-    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
-    {
-      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ] )
-      {
-        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ];
-        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+
+  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInCtuHeight() - uiPartUnitOffset, numPartInCtuWidth ) )
+  {
+    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, numPartInCtuWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * numPartInCtuWidth - 1 ] )
+      {
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * numPartInCtuWidth - 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, numPartInCtuWidth ) )
         {
-          return m_pcPic->getCU( getAddr() );
+          return m_pcPic->getCtu( getCtuRsAddr() );
         }
         else
         {
-          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+          uiBLPartUnitIdx -= m_absZIdxInCtu;
           return this;
         }
       }
-      uiARPartUnitIdx = MAX_UINT;
+      uiBLPartUnitIdx = MAX_UINT;
       return NULL;
     }
-    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + 1 ];
-    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL ||
-       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + (1+uiPartUnitOffset) * numPartInCtuWidth - 1 ];
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuLeft) )
     {
       return NULL;
     }
-    return m_pcCUAbove;
-  }
-  
-  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+    return m_pCtuLeft;
+  }
+
+  uiBLPartUnitIdx = MAX_UINT;
+  return NULL;
+}
+
+TComDataCU* TComDataCU::getPUAboveRight(UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction)
+{
+  UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[ m_absZIdxInCtu ] + (m_puhWidth[0] / m_pcPic->getMinCUWidth()) - 1;
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
   {
     uiARPartUnitIdx = MAX_UINT;
     return NULL;
   }
-  
-  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
-  if ( (bEnforceSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL ||
-       m_pcPic->getPicSym()->getInverseCUOrderMap( m_pcCUAboveRight->getAddr()) > m_pcPic->getPicSym()->getInverseCUOrderMap( getAddr()) ||
-       m_pcCUAboveRight->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
-  {
-    return NULL;
-  }
-  return m_pcCUAboveRight;
-}
-
-TComDataCU* TComDataCU::getPUBelowLeft( UInt& uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
-{
-  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
-  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + (m_puhHeight[0] / m_pcPic->getMinCUHeight() - 1)*m_pcPic->getNumPartInWidth();
-  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
-  
-  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
-  {
-    uiBLPartUnitIdx = MAX_UINT;
-    return NULL;
-  }
-  
-  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInHeight() - 1, uiNumPartInCUWidth ) )
-  {
-    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, uiNumPartInCUWidth ) )
-    {
-      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ] )
-      {
-        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ];
-        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, uiNumPartInCUWidth ) )
+
+  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, numPartInCtuWidth - uiPartUnitOffset, numPartInCtuWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, numPartInCtuWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - numPartInCtuWidth + uiPartUnitOffset ] )
+      {
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - numPartInCtuWidth + uiPartUnitOffset ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, numPartInCtuWidth ) )
         {
-          return m_pcPic->getCU( getAddr() );
+          return m_pcPic->getCtu( getCtuRsAddr() );
         }
         else
         {
-          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+          uiARPartUnitIdx -= m_absZIdxInCtu;
           return this;
         }
       }
-      uiBLPartUnitIdx = MAX_UINT;
+      uiARPartUnitIdx = MAX_UINT;
       return NULL;
     }
-    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth*2 - 1 ];
-    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
-       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
+
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartitionsInCtu() - numPartInCtuWidth + uiPartUnitOffset ];
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAbove) )
     {
       return NULL;
     }
-    return m_pcCULeft;
-  }
-  
-  uiBLPartUnitIdx = MAX_UINT;
-  return NULL;
-}
-
-TComDataCU* TComDataCU::getPUBelowLeftAdi(UInt& uiBLPartUnitIdx,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction )
-{
-  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
-  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ((m_puhHeight[0] / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInWidth();
-  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
-  
-  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples())
-  {
-    uiBLPartUnitIdx = MAX_UINT;
-    return NULL;
-  }
-  
-  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInHeight() - uiPartUnitOffset, uiNumPartInCUWidth ) )
-  {
-    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, uiNumPartInCUWidth ) )
-    {
-      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * uiNumPartInCUWidth - 1 ] )
-      {
-        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * uiNumPartInCUWidth - 1 ];
-        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, uiNumPartInCUWidth ) )
-        {
-          return m_pcPic->getCU( getAddr() );
-        }
-        else
-        {
-          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
-          return this;
-        }
-      }
-      uiBLPartUnitIdx = MAX_UINT;
-      return NULL;
-    }
-    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + (1+uiPartUnitOffset) * uiNumPartInCUWidth - 1 ];
-    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
-       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
-    {
-      return NULL;
-    }
-    return m_pcCULeft;
-  }
-  
-  uiBLPartUnitIdx = MAX_UINT;
-  return NULL;
-}
-
-TComDataCU* TComDataCU::getPUAboveRightAdi(UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction )
-{
-  UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
-  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + (m_puhWidth[0] / m_pcPic->getMinCUWidth()) - 1;
-  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
-  
-  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+    return m_pCtuAbove;
+  }
+
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, numPartInCtuWidth ) )
   {
     uiARPartUnitIdx = MAX_UINT;
     return NULL;
   }
-  
-  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, uiNumPartInCUWidth - uiPartUnitOffset, uiNumPartInCUWidth ) )
-  {
-    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
-    {
-      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + uiPartUnitOffset ] )
-      {
-        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + uiPartUnitOffset ];
-        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
-        {
-          return m_pcPic->getCU( getAddr() );
-        }
-        else
-        {
-          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
-          return this;
-        }
-      }
-      uiARPartUnitIdx = MAX_UINT;
-      return NULL;
-    }
-    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + uiPartUnitOffset ];
-    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
-       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
-    {
-      return NULL;
-    }
-    return m_pcCUAbove;
-  }
-  
-  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
-  {
-    uiARPartUnitIdx = MAX_UINT;
+
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartitionsInCtu() - numPartInCtuWidth + uiPartUnitOffset-1 ];
+  if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAboveRight) )
+  {
     return NULL;
   }
-  
-  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + uiPartUnitOffset-1 ];
-  if ( (bEnforceSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL ||
-       m_pcPic->getPicSym()->getInverseCUOrderMap( m_pcCUAboveRight->getAddr()) > m_pcPic->getPicSym()->getInverseCUOrderMap( getAddr()) ||
-       m_pcCUAboveRight->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
-       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
-       ))
-     )
-  {
-    return NULL;
-  }
-  return m_pcCUAboveRight;
+  return m_pCtuAboveRight;
 }
 
 /** Get left QpMinCu
 *\param   uiLPartUnitIdx
-*\param   uiCurrAbsIdxInLCU
+*\param   uiCurrAbsIdxInCtu
 *\returns TComDataCU*   point of TComDataCU of left QpMinCu
 */
-TComDataCU* TComDataCU::getQpMinCuLeft( UInt& uiLPartUnitIdx, UInt uiCurrAbsIdxInLCU)
-{
-  UInt numPartInCUWidth = m_pcPic->getNumPartInWidth();
-  UInt absZorderQpMinCUIdx = (uiCurrAbsIdxInLCU>>((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth -getSlice()->getPPS()->getMaxCuDQPDepth())<<1);
+TComDataCU* TComDataCU::getQpMinCuLeft( UInt& uiLPartUnitIdx, UInt uiCurrAbsIdxInCtu )
+{
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  const UInt maxCUDepth        = getSlice()->getSPS()->getMaxTotalCUDepth();
+  const UInt maxCuDQPDepth     = getSlice()->getPPS()->getMaxCuDQPDepth();
+  const UInt doubleDepthDifference = ((maxCUDepth - maxCuDQPDepth)<<1);
+  UInt absZorderQpMinCUIdx = (uiCurrAbsIdxInCtu>>doubleDepthDifference)<<doubleDepthDifference;
   UInt absRorderQpMinCUIdx = g_auiZscanToRaster[absZorderQpMinCUIdx];
 
-  // check for left LCU boundary
-  if ( RasterAddress::isZeroCol(absRorderQpMinCUIdx, numPartInCUWidth) )
+  // check for left CTU boundary
+  if ( RasterAddress::isZeroCol(absRorderQpMinCUIdx, numPartInCtuWidth) )
   {
     return NULL;
@@ -1980,21 +1795,24 @@
   uiLPartUnitIdx = g_auiRasterToZscan[absRorderQpMinCUIdx - 1];
 
-  // return pointer to current LCU
-  return m_pcPic->getCU( getAddr() );
+  // return pointer to current CTU
+  return m_pcPic->getCtu( getCtuRsAddr() );
 }
 
 /** Get Above QpMinCu
-*\param   aPartUnitIdx
-*\param   currAbsIdxInLCU
+*\param   uiAPartUnitIdx
+*\param   uiCurrAbsIdxInCtu
 *\returns TComDataCU*   point of TComDataCU of above QpMinCu
 */
-TComDataCU* TComDataCU::getQpMinCuAbove( UInt& aPartUnitIdx, UInt currAbsIdxInLCU )
-{
-  UInt numPartInCUWidth = m_pcPic->getNumPartInWidth();
-  UInt absZorderQpMinCUIdx = (currAbsIdxInLCU>>((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1);
+TComDataCU* TComDataCU::getQpMinCuAbove( UInt& uiAPartUnitIdx, UInt uiCurrAbsIdxInCtu )
+{
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  const UInt maxCUDepth        = getSlice()->getSPS()->getMaxTotalCUDepth();
+  const UInt maxCuDQPDepth     = getSlice()->getPPS()->getMaxCuDQPDepth();
+  const UInt doubleDepthDifference = ((maxCUDepth - maxCuDQPDepth)<<1);
+  UInt absZorderQpMinCUIdx = (uiCurrAbsIdxInCtu>>doubleDepthDifference)<<doubleDepthDifference;
   UInt absRorderQpMinCUIdx = g_auiZscanToRaster[absZorderQpMinCUIdx];
 
-  // check for top LCU boundary
-  if ( RasterAddress::isZeroRow( absRorderQpMinCUIdx, numPartInCUWidth) )
+  // check for top CTU boundary
+  if ( RasterAddress::isZeroRow( absRorderQpMinCUIdx, numPartInCtuWidth) )
   {
     return NULL;
@@ -2002,20 +1820,23 @@
 
   // get index of top-CU relative to top-left corner of current quantization group
-  aPartUnitIdx = g_auiRasterToZscan[absRorderQpMinCUIdx - numPartInCUWidth];
-
-  // return pointer to current LCU
-  return m_pcPic->getCU( getAddr() );
-}
+  uiAPartUnitIdx = g_auiRasterToZscan[absRorderQpMinCUIdx - numPartInCtuWidth];
+
+  // return pointer to current CTU
+  return m_pcPic->getCtu( getCtuRsAddr() );
+}
+
+
 
 /** Get reference QP from left QpMinCu or latest coded QP
-*\param   uiCurrAbsIdxInLCU
+*\param   uiCurrAbsIdxInCtu
 *\returns Char   reference QP value
 */
-Char TComDataCU::getRefQP( UInt uiCurrAbsIdxInLCU )
-{
-  UInt        lPartIdx = 0, aPartIdx = 0;
-  TComDataCU* cULeft  = getQpMinCuLeft ( lPartIdx, m_uiAbsIdxInLCU + uiCurrAbsIdxInLCU );
-  TComDataCU* cUAbove = getQpMinCuAbove( aPartIdx, m_uiAbsIdxInLCU + uiCurrAbsIdxInLCU );
-  return (((cULeft? cULeft->getQP( lPartIdx ): getLastCodedQP( uiCurrAbsIdxInLCU )) + (cUAbove? cUAbove->getQP( aPartIdx ): getLastCodedQP( uiCurrAbsIdxInLCU )) + 1) >> 1);
+Char TComDataCU::getRefQP( UInt uiCurrAbsIdxInCtu )
+{
+  UInt lPartIdx = MAX_UINT;
+  UInt aPartIdx = MAX_UINT;
+  TComDataCU* cULeft  = getQpMinCuLeft ( lPartIdx, m_absZIdxInCtu + uiCurrAbsIdxInCtu );
+  TComDataCU* cUAbove = getQpMinCuAbove( aPartIdx, m_absZIdxInCtu + uiCurrAbsIdxInCtu );
+  return (((cULeft? cULeft->getQP( lPartIdx ): getLastCodedQP( uiCurrAbsIdxInCtu )) + (cUAbove? cUAbove->getQP( aPartIdx ): getLastCodedQP( uiCurrAbsIdxInCtu )) + 1) >> 1);
 }
 
@@ -2024,5 +1845,5 @@
   Int iLastValidPartIdx = iAbsPartIdx-1;
   while ( iLastValidPartIdx >= 0
-       && getPredictionMode( iLastValidPartIdx ) == MODE_NONE )
+       && getPredictionMode( iLastValidPartIdx ) == NUMBER_OF_PREDICTION_MODES )
   {
     UInt uiDepth = getDepth( iLastValidPartIdx );
@@ -2034,8 +1855,8 @@
 Char TComDataCU::getLastCodedQP( UInt uiAbsPartIdx )
 {
-  UInt uiQUPartIdxMask = ~((1<<((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))-1);
-  Int iLastValidPartIdx = getLastValidPartIdx( uiAbsPartIdx&uiQUPartIdxMask );
-  if ( uiAbsPartIdx < m_uiNumPartition
-    && (getSCUAddr()+iLastValidPartIdx < getSliceStartCU(m_uiAbsIdxInLCU+uiAbsPartIdx)))
+  UInt uiQUPartIdxMask = ~((1<<((getSlice()->getSPS()->getMaxTotalCUDepth() - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))-1);
+  Int iLastValidPartIdx = getLastValidPartIdx( uiAbsPartIdx&uiQUPartIdxMask ); // A idx will be invalid if it is off the right or bottom edge of the picture.
+  // If this CU is in the first CTU of the slice and there is no valid part before this one, use slice QP
+  if ( getPic()->getPicSym()->getCtuTsToRsAddrMap(getSlice()->getSliceCurStartCtuTsAddr()) == getCtuRsAddr() && Int(getZorderIdxInCtu())+iLastValidPartIdx<0)
   {
     return getSlice()->getSliceQp();
@@ -2043,27 +1864,32 @@
   else if ( iLastValidPartIdx >= 0 )
   {
+    // If there is a valid part within the current Sub-CU, use it
     return getQP( iLastValidPartIdx );
   }
   else
   {
-    if ( getZorderIdxInCU() > 0 )
-    {
-      return getPic()->getCU( getAddr() )->getLastCodedQP( getZorderIdxInCU() );
-    }
-    else if ( getPic()->getPicSym()->getInverseCUOrderMap(getAddr()) > 0
-      && getPic()->getPicSym()->getTileIdxMap(getAddr()) == getPic()->getPicSym()->getTileIdxMap(getPic()->getPicSym()->getCUOrderMap(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())-1))
-      && !( getSlice()->getPPS()->getEntropyCodingSyncEnabledFlag() && getAddr() % getPic()->getFrameWidthInCU() == 0 ) )
-    {
-      return getPic()->getCU( getPic()->getPicSym()->getCUOrderMap(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())-1) )->getLastCodedQP( getPic()->getNumPartInCU() );
+    if ( getZorderIdxInCtu() > 0 )
+    {
+      // If this wasn't the first sub-cu within the Ctu, explore the CTU itself.
+      return getPic()->getCtu( getCtuRsAddr() )->getLastCodedQP( getZorderIdxInCtu() ); // TODO - remove this recursion
+    }
+    else if ( getPic()->getPicSym()->getCtuRsToTsAddrMap(getCtuRsAddr()) > 0
+      && CUIsFromSameSliceTileAndWavefrontRow(getPic()->getCtu(getPic()->getPicSym()->getCtuTsToRsAddrMap(getPic()->getPicSym()->getCtuRsToTsAddrMap(getCtuRsAddr())-1))) )
+    {
+      // If this isn't the first Ctu (how can it be due to the first 'if'?), and the previous Ctu is from the same tile, examine the previous Ctu.
+      return getPic()->getCtu( getPic()->getPicSym()->getCtuTsToRsAddrMap(getPic()->getPicSym()->getCtuRsToTsAddrMap(getCtuRsAddr())-1) )->getLastCodedQP( getPic()->getNumPartitionsInCtu() );  // TODO - remove this recursion
     }
     else
     {
+      // No other options available - use the slice-level QP.
       return getSlice()->getSliceQp();
     }
   }
 }
-/** Check whether the CU is coded in lossless coding mode
- * \param   uiAbsPartIdx
- * \returns true if the CU is coded in lossless coding mode; false if otherwise 
+
+
+/** Check whether the CU is coded in lossless coding mode.
+ * \param   absPartIdx
+ * \returns true if the CU is coded in lossless coding mode; false if otherwise
  */
 Bool TComDataCU::isLosslessCoded(UInt absPartIdx)
@@ -2072,11 +1898,12 @@
 }
 
+
 /** Get allowed chroma intra modes
-*\param   uiAbsPartIdx
-*\param   uiModeList  pointer to chroma intra modes array
-*\returns 
-*- fill uiModeList with chroma intra modes
+*   - fills uiModeList with chroma intra modes
+*
+*\param   [in]  uiAbsPartIdx
+*\param   [out] uiModeList pointer to chroma intra modes array
 */
-Void TComDataCU::getAllowedChromaDir( UInt uiAbsPartIdx, UInt* uiModeList )
+Void TComDataCU::getAllowedChromaDir( UInt uiAbsPartIdx, UInt uiModeList[NUM_CHROMA_MODE] )
 {
   uiModeList[0] = PLANAR_IDX;
@@ -2085,6 +1912,7 @@
   uiModeList[3] = DC_IDX;
   uiModeList[4] = DM_CHROMA_IDX;
-
-  UInt uiLumaMode = getLumaIntraDir( uiAbsPartIdx );
+  assert(4<NUM_CHROMA_MODE);
+
+  UInt uiLumaMode = getIntraDir( CHANNEL_TYPE_LUMA, uiAbsPartIdx );
 
   for( Int i = 0; i < NUM_CHROMA_MODE - 1; i++ )
@@ -2099,33 +1927,59 @@
 
 /** Get most probable intra modes
-*\param   uiAbsPartIdx
+*\param   uiAbsPartIdx    partition index
 *\param   uiIntraDirPred  pointer to the array for MPM storage
+*\param   compID          colour component ID
 *\param   piMode          it is set with MPM mode in case both MPM are equal. It is used to restrict RD search at encode side.
 *\returns Number of MPM
 */
-Int TComDataCU::getIntraDirLumaPredictor( UInt uiAbsPartIdx, Int* uiIntraDirPred, Int* piMode  )
-{
-  TComDataCU* pcTempCU;
-  UInt        uiTempPartIdx;
+Void TComDataCU::getIntraDirPredictor( UInt uiAbsPartIdx, Int uiIntraDirPred[NUM_MOST_PROBABLE_MODES], const ComponentID compID, Int* piMode  )
+{
+  TComDataCU* pcCULeft, *pcCUAbove;
+  UInt        LeftPartIdx  = MAX_UINT;
+  UInt        AbovePartIdx = MAX_UINT;
   Int         iLeftIntraDir, iAboveIntraDir;
-  Int         uiPredNum = 0;
-  
+  const TComSPS *sps=getSlice()->getSPS();
+  const UInt partsPerMinCU = 1<<(2*(sps->getMaxTotalCUDepth() - sps->getLog2DiffMaxMinCodingBlockSize()));
+
+  const ChannelType chType = toChannelType(compID);
+  const ChromaFormat chForm = getPic()->getChromaFormat();
   // Get intra direction of left PU
-  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
-  
-  iLeftIntraDir  = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+  pcCULeft = getPULeft( LeftPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
+
+  if (isChroma(compID))
+  {
+    LeftPartIdx = getChromasCorrespondingPULumaIdx(LeftPartIdx, chForm, partsPerMinCU);
+  }
+  iLeftIntraDir  = pcCULeft ? ( pcCULeft->isIntra( LeftPartIdx ) ? pcCULeft->getIntraDir( chType, LeftPartIdx ) : DC_IDX ) : DC_IDX;
 #if H_3D_DIM
   mapDepthModeToIntraDir( iLeftIntraDir );
 #endif
-  
+
   // Get intra direction of above PU
-  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, true );
-  
-  iAboveIntraDir = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+  pcCUAbove = getPUAbove( AbovePartIdx, m_absZIdxInCtu + uiAbsPartIdx, true, true );
+
+  if (isChroma(compID))
+  {
+    AbovePartIdx = getChromasCorrespondingPULumaIdx(AbovePartIdx, chForm, partsPerMinCU);
+  }
+  iAboveIntraDir = pcCUAbove ? ( pcCUAbove->isIntra( AbovePartIdx ) ? pcCUAbove->getIntraDir( chType, AbovePartIdx ) : DC_IDX ) : DC_IDX;
 #if H_3D_DIM
   mapDepthModeToIntraDir( iAboveIntraDir );
 #endif
-  
-  uiPredNum = 3;
+
+
+  if (isChroma(chType))
+  {
+    if (iLeftIntraDir  == DM_CHROMA_IDX)
+    {
+      iLeftIntraDir  = pcCULeft-> getIntraDir( CHANNEL_TYPE_LUMA, LeftPartIdx  );
+    }
+    if (iAboveIntraDir == DM_CHROMA_IDX)
+    {
+      iAboveIntraDir = pcCUAbove->getIntraDir( CHANNEL_TYPE_LUMA, AbovePartIdx );
+    }
+  }
+
+  assert (2<NUM_MOST_PROBABLE_MODES);
   if(iLeftIntraDir == iAboveIntraDir)
   {
@@ -2134,5 +1988,5 @@
       *piMode = 1;
     }
-    
+
     if (iLeftIntraDir > 1) // angular modes
     {
@@ -2145,5 +1999,5 @@
       uiIntraDirPred[0] = PLANAR_IDX;
       uiIntraDirPred[1] = DC_IDX;
-      uiIntraDirPred[2] = VER_IDX; 
+      uiIntraDirPred[2] = VER_IDX;
     }
   }
@@ -2156,5 +2010,5 @@
     uiIntraDirPred[0] = iLeftIntraDir;
     uiIntraDirPred[1] = iAboveIntraDir;
-    
+
     if (iLeftIntraDir && iAboveIntraDir ) //both modes are non-planar
     {
@@ -2166,6 +2020,8 @@
     }
   }
-  
-  return uiPredNum;
+  for (UInt i=0; i<NUM_MOST_PROBABLE_MODES; i++)
+  {
+    assert(uiIntraDirPred[i] < 35);
+  }
 }
 
@@ -2176,23 +2032,25 @@
   UInt        uiCtx;
   // Get left split flag
-  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  pcTempCU = getPULeft( uiTempPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
   uiCtx  = ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
-  
+
   // Get above split flag
-  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  pcTempCU = getPUAbove( uiTempPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
   uiCtx += ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
-  
+
   return uiCtx;
 }
 
-UInt TComDataCU::getCtxQtCbf( TextType eType, UInt uiTrDepth )
-{
-  if( eType )
-  {
-    return uiTrDepth;
+UInt TComDataCU::getCtxQtCbf( TComTU &rTu, const ChannelType chType )
+{
+  const UInt transformDepth = rTu.GetTransformDepthRel();
+
+  if (isChroma(chType))
+  {
+    return transformDepth;
   }
   else
   {
-    const UInt uiCtx = ( uiTrDepth == 0 ? 1 : 0 );
+    const UInt uiCtx = ( transformDepth == 0 ? 1 : 0 );
     return uiCtx;
   }
@@ -2203,10 +2061,10 @@
   UInt log2CbSize = g_aucConvertToBit[getWidth( absPartIdx )] + 2;
   PartSize  partSize  = getPartitionSize( absPartIdx );
-  UInt quadtreeTUMaxDepth = getPredictionMode( absPartIdx ) == MODE_INTRA ? m_pcSlice->getSPS()->getQuadtreeTUMaxDepthIntra() : m_pcSlice->getSPS()->getQuadtreeTUMaxDepthInter(); 
-  Int intraSplitFlag = ( getPredictionMode( absPartIdx ) == MODE_INTRA && partSize == SIZE_NxN ) ? 1 : 0;
-  Int interSplitFlag = ((quadtreeTUMaxDepth == 1) && (getPredictionMode( absPartIdx ) == MODE_INTER) && (partSize != SIZE_2Nx2N) );
-  
+  UInt quadtreeTUMaxDepth = isIntra( absPartIdx ) ? m_pcSlice->getSPS()->getQuadtreeTUMaxDepthIntra() : m_pcSlice->getSPS()->getQuadtreeTUMaxDepthInter();
+  Int intraSplitFlag = ( isIntra( absPartIdx ) && partSize == SIZE_NxN ) ? 1 : 0;
+  Int interSplitFlag = ((quadtreeTUMaxDepth == 1) && isInter( absPartIdx ) && (partSize != SIZE_2Nx2N) );
+
   UInt log2MinTUSizeInCU = 0;
-  if (log2CbSize < (m_pcSlice->getSPS()->getQuadtreeTULog2MinSize() + quadtreeTUMaxDepth - 1 + interSplitFlag + intraSplitFlag) ) 
+  if (log2CbSize < (m_pcSlice->getSPS()->getQuadtreeTULog2MinSize() + quadtreeTUMaxDepth - 1 + interSplitFlag + intraSplitFlag) )
   {
     // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is < QuadtreeTULog2MinSize
@@ -2221,5 +2079,5 @@
       // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is still > QuadtreeTULog2MaxSize
       log2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize();
-    }  
+    }
   }
   return log2MinTUSizeInCU;
@@ -2231,16 +2089,15 @@
   UInt        uiTempPartIdx;
   UInt        uiCtx = 0;
-  
+
   // Get BCBP of left PU
-  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  pcTempCU = getPULeft( uiTempPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
   uiCtx    = ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
-  
+
   // Get BCBP of above PU
-  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  pcTempCU = getPUAbove( uiTempPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
   uiCtx   += ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
-  
+
   return uiCtx;
 }
-
 #if H_3D_ARP
 UInt TComDataCU::getCTXARPWFlag( UInt uiAbsPartIdx )
@@ -2343,4 +2200,5 @@
 #endif
 
+
 UInt TComDataCU::getCtxInterDir( UInt uiAbsPartIdx )
 {
@@ -2348,35 +2206,58 @@
 }
 
-Void TComDataCU::setCbfSubParts( UInt uiCbfY, UInt uiCbfU, UInt uiCbfV, UInt uiAbsPartIdx, UInt uiDepth )
-{
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-  memset( m_puhCbf[0] + uiAbsPartIdx, uiCbfY, sizeof( UChar ) * uiCurrPartNumb );
-  memset( m_puhCbf[1] + uiAbsPartIdx, uiCbfU, sizeof( UChar ) * uiCurrPartNumb );
-  memset( m_puhCbf[2] + uiAbsPartIdx, uiCbfV, sizeof( UChar ) * uiCurrPartNumb );
-}
-
-Void TComDataCU::setCbfSubParts( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiDepth )
-{
-
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-  memset( m_puhCbf[g_aucConvertTxtTypeToIdx[eTType]] + uiAbsPartIdx, uiCbf, sizeof( UChar ) * uiCurrPartNumb );
+
+UChar TComDataCU::getQtRootCbf( UInt uiIdx )
+{
+  const UInt numberValidComponents = getPic()->getNumberValidComponents();
+  return getCbf( uiIdx, COMPONENT_Y, 0 )
+          || ((numberValidComponents > COMPONENT_Cb) && getCbf( uiIdx, COMPONENT_Cb, 0 ))
+          || ((numberValidComponents > COMPONENT_Cr) && getCbf( uiIdx, COMPONENT_Cr, 0 ));
+}
+
+Void TComDataCU::setCbfSubParts( const UInt uiCbf[MAX_NUM_COMPONENT], UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    memset( m_puhCbf[comp] + uiAbsPartIdx, uiCbf[comp], sizeof( UChar ) * uiCurrPartNumb );
+  }
+}
+
+Void TComDataCU::setCbfSubParts( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  memset( m_puhCbf[compID] + uiAbsPartIdx, uiCbf, sizeof( UChar ) * uiCurrPartNumb );
 }
 
 /** Sets a coded block flag for all sub-partitions of a partition
- * \param uiCbf The value of the coded block flag to be set
- * \param eTType
+ * \param uiCbf          The value of the coded block flag to be set
+ * \param compID
  * \param uiAbsPartIdx
  * \param uiPartIdx
  * \param uiDepth
- * \returns Void
  */
-Void TComDataCU::setCbfSubParts ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
-{
-  setSubPart<UChar>( uiCbf, m_puhCbf[g_aucConvertTxtTypeToIdx[eTType]], uiAbsPartIdx, uiDepth, uiPartIdx );
+Void TComDataCU::setCbfSubParts ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiCbf, m_puhCbf[compID], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setCbfPartRange ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_puhCbf[compID] + uiAbsPartIdx), uiCbf, (sizeof(UChar) * uiCoveredPartIdxes));
+}
+
+Void TComDataCU::bitwiseOrCbfPartRange( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  const UInt stopAbsPartIdx = uiAbsPartIdx + uiCoveredPartIdxes;
+
+  for (UInt subPartIdx = uiAbsPartIdx; subPartIdx < stopAbsPartIdx; subPartIdx++)
+  {
+    m_puhCbf[compID][subPartIdx] |= uiCbf;
+  }
 }
 
 Void TComDataCU::setDepthSubParts( UInt uiDepth, UInt uiAbsPartIdx )
 {
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
   memset( m_puhDepth + uiAbsPartIdx, uiDepth, sizeof(UChar)*uiCurrPartNumb );
 }
@@ -2384,6 +2265,6 @@
 Bool TComDataCU::isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth)
 {
-  UInt uiPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-  return (((m_uiAbsIdxInLCU + uiAbsPartIdx)% uiPartNumb) == 0);
+  UInt uiPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  return (((m_absZIdxInCtu + uiAbsPartIdx)% uiPartNumb) == 0);
 }
 
@@ -2391,10 +2272,10 @@
 {
   assert( sizeof( *m_pePartSize) == 1 );
-  memset( m_pePartSize + uiAbsPartIdx, eMode, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+  memset( m_pePartSize + uiAbsPartIdx, eMode, m_pcPic->getNumPartitionsInCtu() >> ( 2 * uiDepth ) );
 }
 
 Void TComDataCU::setCUTransquantBypassSubParts( Bool flag, UInt uiAbsPartIdx, UInt uiDepth )
 {
-  memset( m_CUTransquantBypass + uiAbsPartIdx, flag, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+  memset( m_CUTransquantBypass + uiAbsPartIdx, flag, m_pcPic->getNumPartitionsInCtu() >> ( 2 * uiDepth ) );
 }
 
@@ -2402,6 +2283,7 @@
 {
   assert( sizeof( *m_skipFlag) == 1 );
-  memset( m_skipFlag + absPartIdx, skip, m_pcPic->getNumPartInCU() >> ( 2 * depth ) );
-}
+  memset( m_skipFlag + absPartIdx, skip, m_pcPic->getNumPartitionsInCtu() >> ( 2 * depth ) );
+}
+
 #if H_3D
 Void TComDataCU::setDISFlagSubParts( Bool bDIS, UInt absPartIdx, UInt depth )
@@ -2420,24 +2302,31 @@
 {
   assert( sizeof( *m_pePredMode) == 1 );
-  memset( m_pePredMode + uiAbsPartIdx, eMode, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
-}
-
-Void TComDataCU::setQPSubCUs( Int qp, TComDataCU* pcCU, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf )
-{
-  UInt currPartNumb = m_pcPic->getNumPartInCU() >> (depth << 1);
+  memset( m_pePredMode + uiAbsPartIdx, eMode, m_pcPic->getNumPartitionsInCtu() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setChromaQpAdjSubParts( UChar val, Int absPartIdx, Int depth )
+{
+  assert( sizeof(*m_ChromaQpAdj) == 1 );
+  memset( m_ChromaQpAdj + absPartIdx, val, m_pcPic->getNumPartitionsInCtu() >> ( 2 * depth ) );
+}
+
+Void TComDataCU::setQPSubCUs( Int qp, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf )
+{
+  UInt currPartNumb = m_pcPic->getNumPartitionsInCtu() >> (depth << 1);
   UInt currPartNumQ = currPartNumb >> 2;
+  const UInt numValidComp = m_pcPic->getNumberValidComponents();
 
   if(!foundNonZeroCbf)
   {
-    if(pcCU->getDepth(absPartIdx) > depth)
+    if(getDepth(absPartIdx) > depth)
     {
       for ( UInt partUnitIdx = 0; partUnitIdx < 4; partUnitIdx++ )
       {
-        pcCU->setQPSubCUs( qp, pcCU, absPartIdx+partUnitIdx*currPartNumQ, depth+1, foundNonZeroCbf );
+        setQPSubCUs( qp, absPartIdx+partUnitIdx*currPartNumQ, depth+1, foundNonZeroCbf );
       }
     }
     else
     {
-      if(pcCU->getCbf( absPartIdx, TEXT_LUMA ) || pcCU->getCbf( absPartIdx, TEXT_CHROMA_U ) || pcCU->getCbf( absPartIdx, TEXT_CHROMA_V ) )
+      if(getCbf( absPartIdx, COMPONENT_Y ) || (numValidComp>COMPONENT_Cb && getCbf( absPartIdx, COMPONENT_Cb )) || (numValidComp>COMPONENT_Cr && getCbf( absPartIdx, COMPONENT_Cr) ) )
       {
         foundNonZeroCbf = true;
@@ -2453,54 +2342,45 @@
 Void TComDataCU::setQPSubParts( Int qp, UInt uiAbsPartIdx, UInt uiDepth )
 {
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-  TComSlice * pcSlice = getPic()->getSlice(getPic()->getCurrSliceIdx());
-
-  for(UInt uiSCUIdx = uiAbsPartIdx; uiSCUIdx < uiAbsPartIdx+uiCurrPartNumb; uiSCUIdx++)
-  {
-    if( m_pcPic->getCU( getAddr() )->getSliceSegmentStartCU(uiSCUIdx+getZorderIdxInCU()) == pcSlice->getSliceSegmentCurStartCUAddr() )
-    {
-      m_phQP[uiSCUIdx] = qp;
-    }
-  }
-}
-
-Void TComDataCU::setLumaIntraDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiDepth )
-{
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-  
-  memset( m_puhLumaIntraDir + uiAbsPartIdx, uiDir, sizeof(UChar)*uiCurrPartNumb );
+  const UInt numPart = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  memset(m_phQP+uiAbsPartIdx, qp, numPart);
+}
+
+Void TComDataCU::setIntraDirSubParts( const ChannelType channelType, const UInt dir, const UInt absPartIdx, const UInt depth )
+{
+  UInt numPart = m_pcPic->getNumPartitionsInCtu() >> (depth << 1);
+  memset( m_puhIntraDir[channelType] + absPartIdx, dir,sizeof(UChar)*numPart );
 }
 
 template<typename T>
-Void TComDataCU::setSubPart( T uiParameter, T* puhBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx )
+Void TComDataCU::setSubPart( T uiParameter, T* puhBaseCtu, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx )
 {
   assert( sizeof(T) == 1 ); // Using memset() works only for types of size 1
-  
-  UInt uiCurrPartNumQ = (m_pcPic->getNumPartInCU() >> (2 * uiCUDepth)) >> 2;
+
+  UInt uiCurrPartNumQ = (m_pcPic->getNumPartitionsInCtu() >> (2 * uiCUDepth)) >> 2;
   switch ( m_pePartSize[ uiCUAddr ] )
   {
     case SIZE_2Nx2N:
-      memset( puhBaseLCU + uiCUAddr, uiParameter, 4 * uiCurrPartNumQ );
+      memset( puhBaseCtu + uiCUAddr, uiParameter, 4 * uiCurrPartNumQ );
       break;
     case SIZE_2NxN:
-      memset( puhBaseLCU + uiCUAddr, uiParameter, 2 * uiCurrPartNumQ );
+      memset( puhBaseCtu + uiCUAddr, uiParameter, 2 * uiCurrPartNumQ );
       break;
     case SIZE_Nx2N:
-      memset( puhBaseLCU + uiCUAddr, uiParameter, uiCurrPartNumQ );
-      memset( puhBaseLCU + uiCUAddr + 2 * uiCurrPartNumQ, uiParameter, uiCurrPartNumQ );
+      memset( puhBaseCtu + uiCUAddr, uiParameter, uiCurrPartNumQ );
+      memset( puhBaseCtu + uiCUAddr + 2 * uiCurrPartNumQ, uiParameter, uiCurrPartNumQ );
       break;
     case SIZE_NxN:
-      memset( puhBaseLCU + uiCUAddr, uiParameter, uiCurrPartNumQ ); 
+      memset( puhBaseCtu + uiCUAddr, uiParameter, uiCurrPartNumQ );
       break;
     case SIZE_2NxnU:
       if ( uiPUIdx == 0 )
       {
-        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
-        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );
+        memset( puhBaseCtu + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );
       }
       else if ( uiPUIdx == 1 )
       {
-        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
-        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, ((uiCurrPartNumQ >> 1) + (uiCurrPartNumQ << 1)) );                      
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );
+        memset( puhBaseCtu + uiCUAddr + uiCurrPartNumQ, uiParameter, ((uiCurrPartNumQ >> 1) + (uiCurrPartNumQ << 1)) );
       }
       else
@@ -2512,11 +2392,11 @@
       if ( uiPUIdx == 0 )
       {
-        memset( puhBaseLCU + uiCUAddr, uiParameter, ((uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1)) );                      
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseCtu + uiCUAddr, uiParameter, ((uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1)) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );
       }
       else if ( uiPUIdx == 1 )
       {
-        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
-        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );
+        memset( puhBaseCtu + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );
       }
       else
@@ -2528,15 +2408,15 @@
       if ( uiPUIdx == 0 )
       {
-        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
       }
       else if ( uiPUIdx == 1 )
       {
-        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) ); 
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) ); 
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );
       }
       else
@@ -2547,16 +2427,16 @@
     case SIZE_nRx2N:
       if ( uiPUIdx == 0 )
-      {      
-        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );                           
-        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );                           
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );
+        memset( puhBaseCtu + uiCUAddr + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
       }
       else if ( uiPUIdx == 1 )
       {
-        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );                           
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
-        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                          
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
       }
       else
@@ -2567,4 +2447,5 @@
     default:
       assert( 0 );
+      break;
   }
 }
@@ -2605,4 +2486,5 @@
 }
 #endif
+
 Void TComDataCU::setMergeFlagSubParts ( Bool bMergeFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
 {
@@ -2764,10 +2646,4 @@
 #endif
 #endif
-Void TComDataCU::setChromIntraDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiDepth )
-{
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-  
-  memset( m_puhChromaIntraDir + uiAbsPartIdx, uiDir, sizeof(UChar)*uiCurrPartNumb );
-}
 
 Void TComDataCU::setInterDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
@@ -2789,38 +2665,54 @@
 Void TComDataCU::setTrIdxSubParts( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth )
 {
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-  
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+
   memset( m_puhTrIdx + uiAbsPartIdx, uiTrIdx, sizeof(UChar)*uiCurrPartNumb );
 }
 
-Void TComDataCU::setTransformSkipSubParts( UInt useTransformSkipY, UInt useTransformSkipU, UInt useTransformSkipV, UInt uiAbsPartIdx, UInt uiDepth )
-{
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-
-  memset( m_puhTransformSkip[0] + uiAbsPartIdx, useTransformSkipY, sizeof( UChar ) * uiCurrPartNumb );
-  memset( m_puhTransformSkip[1] + uiAbsPartIdx, useTransformSkipU, sizeof( UChar ) * uiCurrPartNumb );
-  memset( m_puhTransformSkip[2] + uiAbsPartIdx, useTransformSkipV, sizeof( UChar ) * uiCurrPartNumb );
-}
-
-Void TComDataCU::setTransformSkipSubParts( UInt useTransformSkip, TextType eType, UInt uiAbsPartIdx, UInt uiDepth)
-{
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-
-  memset( m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]] + uiAbsPartIdx, useTransformSkip, sizeof( UChar ) * uiCurrPartNumb );
+Void TComDataCU::setTransformSkipSubParts( const UInt useTransformSkip[MAX_NUM_COMPONENT], UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    memset( m_puhTransformSkip[i] + uiAbsPartIdx, useTransformSkip[i], sizeof( UChar ) * uiCurrPartNumb );
+  }
+}
+
+Void TComDataCU::setTransformSkipSubParts( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+
+  memset( m_puhTransformSkip[compID] + uiAbsPartIdx, useTransformSkip, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+Void TComDataCU::setTransformSkipPartRange ( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_puhTransformSkip[compID] + uiAbsPartIdx), useTransformSkip, (sizeof(UChar) * uiCoveredPartIdxes));
+}
+
+Void TComDataCU::setCrossComponentPredictionAlphaPartRange( Char alphaValue, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_crossComponentPredictionAlpha[compID] + uiAbsPartIdx), alphaValue, (sizeof(Char) * uiCoveredPartIdxes));
+}
+
+Void TComDataCU::setExplicitRdpcmModePartRange ( UInt rdpcmMode, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_explicitRdpcmMode[compID] + uiAbsPartIdx), rdpcmMode, (sizeof(UChar) * uiCoveredPartIdxes));
 }
 
 Void TComDataCU::setSizeSubParts( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, UInt uiDepth )
 {
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
-  
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+
   memset( m_puhWidth  + uiAbsPartIdx, uiWidth,  sizeof(UChar)*uiCurrPartNumb );
   memset( m_puhHeight + uiAbsPartIdx, uiHeight, sizeof(UChar)*uiCurrPartNumb );
 }
 
-UChar TComDataCU::getNumPartitions()
+UChar TComDataCU::getNumPartitions(const UInt uiAbsPartIdx)
 {
   UChar iNumPart = 0;
-  
-  switch ( m_pePartSize[0] )
+
+  switch ( m_pePartSize[uiAbsPartIdx] )
   {
     case SIZE_2Nx2N:    iNumPart = 1; break;
@@ -2834,8 +2726,9 @@
     default:            assert (0);   break;
   }
-  
+
   return  iNumPart;
 }
 
+// This is for use by a leaf/sub CU object only, with no additional AbsPartIdx
 #if H_3D_IC
 Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx, Bool bLCU)
@@ -2882,4 +2775,5 @@
 }
 #else
+
 Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight )
 {
@@ -2932,5 +2826,5 @@
     return;
   }
-  
+
   TComCUMvField*  pcCUMvField = pcCU->getCUMvField( eRefPicList );
   rcMvField.setMvField( pcCUMvField->getMv( uiAbsPartIdx ), pcCUMvField->getRefIdx( uiAbsPartIdx ) );
@@ -2939,7 +2833,7 @@
 Void TComDataCU::deriveLeftRightTopIdxGeneral ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
 {
-  ruiPartIdxLT = m_uiAbsIdxInLCU + uiAbsPartIdx;
+  ruiPartIdxLT = m_absZIdxInCtu + uiAbsPartIdx;
   UInt uiPUWidth = 0;
-  
+
   switch ( m_pePartSize[uiAbsPartIdx] )
   {
@@ -2950,12 +2844,12 @@
     case SIZE_2NxnU:   uiPUWidth = m_puhWidth[uiAbsPartIdx]; break;
     case SIZE_2NxnD:   uiPUWidth = m_puhWidth[uiAbsPartIdx]; break;
-    case SIZE_nLx2N:   
+    case SIZE_nLx2N:
       if ( uiPartIdx == 0 )
       {
-        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2; 
+        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2;
       }
       else if ( uiPartIdx == 1 )
       {
-        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2); 
+        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2);
       }
       else
@@ -2964,12 +2858,12 @@
       }
       break;
-    case SIZE_nRx2N:   
+    case SIZE_nRx2N:
       if ( uiPartIdx == 0 )
       {
-        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2); 
+        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2);
       }
       else if ( uiPartIdx == 1 )
       {
-        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2; 
+        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2;
       }
       else
@@ -2982,5 +2876,5 @@
       break;
   }
-  
+
   ruiPartIdxRT = g_auiRasterToZscan [g_auiZscanToRaster[ ruiPartIdxLT ] + uiPUWidth / m_pcPic->getMinCUWidth() - 1 ];
 }
@@ -2995,12 +2889,12 @@
     case SIZE_Nx2N:  uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
     case SIZE_NxN:   uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 1;    break;
-    case SIZE_2NxnU: 
+    case SIZE_2NxnU:
       if ( uiPartIdx == 0 )
       {
-        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;    
+        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;
       }
       else if ( uiPartIdx == 1 )
       {
-        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);    
+        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);
       }
       else
@@ -3009,12 +2903,12 @@
       }
       break;
-    case SIZE_2NxnD: 
+    case SIZE_2NxnD:
       if ( uiPartIdx == 0 )
       {
-        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);    
+        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);
       }
       else if ( uiPartIdx == 1 )
       {
-        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;    
+        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;
       }
       else
@@ -3029,13 +2923,13 @@
       break;
   }
-  
-  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU + uiAbsPartIdx ] + ((uiPUHeight / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInWidth()];
+
+  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_absZIdxInCtu + uiAbsPartIdx ] + ((uiPUHeight / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInCtuWidth()];
 }
 
 Void TComDataCU::deriveLeftRightTopIdx ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
 {
-  ruiPartIdxLT = m_uiAbsIdxInLCU;
+  ruiPartIdxLT = m_absZIdxInCtu;
   ruiPartIdxRT = g_auiRasterToZscan [g_auiZscanToRaster[ ruiPartIdxLT ] + m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1 ];
-  
+
   switch ( m_pePartSize[0] )
   {
@@ -3070,11 +2964,11 @@
       break;
   }
-  
+
 }
 
 Void TComDataCU::deriveLeftBottomIdx( UInt  uiPartIdx,      UInt&      ruiPartIdxLB )
 {
-  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInWidth()];
-  
+  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_absZIdxInCtu ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInCtuWidth()];
+
   switch ( m_pePartSize[0] )
   {
@@ -3109,26 +3003,25 @@
 }
 
-/** Derives the partition index of neighbouring bottom right block
- * \param [in]  eCUMode
- * \param [in]  uiPartIdx 
- * \param [out] ruiPartIdxRB 
+/** Derive the partition index of neighbouring bottom right block
+ * \param [in]  uiPartIdx     current partition index
+ * \param [out] ruiPartIdxRB  partition index of neighbouring bottom right block
  */
-Void TComDataCU::deriveRightBottomIdx( UInt  uiPartIdx,      UInt&      ruiPartIdxRB )
-{
-  ruiPartIdxRB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInWidth() +  m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1];
+Void TComDataCU::deriveRightBottomIdx( UInt uiPartIdx, UInt &ruiPartIdxRB )
+{
+  ruiPartIdxRB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_absZIdxInCtu ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInCtuWidth() +  m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1];
 
   switch ( m_pePartSize[0] )
   {
-    case SIZE_2Nx2N:  
-      ruiPartIdxRB += m_uiNumPartition >> 1;    
+    case SIZE_2Nx2N:
+      ruiPartIdxRB += m_uiNumPartition >> 1;
       break;
-    case SIZE_2NxN:  
-      ruiPartIdxRB += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;   
+    case SIZE_2NxN:
+      ruiPartIdxRB += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
       break;
-    case SIZE_Nx2N:  
-      ruiPartIdxRB += ( uiPartIdx == 0 )? m_uiNumPartition >> 2 : (m_uiNumPartition >> 1);   
+    case SIZE_Nx2N:
+      ruiPartIdxRB += ( uiPartIdx == 0 )? m_uiNumPartition >> 2 : (m_uiNumPartition >> 1);
       break;
-    case SIZE_NxN:   
-      ruiPartIdxRB += ( m_uiNumPartition >> 2 ) * ( uiPartIdx - 1 );   
+    case SIZE_NxN:
+      ruiPartIdxRB += ( m_uiNumPartition >> 2 ) * ( uiPartIdx - 1 );
       break;
     case SIZE_2NxnU:
@@ -3150,26 +3043,6 @@
 }
 
-Void TComDataCU::deriveLeftRightTopIdxAdi ( UInt& ruiPartIdxLT, UInt& ruiPartIdxRT, UInt uiPartOffset, UInt uiPartDepth )
-{
-  UInt uiNumPartInWidth = (m_puhWidth[0]/m_pcPic->getMinCUWidth())>>uiPartDepth;
-  ruiPartIdxLT = m_uiAbsIdxInLCU + uiPartOffset;
-  ruiPartIdxRT = g_auiRasterToZscan[ g_auiZscanToRaster[ ruiPartIdxLT ] + uiNumPartInWidth - 1 ];
-}
-
-Void TComDataCU::deriveLeftBottomIdxAdi( UInt& ruiPartIdxLB, UInt uiPartOffset, UInt uiPartDepth )
-{
-  UInt uiAbsIdx;
-  UInt uiMinCuWidth, uiWidthInMinCus;
-  
-  uiMinCuWidth    = getPic()->getMinCUWidth();
-  uiWidthInMinCus = (getWidth(0)/uiMinCuWidth)>>uiPartDepth;
-  uiAbsIdx        = getZorderIdxInCU()+uiPartOffset+(m_uiNumPartition>>(uiPartDepth<<1))-1;
-  uiAbsIdx        = g_auiZscanToRaster[uiAbsIdx]-(uiWidthInMinCus-1);
-  ruiPartIdxLB    = g_auiRasterToZscan[uiAbsIdx];
-}
-
 Bool TComDataCU::hasEqualMotion( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx )
 {
-
   if ( getInterDir( uiAbsPartIdx ) != pcCandCU->getInterDir( uiCandAbsPartIdx ) )
   {
@@ -3181,5 +3054,5 @@
     if ( getInterDir( uiAbsPartIdx ) & ( 1 << uiRefListIdx ) )
     {
-      if ( getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiAbsPartIdx )     != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiCandAbsPartIdx ) || 
+      if ( getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiAbsPartIdx )     != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiCandAbsPartIdx ) ||
         getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiAbsPartIdx ) != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiCandAbsPartIdx ) )
       {
@@ -3320,5 +3193,4 @@
 
 #endif
-
 #if H_3D
 Void TComDataCU::buildMCL(TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
@@ -4647,17 +4519,8 @@
 #else
 
-/** Constructs a list of merging candidates
- * \param uiAbsPartIdx
- * \param uiPUIdx 
- * \param uiDepth
- * \param pcMvFieldNeighbours
- * \param puhInterDirNeighbours
- * \param numValidMergeCand
- */
-Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
-      , Int& numValidMergeCand, Int mrgCandIdx
-)
-{
-  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiAbsPartIdx;
+//! Construct a list of merging candidates
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx )
+{
+  UInt uiAbsPartAddr = m_absZIdxInCtu + uiAbsPartIdx;
   Bool abCandIsInter[ MRG_MAX_NUM_CANDS ];
   for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ++ui )
@@ -4677,5 +4540,5 @@
   PartSize cCurPS = getPartitionSize( uiAbsPartIdx );
   deriveLeftRightTopIdxGeneral( uiAbsPartIdx, uiPUIdx, uiPartIdxLT, uiPartIdxRT );
-  deriveLeftBottomIdxGeneral  ( uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
+  deriveLeftBottomIdxGeneral( uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
 
   //left
@@ -4683,8 +4546,10 @@
   TComDataCU* pcCULeft = 0;
   pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );
+
   Bool isAvailableA1 = pcCULeft &&
-  pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP) &&
-  !( uiPUIdx == 1 && (cCurPS == SIZE_Nx2N || cCurPS == SIZE_nLx2N || cCurPS == SIZE_nRx2N) ) &&
-  !pcCULeft->isIntra( uiLeftPartIdx ) ;
+                       pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP) &&
+                       !( uiPUIdx == 1 && (cCurPS == SIZE_Nx2N || cCurPS == SIZE_nLx2N || cCurPS == SIZE_nRx2N) ) &&
+                       pcCULeft->isInter( uiLeftPartIdx ) ;
+
   if ( isAvailableA1 )
   {
@@ -4704,19 +4569,20 @@
     iCount ++;
   }
-  
+
   // early termination
-  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  if (iCount == getSlice()->getMaxNumMergeCand())
   {
     return;
   }
-
   // above
   UInt uiAbovePartIdx = 0;
   TComDataCU* pcCUAbove = 0;
   pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
+
   Bool isAvailableB1 = pcCUAbove &&
-  pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP) &&
-  !( uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD) ) &&
-  !pcCUAbove->isIntra( uiAbovePartIdx );
+                       pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP) &&
+                       !( uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD) ) &&
+                       pcCUAbove->isInter( uiAbovePartIdx );
+
   if ( isAvailableB1 && (!isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) )
   {
@@ -4730,5 +4596,4 @@
       pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
     }
-
     if ( mrgCandIdx == iCount )
     {
@@ -4738,9 +4603,8 @@
   }
   // early termination
-  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  if (iCount == getSlice()->getMaxNumMergeCand())
   {
     return;
   }
-
 
   // above right
@@ -4748,7 +4612,9 @@
   TComDataCU* pcCUAboveRight = 0;
   pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
+
   Bool isAvailableB0 = pcCUAboveRight &&
-  pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP) &&
-  !pcCUAboveRight->isIntra( uiAboveRightPartIdx );
+                       pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP) &&
+                       pcCUAboveRight->isInter( uiAboveRightPartIdx );
+
   if ( isAvailableB0 && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) )
   {
@@ -4769,5 +4635,5 @@
   }
   // early termination
-  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  if (iCount == getSlice()->getMaxNumMergeCand())
   {
     return;
@@ -4778,7 +4644,9 @@
   TComDataCU* pcCULeftBottom = 0;
   pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
+
   Bool isAvailableA0 = pcCULeftBottom &&
-  pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP) &&
-  !pcCULeftBottom->isIntra( uiLeftBottomPartIdx ) ;
+                       pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP) &&
+                       pcCULeftBottom->isInter( uiLeftBottomPartIdx ) ;
+
   if ( isAvailableA0 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) )
   {
@@ -4792,5 +4660,4 @@
       pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
     }
-
     if ( mrgCandIdx == iCount )
     {
@@ -4800,10 +4667,10 @@
   }
   // early termination
-  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  if (iCount == getSlice()->getMaxNumMergeCand())
   {
     return;
   }
 
-  // above left 
+  // above left
   if( iCount < 4 )
   {
@@ -4811,7 +4678,9 @@
     TComDataCU* pcCUAboveLeft = 0;
     pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
+
     Bool isAvailableB2 = pcCUAboveLeft &&
-    pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP) &&
-    !pcCUAboveLeft->isIntra( uiAboveLeftPartIdx );
+                         pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP) &&
+                         pcCUAboveLeft->isInter( uiAboveLeftPartIdx );
+
     if ( isAvailableB2 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
         && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) ) )
@@ -4834,64 +4703,59 @@
   }
   // early termination
-  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  if (iCount == getSlice()->getMaxNumMergeCand())
   {
     return;
   }
 
-  if ( getSlice()->getEnableTMVPFlag())
+  if ( getSlice()->getEnableTMVPFlag() )
   {
     //>> MTK colocated-RightBottom
     UInt uiPartIdxRB;
 
-    deriveRightBottomIdx( uiPUIdx, uiPartIdxRB );  
+    deriveRightBottomIdx( uiPUIdx, uiPartIdxRB );
 
     UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
-    UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+    const UInt numPartInCtuWidth  = m_pcPic->getNumPartInCtuWidth();
+    const UInt numPartInCtuHeight = m_pcPic->getNumPartInCtuHeight();
 
     TComMv cColMv;
     Int iRefIdx;
-    Int uiLCUIdx = -1;
-
-    if      ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
-    {
-    }
-    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
-    {
-    }
-    else
-    {
-      if ( ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
-        ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
-      {
-        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + uiNumPartInCUWidth + 1 ];
-        uiLCUIdx = getAddr();
-      }
-      else if ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
-      {
-        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdxTmp + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
-      }
-      else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+    Int ctuRsAddr = -1;
+
+    if (   ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth () ) < m_pcSlice->getSPS()->getPicWidthInLumaSamples () )  // image boundary check
+        && ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+    {
+      if ( ( uiAbsPartIdxTmp % numPartInCtuWidth < numPartInCtuWidth - 1 ) &&           // is not at the last column of CTU
+        ( uiAbsPartIdxTmp / numPartInCtuWidth < numPartInCtuHeight - 1 ) )              // is not at the last row    of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + numPartInCtuWidth + 1 ];
+        ctuRsAddr = getCtuRsAddr();
+      }
+      else if ( uiAbsPartIdxTmp % numPartInCtuWidth < numPartInCtuWidth - 1 )           // is not at the last column of CTU But is last row of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdxTmp + numPartInCtuWidth + 1) % m_pcPic->getNumPartitionsInCtu() ];
+      }
+      else if ( uiAbsPartIdxTmp / numPartInCtuWidth < numPartInCtuHeight - 1 )          // is not at the last row of CTU But is last column of CTU
       {
         uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
-        uiLCUIdx = getAddr() + 1;
-      }
-      else //is the right bottom corner of LCU                       
+        ctuRsAddr = getCtuRsAddr() + 1;
+      }
+      else //is the right bottom corner of CTU
       {
         uiAbsPartAddr = 0;
       }
     }
-    
-    
+
     iRefIdx = 0;
+
     Bool bExistMV = false;
     UInt uiPartIdxCenter;
-    UInt uiCurLCUIdx = getAddr();
     Int dir = 0;
     UInt uiArrayAddr = iCount;
     xDeriveCenterIdx( uiPUIdx, uiPartIdxCenter );
-    bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_0, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx );
+    bExistMV = ctuRsAddr >= 0 && xGetColMVP( REF_PIC_LIST_0, ctuRsAddr, uiAbsPartAddr, cColMv, iRefIdx );
     if( bExistMV == false )
     {
-      bExistMV = xGetColMVP( REF_PIC_LIST_0, uiCurLCUIdx, uiPartIdxCenter, cColMv, iRefIdx );
+      bExistMV = xGetColMVP( REF_PIC_LIST_0, getCtuRsAddr(), uiPartIdxCenter,  cColMv, iRefIdx );
     }
     if( bExistMV )
@@ -4903,8 +4767,8 @@
     if ( getSlice()->isInterB() )
     {
-      bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_1, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx);
+      bExistMV = ctuRsAddr >= 0 && xGetColMVP( REF_PIC_LIST_1, ctuRsAddr, uiAbsPartAddr, cColMv, iRefIdx);
       if( bExistMV == false )
       {
-        bExistMV = xGetColMVP( REF_PIC_LIST_1, uiCurLCUIdx, uiPartIdxCenter, cColMv, iRefIdx );
+        bExistMV = xGetColMVP( REF_PIC_LIST_1, getCtuRsAddr(), uiPartIdxCenter, cColMv, iRefIdx );
       }
       if( bExistMV )
@@ -4914,9 +4778,10 @@
       }
     }
-    
+
     if (dir != 0)
     {
       puhInterDirNeighbours[uiArrayAddr] = dir;
       abCandIsInter[uiArrayAddr] = true;
+
       if ( mrgCandIdx == iCount )
       {
@@ -4927,19 +4792,23 @@
   }
   // early termination
-  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  if (iCount == getSlice()->getMaxNumMergeCand())
   {
     return;
   }
+
   UInt uiArrayAddr = iCount;
   UInt uiCutoff = uiArrayAddr;
-    
-  if ( getSlice()->isInterB())
-  {
-    UInt uiPriorityList0[12] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3};
-    UInt uiPriorityList1[12] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2};
+
+  if ( getSlice()->isInterB() )
+  {
+    static const UInt NUM_PRIORITY_LIST=12;
+    static const UInt uiPriorityList0[NUM_PRIORITY_LIST] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3};
+    static const UInt uiPriorityList1[NUM_PRIORITY_LIST] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2};
 
     for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!= getSlice()->getMaxNumMergeCand(); idx++)
     {
-      Int i = uiPriorityList0[idx]; Int j = uiPriorityList1[idx];
+      assert(idx<NUM_PRIORITY_LIST);
+      Int i = uiPriorityList0[idx];
+      Int j = uiPriorityList1[idx];
       if (abCandIsInter[i] && abCandIsInter[j]&& (puhInterDirNeighbours[i]&0x1)&&(puhInterDirNeighbours[j]&0x2))
       {
@@ -4965,9 +4834,11 @@
   }
   // early termination
-  if (uiArrayAddr == getSlice()->getMaxNumMergeCand()) 
+  if (uiArrayAddr == getSlice()->getMaxNumMergeCand())
   {
     return;
   }
+
   Int iNumRefIdx = (getSlice()->isInterB()) ? min(m_pcSlice->getNumRefIdx(REF_PIC_LIST_0), m_pcSlice->getNumRefIdx(REF_PIC_LIST_1)) : m_pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+
   Int r = 0;
   Int refcnt = 0;
@@ -4984,4 +4855,5 @@
     }
     uiArrayAddr++;
+
     if ( refcnt == iNumRefIdx - 1 )
     {
@@ -4994,5 +4866,4 @@
     }
   }
-
   numValidMergeCand = uiArrayAddr;
 }
@@ -5000,7 +4871,6 @@
 
 /** Check whether the current PU and a spatial neighboring PU are in a same ME region.
- * \param xN, xN   location of the upper-left corner pixel of a neighboring PU
+ * \param xN, yN   location of the upper-left corner pixel of a neighboring PU
  * \param xP, yP   location of the upper-left corner pixel of the current PU
- * \returns Bool
  */
 Bool TComDataCU::isDiffMER(Int xN, Int yN, Int xP, Int yP)
@@ -5018,9 +4888,9 @@
   return false;
 }
-/** calculate the location of upper-left corner pixel and size of the current PU.
- * \param partIdx  PU index within a CU
- * \param xP, yP   location of the upper-left corner pixel of the current PU
- * \param PSW, nPSH    size of the curren PU
- * \returns Void
+
+/** Calculate the location of upper-left corner pixel and size of the current PU.
+ * \param partIdx       PU index within a CU
+ * \param xP, yP        location of the upper-left corner pixel of the current PU
+ * \param nPSW, nPSH    size of the current PU
  */
 Void TComDataCU::getPartPosition( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH)
@@ -5032,18 +4902,18 @@
   {
   case SIZE_2NxN:
-    nPSW = getWidth(0);      
-    nPSH = getHeight(0) >> 1; 
+    nPSW = getWidth(0);
+    nPSH = getHeight(0) >> 1;
     xP   = col;
     yP   = (partIdx ==0)? row: row + nPSH;
     break;
   case SIZE_Nx2N:
-    nPSW = getWidth(0) >> 1; 
-    nPSH = getHeight(0);      
+    nPSW = getWidth(0) >> 1;
+    nPSH = getHeight(0);
     xP   = (partIdx ==0)? col: col + nPSW;
     yP   = row;
     break;
   case SIZE_NxN:
-    nPSW = getWidth(0) >> 1; 
-    nPSH = getHeight(0) >> 1; 
+    nPSW = getWidth(0) >> 1;
+    nPSH = getHeight(0) >> 1;
     xP   = col + (partIdx&0x1)*nPSW;
     yP   = row + (partIdx>>1)*nPSH;
@@ -5076,6 +4946,6 @@
   default:
     assert ( m_pePartSize[0] == SIZE_2Nx2N );
-    nPSW = getWidth(0);      
-    nPSH = getHeight(0);      
+    nPSW = getWidth(0);
+    nPSH = getHeight(0);
     xP   = col ;
     yP   = row ;
@@ -5087,5 +4957,5 @@
 /** Constructs a list of candidates for AMVP
  * \param uiPartIdx
- * \param uiPartAddr 
+ * \param uiPartAddr
  * \param eRefPicList
  * \param iRefIdx
@@ -5097,48 +4967,50 @@
   Bool bAddedSmvp = false;
 
-  pInfo->iN = 0;  
+  pInfo->iN = 0;
   if (iRefIdx < 0)
   {
     return;
   }
-  
+
   //-- Get Spatial MV
   UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
-  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  const UInt numPartInCtuWidth  = m_pcPic->getNumPartInCtuWidth();
+  const UInt numPartInCtuHeight = m_pcPic->getNumPartInCtuHeight();
   Bool bAdded = false;
-  
+
   deriveLeftRightTopIdx( uiPartIdx, uiPartIdxLT, uiPartIdxRT );
   deriveLeftBottomIdx( uiPartIdx, uiPartIdxLB );
-  
+
   TComDataCU* tmpCU = NULL;
   UInt idx;
   tmpCU = getPUBelowLeft(idx, uiPartIdxLB);
-  bAddedSmvp = (tmpCU != NULL) && (tmpCU->getPredictionMode(idx) != MODE_INTRA);
+  bAddedSmvp = (tmpCU != NULL) && (tmpCU->isInter(idx));
 
   if (!bAddedSmvp)
   {
     tmpCU = getPULeft(idx, uiPartIdxLB);
-    bAddedSmvp = (tmpCU != NULL) && (tmpCU->getPredictionMode(idx) != MODE_INTRA);
+    bAddedSmvp = (tmpCU != NULL) && (tmpCU->isInter(idx));
   }
 
   // Left predictor search
   bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
-  if (!bAdded) 
+  if (!bAdded)
   {
     bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
   }
-  
+
   if(!bAdded)
   {
     bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
-    if (!bAdded) 
+    if (!bAdded)
     {
       xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
     }
   }
+
   // Above predictor search
   bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
 
-  if (!bAdded) 
+  if (!bAdded)
   {
     bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
@@ -5150,8 +5022,8 @@
   }
 
-  if (!bAddedSmvp)
+  if(!bAddedSmvp)
   {
     bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
-    if (!bAdded) 
+    if (!bAdded)
     {
       bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
@@ -5163,5 +5035,5 @@
     }
   }
-  
+
   if ( pInfo->iN == 2 )
   {
@@ -5178,59 +5050,53 @@
     TComMv cColMv;
     UInt uiPartIdxRB;
-    UInt uiAbsPartIdx;  
+    UInt uiAbsPartIdx;
     UInt uiAbsPartAddr;
 
     deriveRightBottomIdx( uiPartIdx, uiPartIdxRB );
-    uiAbsPartAddr = m_uiAbsIdxInLCU + uiPartAddr;
+    uiAbsPartAddr = m_absZIdxInCtu + uiPartAddr;
 
     //----  co-located RightBottom Temporal Predictor (H) ---//
     uiAbsPartIdx = g_auiZscanToRaster[uiPartIdxRB];
-    Int uiLCUIdx = -1;
-    if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
-    {
-    }
-    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
-    {
-    }
-    else
-    {
-      if ( ( uiAbsPartIdx % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
-        ( uiAbsPartIdx / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
-      {
-        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + uiNumPartInCUWidth + 1 ];
-        uiLCUIdx = getAddr();
-      }
-      else if ( uiAbsPartIdx % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
-      {
-        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdx + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
-      }
-      else if ( uiAbsPartIdx / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+    Int ctuRsAddr = -1;
+    if (  ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth () ) < m_pcSlice->getSPS()->getPicWidthInLumaSamples () )  // image boundary check
+       && ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+    {
+      if ( ( uiAbsPartIdx % numPartInCtuWidth < numPartInCtuWidth - 1 ) &&  // is not at the last column of CTU
+           ( uiAbsPartIdx / numPartInCtuWidth < numPartInCtuHeight - 1 ) )  // is not at the last row    of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + numPartInCtuWidth + 1 ];
+        ctuRsAddr = getCtuRsAddr();
+      }
+      else if ( uiAbsPartIdx % numPartInCtuWidth < numPartInCtuWidth - 1 )  // is not at the last column of CTU But is last row of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdx + numPartInCtuWidth + 1) % m_pcPic->getNumPartitionsInCtu() ];
+      }
+      else if ( uiAbsPartIdx / numPartInCtuWidth < numPartInCtuHeight - 1 ) // is not at the last row of CTU But is last column of CTU
       {
         uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + 1 ];
-        uiLCUIdx = getAddr() + 1;
-      }
-      else //is the right bottom corner of LCU                       
+        ctuRsAddr = getCtuRsAddr() + 1;
+      }
+      else //is the right bottom corner of CTU
       {
         uiAbsPartAddr = 0;
       }
     }
-    if ( uiLCUIdx >= 0 && xGetColMVP( eRefPicList, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx_Col 
+    if ( ctuRsAddr >= 0 && xGetColMVP( eRefPicList, ctuRsAddr, uiAbsPartAddr, cColMv, iRefIdx_Col
 #if H_3D_TMVP
          , 0
 #endif
-    ) )
+ ) )
     {
       pInfo->m_acMvCand[pInfo->iN++] = cColMv;
     }
-    else 
+    else
     {
       UInt uiPartIdxCenter;
-      UInt uiCurLCUIdx = getAddr();
       xDeriveCenterIdx( uiPartIdx, uiPartIdxCenter );
-      if (xGetColMVP( eRefPicList, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx_Col 
+      if (xGetColMVP( eRefPicList, getCtuRsAddr(), uiPartIdxCenter,  cColMv, iRefIdx_Col 
 #if H_3D_TMVP
          , 0
 #endif
-      ))
+))
       {
         pInfo->m_acMvCand[pInfo->iN++] = cColMv;
@@ -5244,11 +5110,13 @@
     pInfo->iN = AMVP_MAX_NUM_CANDS;
   }
+
   while (pInfo->iN < AMVP_MAX_NUM_CANDS)
   {
-      pInfo->m_acMvCand[pInfo->iN].set(0,0);
-      pInfo->iN++;
+    pInfo->m_acMvCand[pInfo->iN].set(0,0);
+    pInfo->iN++;
   }
   return ;
 }
+
 
 Bool TComDataCU::isBipredRestriction(UInt puIdx)
@@ -5257,5 +5125,5 @@
   Int height = 0;
   UInt partAddr;
-  
+
 #if H_3D_DBBP
   if( getDBBPFlag(0) )
@@ -5273,6 +5141,8 @@
 }
 
+
 Void TComDataCU::clipMv    (TComMv&  rcMv)
 {
+  const TComSPS &sps=*(m_pcSlice->getSPS());
   Int  iMvShift = 2;
 #if H_3D_IC
@@ -5280,16 +5150,17 @@
     iMvShift = 0;
 #endif
+
   Int iOffset = 8;
-  Int iHorMax = ( m_pcSlice->getSPS()->getPicWidthInLumaSamples() + iOffset - m_uiCUPelX - 1 ) << iMvShift;
-  Int iHorMin = (       -(Int)g_uiMaxCUWidth - iOffset - (Int)m_uiCUPelX + 1 ) << iMvShift;
-  
-  Int iVerMax = ( m_pcSlice->getSPS()->getPicHeightInLumaSamples() + iOffset - m_uiCUPelY - 1 ) << iMvShift;
-  Int iVerMin = (       -(Int)g_uiMaxCUHeight - iOffset - (Int)m_uiCUPelY + 1 ) << iMvShift;
-  
+  Int iHorMax = ( sps.getPicWidthInLumaSamples() + iOffset - (Int)m_uiCUPelX - 1 ) << iMvShift;
+  Int iHorMin = (      -(Int)sps.getMaxCUWidth() - iOffset - (Int)m_uiCUPelX + 1 ) << iMvShift;
+
+  Int iVerMax = ( sps.getPicHeightInLumaSamples() + iOffset - (Int)m_uiCUPelY - 1 ) << iMvShift;
+  Int iVerMin = (      -(Int)sps.getMaxCUHeight() - iOffset - (Int)m_uiCUPelY + 1 ) << iMvShift;
+
   rcMv.setHor( min (iHorMax, max (iHorMin, rcMv.getHor())) );
   rcMv.setVer( min (iVerMax, max (iVerMin, rcMv.getVer())) );
 }
 
-#if H_MV
+#if NH_MV
 Void TComDataCU::checkMvVertRest (TComMv&  rcMv,  RefPicList eRefPicList, int iRefIdx )
 {
@@ -5310,5 +5181,5 @@
 {
   UInt uiShift = ( m_pePartSize[uiAbsPartIdx]==SIZE_NxN ? 1 : 0 );
-  
+
   UChar uiWidth = m_puhWidth[uiAbsPartIdx]>>uiShift;
   UInt  uiCnt = 0;
@@ -5322,7 +5193,7 @@
 }
 
-Void TComDataCU::clearCbf( UInt uiIdx, TextType eType, UInt uiNumParts )
-{
-  ::memset( &m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx], 0, sizeof(UChar)*uiNumParts);
+Void TComDataCU::clearCbf( UInt uiIdx, ComponentID compID, UInt uiNumParts )
+{
+  memset( &m_puhCbf[compID][uiIdx], 0, sizeof(UChar)*uiNumParts);
 }
 
@@ -5335,12 +5206,12 @@
 Void TComDataCU::setIPCMFlagSubParts  (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth)
 {
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
 
   memset(m_pbIPCMFlag + uiAbsPartIdx, bIpcmFlag, sizeof(Bool)*uiCurrPartNumb );
 }
 
-/** Test whether the current block is skipped
- * \param uiPartIdx Block index
- * \returns Flag indicating whether the block is skipped
+/** Test whether the block at uiPartIdx is skipped.
+ * \param uiPartIdx Partition index
+ * \returns true if the current the block is skipped
  */
 Bool TComDataCU::isSkipped( UInt uiPartIdx )
@@ -5377,5 +5248,5 @@
     case MD_ABOVE:
     {
-      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx );
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx);
       break;
     }
@@ -5405,9 +5276,9 @@
     return false;
   }
-  
+
   if ( pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) >= 0 && m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC() == pcTmpCU->getSlice()->getRefPOC( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ))
   {
     TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
-    
+
     pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
     return true;
@@ -5442,7 +5313,7 @@
 }
 
-/** 
+/**
  * \param pInfo
- * \param eRefPicList 
+ * \param eRefPicList
  * \param iRefIdx
  * \param uiPartUnitIdx
@@ -5487,9 +5358,9 @@
   }
 
-  if ( pcTmpCU == NULL ) 
+  if ( pcTmpCU == NULL )
   {
     return false;
   }
-  
+
   RefPicList eRefPicList2nd = REF_PIC_LIST_0;
   if(       eRefPicList == REF_PIC_LIST_0 )
@@ -5506,7 +5377,7 @@
   Int iNeibPOC = iCurrPOC;
   Int iNeibRefPOC;
-
   Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getIsLongTerm();
   Bool bIsNeibRefLongTerm = false;
+
   //---------------  V1 (END) ------------------//
   if( pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) >= 0)
@@ -5517,14 +5388,7 @@
 
     bIsNeibRefLongTerm = pcTmpCU->getSlice()->getRefPic( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) )->getIsLongTerm();
-    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm ) 
-    {
-    if ( bIsCurrRefLongTerm || bIsNeibRefLongTerm )
-    {
-      rcMv = cMvPred;
-    }
-    else
-    {
-      Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
-      if ( iScale == 4096 )
+    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm )
+    {
+      if ( bIsCurrRefLongTerm || bIsNeibRefLongTerm )
       {
         rcMv = cMvPred;
@@ -5532,9 +5396,17 @@
       else
       {
-        rcMv = cMvPred.scaleMv( iScale );
-      }
-    }
-    pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
-    return true;
+        Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+        if ( iScale == 4096 )
+        {
+          rcMv = cMvPred;
+        }
+        else
+        {
+          rcMv = cMvPred.scaleMv( iScale );
+        }
+      }
+
+      pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
+      return true;
     }
   }
@@ -5547,14 +5419,7 @@
 
     bIsNeibRefLongTerm = pcTmpCU->getSlice()->getRefPic( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) )->getIsLongTerm();
-    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm ) 
-    {
-    if ( bIsCurrRefLongTerm || bIsNeibRefLongTerm )
-    {
-      rcMv = cMvPred;
-    }
-    else
-    {
-      Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
-      if ( iScale == 4096 )
+    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm )
+    {
+      if ( bIsCurrRefLongTerm || bIsNeibRefLongTerm )
       {
         rcMv = cMvPred;
@@ -5562,9 +5427,17 @@
       else
       {
-        rcMv = cMvPred.scaleMv( iScale );
-      }
-    }
-    pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
-    return true;
+        Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+        if ( iScale == 4096 )
+        {
+          rcMv = cMvPred;
+        }
+        else
+        {
+          rcMv = cMvPred.scaleMv( iScale );
+        }
+      }
+
+      pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
+      return true;
     }
   }
@@ -5573,16 +5446,9 @@
 }
 
-/** 
- * \param eRefPicList
- * \param uiCUAddr 
- * \param uiPartUnitIdx
- * \param riRefIdx
- * \returns Bool
- */
-Bool TComDataCU::xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx 
+Bool TComDataCU::xGetColMVP( RefPicList eRefPicList, Int ctuRsAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx 
 #if H_3D_TMVP
   , Bool bMRG
 #endif
-  )
+)
 {
   UInt uiAbsPartAddr = uiPartUnitIdx;
@@ -5594,24 +5460,25 @@
   // use coldir.
   TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
-  TComDataCU *pColCU = pColPic->getCU( uiCUAddr );
-  if(pColCU->getPic()==0||pColCU->getPartitionSize(uiPartUnitIdx)==SIZE_NONE)
+  TComDataCU *pColCtu = pColPic->getCtu( ctuRsAddr );
+  if(pColCtu->getPic()==0||pColCtu->getPartitionSize(uiPartUnitIdx)==NUMBER_OF_PART_SIZES)
   {
     return false;
   }
-  iCurrPOC = m_pcSlice->getPOC();    
-  iColPOC = pColCU->getSlice()->getPOC();  
-
-  if (pColCU->isIntra(uiAbsPartAddr))
+  iCurrPOC = m_pcSlice->getPOC();
+  iColPOC = pColCtu->getSlice()->getPOC();
+
+  if (!pColCtu->isInter(uiAbsPartAddr))
   {
     return false;
   }
+
   eColRefPicList = getSlice()->getCheckLDC() ? eRefPicList : RefPicList(getSlice()->getColFromL0Flag());
 
-  Int iColRefIdx = pColCU->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+  Int iColRefIdx = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
 
   if (iColRefIdx < 0 )
   {
     eColRefPicList = RefPicList(1 - eColRefPicList);
-    iColRefIdx = pColCU->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+    iColRefIdx = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
 
     if (iColRefIdx < 0 )
@@ -5622,12 +5489,13 @@
 
   // Scale the vector.
-  iColRefPOC = pColCU->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
-  cColMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+  iColRefPOC = pColCtu->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
+  cColMv = pColCtu->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
 
   iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+
   Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
-  Bool bIsColRefLongTerm = pColCU->getSlice()->getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);
-
-  if ( bIsCurrRefLongTerm != bIsColRefLongTerm ) 
+  Bool bIsColRefLongTerm = pColCtu->getSlice()->getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);
+
+  if ( bIsCurrRefLongTerm != bIsColRefLongTerm )
   {
 #if H_3D_TMVP
@@ -5643,5 +5511,5 @@
     {
 #endif
-      return false;
+    return false;
 #if H_3D_TMVP
     }
@@ -5668,5 +5536,5 @@
     {
 #endif
-       rcMv = cColMv;
+    rcMv = cColMv;
 #if H_3D_TMVP
     }
@@ -5685,28 +5553,7 @@
     }
   }
+
   return true;
 }
-
-UInt TComDataCU::xGetMvdBits(TComMv cMvd)
-{
-  return ( xGetComponentBits(cMvd.getHor()) + xGetComponentBits(cMvd.getVer()) );
-}
-
-UInt TComDataCU::xGetComponentBits(Int iVal)
-{
-  UInt uiLength = 1;
-  UInt uiTemp   = ( iVal <= 0) ? (-iVal<<1)+1: (iVal<<1);
-  
-  assert ( uiTemp );
-  
-  while ( 1 != uiTemp )
-  {
-    uiTemp >>= 1;
-    uiLength += 2;
-  }
-  
-  return uiLength;
-}
-
 
 Int TComDataCU::xGetDistScaleFactor(Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC)
@@ -5714,5 +5561,5 @@
   Int iDiffPocD = iColPOC - iColRefPOC;
   Int iDiffPocB = iCurrPOC - iCurrRefPOC;
-  
+
   if( iDiffPocD == iDiffPocB )
   {
@@ -5729,10 +5576,4 @@
 }
 
-/** 
- * \param eCUMode
- * \param uiPartIdx 
- * \param ruiPartIdxCenter
- * \returns Void
- */
 Void TComDataCU::xDeriveCenterIdx( UInt uiPartIdx, UInt& ruiPartIdxCenter )
 {
@@ -5741,95 +5582,97 @@
   Int  iPartHeight;
   getPartIndexAndSize( uiPartIdx, uiPartAddr, iPartWidth, iPartHeight);
-  
-  ruiPartIdxCenter = m_uiAbsIdxInLCU+uiPartAddr; // partition origin.
+
+  ruiPartIdxCenter = m_absZIdxInCtu+uiPartAddr; // partition origin.
   ruiPartIdxCenter = g_auiRasterToZscan[ g_auiZscanToRaster[ ruiPartIdxCenter ]
-                                        + ( iPartHeight/m_pcPic->getMinCUHeight()  )/2*m_pcPic->getNumPartInWidth()
+                                        + ( iPartHeight/m_pcPic->getMinCUHeight()  )/2*m_pcPic->getNumPartInCtuWidth()
                                         + ( iPartWidth/m_pcPic->getMinCUWidth()  )/2];
 }
-#if H_3D
+
+#if NH_3D
 Void TComDataCU::compressMV(Int scale)
+{
+   Int scaleFactor = (4 / scale ) * AMVP_DECIMATION_FACTOR / m_unitSize;
 #else
 Void TComDataCU::compressMV()
-#endif
-{
-#if H_3D
-  Int scaleFactor = (4 / scale ) * AMVP_DECIMATION_FACTOR / m_unitSize;
-#else
+{
   Int scaleFactor = 4 * AMVP_DECIMATION_FACTOR / m_unitSize;
 #endif
   if (scaleFactor > 0)
   {
-    m_acCUMvField[0].compress(m_pePredMode, scaleFactor);
-    m_acCUMvField[1].compress(m_pePredMode, scaleFactor);    
-  }
-}
-
-UInt TComDataCU::getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra)
-{
-  UInt uiCTXIdx;
-  UInt uiScanIdx;
-  UInt uiDirMode;
-
-  if ( !bIsIntra ) 
-  {
-    uiScanIdx = SCAN_DIAG;
-    return uiScanIdx;
-  }
-
-  switch(uiWidth)
-  {
-    case  2: uiCTXIdx = 6; break;
-    case  4: uiCTXIdx = 5; break;
-    case  8: uiCTXIdx = 4; break;
-    case 16: uiCTXIdx = 3; break;
-    case 32: uiCTXIdx = 2; break;
-    case 64: uiCTXIdx = 1; break;
-    default: uiCTXIdx = 0; break;
-  }
-
-  if ( bIsLuma )
-  {
-    uiDirMode = getLumaIntraDir(uiAbsPartIdx);
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acCUMvField[i].compress(m_pePredMode, scaleFactor);
+    }
+  }
+}
+
+UInt TComDataCU::getCoefScanIdx(const UInt uiAbsPartIdx, const UInt uiWidth, const UInt uiHeight, const ComponentID compID) const
+{
+  //------------------------------------------------
+
+  //this mechanism is available for intra only
+
+  if (!isIntra(uiAbsPartIdx))
+  {
+    return SCAN_DIAG;
+  }
+
+  //------------------------------------------------
+
+  //check that MDCS can be used for this TU
+
+  const ChromaFormat format = getPic()->getChromaFormat();
+
+  const UInt maximumWidth  = MDCS_MAXIMUM_WIDTH  >> getComponentScaleX(compID, format);
+  const UInt maximumHeight = MDCS_MAXIMUM_HEIGHT >> getComponentScaleY(compID, format);
+
+  if ((uiWidth > maximumWidth) || (uiHeight > maximumHeight))
+  {
+    return SCAN_DIAG;
+  }
+
+  //------------------------------------------------
+
+  //otherwise, select the appropriate mode
+
+  UInt uiDirMode  = getIntraDir(toChannelType(compID), uiAbsPartIdx);
+
 #if H_3D_DIM
     mapDepthModeToIntraDir( uiDirMode );
 #endif
-    uiScanIdx = SCAN_DIAG;
-    if (uiCTXIdx >3 && uiCTXIdx < 6) //if multiple scans supported for transform size
-    {
-      uiScanIdx = abs((Int) uiDirMode - VER_IDX) < 5 ? SCAN_HOR : (abs((Int)uiDirMode - HOR_IDX) < 5 ? SCAN_VER : SCAN_DIAG);
-    }
-  }
-  else
-  {
-    uiDirMode = getChromaIntraDir(uiAbsPartIdx);
-    if( uiDirMode == DM_CHROMA_IDX )
-    {
-      // get number of partitions in current CU
-      UInt depth = getDepth(uiAbsPartIdx);
-      UInt numParts = getPic()->getNumPartInCU() >> (2 * depth);
-      
-      // get luma mode from upper-left corner of current CU
-      uiDirMode = getLumaIntraDir((uiAbsPartIdx/numParts)*numParts);
+
+  if (uiDirMode==DM_CHROMA_IDX)
+  {
+    const TComSPS *sps=getSlice()->getSPS();
+    const UInt partsPerMinCU = 1<<(2*(sps->getMaxTotalCUDepth() - sps->getLog2DiffMaxMinCodingBlockSize()));
+    uiDirMode = getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, getPic()->getChromaFormat(), partsPerMinCU));
 #if H_3D_DIM
       mapDepthModeToIntraDir( uiDirMode );
 #endif
-    }
-    uiScanIdx = SCAN_DIAG;
-    if (uiCTXIdx >4 && uiCTXIdx < 7) //if multiple scans supported for transform size
-    {
-      uiScanIdx = abs((Int) uiDirMode - VER_IDX) < 5 ? SCAN_HOR : (abs((Int)uiDirMode - HOR_IDX) < 5 ? SCAN_VER : SCAN_DIAG);
-    }
-  }
-
-  return uiScanIdx;
-}
-
-UInt TComDataCU::getSCUAddr()
-{ 
-  return getPic()->getPicSym()->getInverseCUOrderMap(m_uiCUAddr)*(1<<(m_pcSlice->getSPS()->getMaxCUDepth()<<1))+m_uiAbsIdxInLCU; 
-}
-
-#if H_3D
-Void TComDataCU::getPosInPic( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY )
+  }
+
+  if (isChroma(compID) && (format == CHROMA_422))
+  {
+    uiDirMode = g_chroma422IntraAngleMappingTable[uiDirMode];
+  }
+
+  //------------------
+
+  if      (abs((Int)uiDirMode - VER_IDX) <= MDCS_ANGLE_LIMIT)
+  {
+    return SCAN_HOR;
+  }
+  else if (abs((Int)uiDirMode - HOR_IDX) <= MDCS_ANGLE_LIMIT)
+  {
+    return SCAN_VER;
+  }
+  else
+  {
+    return SCAN_DIAG;
+  }
+}
+
+#if NH_3D_VSO
+Void TComDataCU::getPosInPic( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY ) const
 {
   riPosX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIndex]] + getCUPelX();
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComDataCU.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComDataCU.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,8 +37,9 @@
 */
 
-#ifndef _TCOMDATACU_
-#define _TCOMDATACU_
-
-#include <assert.h>
+#ifndef __TCOMDATACU__
+#define __TCOMDATACU__
+
+#include <algorithm>
+#include <vector>
 
 // Include files
@@ -52,11 +53,15 @@
 #include "TComYuv.h"
 #endif
-
+#if H_3D
 #include <algorithm>
 #include <vector>
+#endif
 
 //! \ingroup TLibCommon
 //! \{
 
+class TComTU; // forward declaration
+
+static const UInt NUM_MOST_PROBABLE_MODES=3;
 
 #if H_3D_DBBP
@@ -75,4 +80,5 @@
 #endif
 
+
 // ====================================================================================================================
 // Class definition
@@ -83,19 +89,18 @@
 {
 private:
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // class pointers
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   TComPic*      m_pcPic;              ///< picture class pointer
   TComSlice*    m_pcSlice;            ///< slice header pointer
-  TComPattern*  m_pcPattern;          ///< neighbour access class pointer
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // CU description
   // -------------------------------------------------------------------------------------------------------------------
-  
-  UInt          m_uiCUAddr;           ///< CU address in a slice
-  UInt          m_uiAbsIdxInLCU;      ///< absolute address in a CU. It's Z scan order
+
+  UInt          m_ctuRsAddr;          ///< CTU (also known as LCU) address in a slice (Raster-scan address, as opposed to tile-scan/encoding order).
+  UInt          m_absZIdxInCtu;       ///< absolute address in a CTU. It's Z scan order
   UInt          m_uiCUPelX;           ///< CU position in a pixel (X)
   UInt          m_uiCUPelY;           ///< CU position in a pixel (Y)
@@ -105,57 +110,51 @@
   UChar*        m_puhDepth;           ///< array of depths
   Int           m_unitSize;           ///< size of a "minimum partition"
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // CU data
   // -------------------------------------------------------------------------------------------------------------------
-  Bool*         m_skipFlag;           ///< array of skip flags
+
+  Bool*          m_skipFlag;           ///< array of skip flags
 #if H_3D
   Bool*         m_bDISFlag;         
   UInt*         m_uiDISType;
 #endif
-  Char*         m_pePartSize;         ///< array of partition sizes
-  Char*         m_pePredMode;         ///< array of prediction modes
-  Bool*         m_CUTransquantBypass;   ///< array of cu_transquant_bypass flags
-  Char*         m_phQP;               ///< array of QP values
-  UChar*        m_puhTrIdx;           ///< array of transform indices
-  UChar*        m_puhTransformSkip[3];///< array of transform skipping flags
-  UChar*        m_puhCbf[3];          ///< array of coded block flags (CBF)
-  TComCUMvField m_acCUMvField[2];     ///< array of motion vectors
-  TCoeff*       m_pcTrCoeffY;         ///< transformed coefficient buffer (Y)
-  TCoeff*       m_pcTrCoeffCb;        ///< transformed coefficient buffer (Cb)
-  TCoeff*       m_pcTrCoeffCr;        ///< transformed coefficient buffer (Cr)
+  Char*          m_pePartSize;         ///< array of partition sizes
+  Char*          m_pePredMode;         ///< array of prediction modes
+  Char*          m_crossComponentPredictionAlpha[MAX_NUM_COMPONENT]; ///< array of cross-component prediction alpha values
+  Bool*          m_CUTransquantBypass;   ///< array of cu_transquant_bypass flags
+  Char*          m_phQP;               ///< array of QP values
+  UChar*         m_ChromaQpAdj;        ///< array of chroma QP adjustments (indexed). when value = 0, cu_chroma_qp_offset_flag=0; when value>0, indicates cu_chroma_qp_offset_flag=1 and cu_chroma_qp_offset_idx=value-1
+  UInt           m_codedChromaQpAdj;
+  UChar*         m_puhTrIdx;           ///< array of transform indices
+  UChar*         m_puhTransformSkip[MAX_NUM_COMPONENT];///< array of transform skipping flags
+  UChar*         m_puhCbf[MAX_NUM_COMPONENT];          ///< array of coded block flags (CBF)
+  TComCUMvField  m_acCUMvField[NUM_REF_PIC_LIST_01];    ///< array of motion vectors.
+  TCoeff*        m_pcTrCoeff[MAX_NUM_COMPONENT];       ///< array of transform coefficient buffers (0->Y, 1->Cb, 2->Cr)
 #if ADAPTIVE_QP_SELECTION
-  Int*          m_pcArlCoeffY;        ///< ARL coefficient buffer (Y)
-  Int*          m_pcArlCoeffCb;       ///< ARL coefficient buffer (Cb)
-  Int*          m_pcArlCoeffCr;       ///< ARL coefficient buffer (Cr)
-  Bool          m_ArlCoeffIsAliasedAllocation; ///< ARL coefficient buffer is an alias of the global buffer and must not be free()'d
-
-  static Int*   m_pcGlbArlCoeffY;     ///< ARL coefficient buffer (Y)
-  static Int*   m_pcGlbArlCoeffCb;    ///< ARL coefficient buffer (Cb)
-  static Int*   m_pcGlbArlCoeffCr;    ///< ARL coefficient buffer (Cr)
-#endif
-  
-  Pel*          m_pcIPCMSampleY;      ///< PCM sample buffer (Y)
-  Pel*          m_pcIPCMSampleCb;     ///< PCM sample buffer (Cb)
-  Pel*          m_pcIPCMSampleCr;     ///< PCM sample buffer (Cr)
+  TCoeff*        m_pcArlCoeff[MAX_NUM_COMPONENT];  // ARL coefficient buffer (0->Y, 1->Cb, 2->Cr)
+  Bool           m_ArlCoeffIsAliasedAllocation;  ///< ARL coefficient buffer is an alias of the global buffer and must not be free()'d
+#endif
+
+  Pel*           m_pcIPCMSample[MAX_NUM_COMPONENT];    ///< PCM sample buffer (0->Y, 1->Cb, 2->Cr)
 
   // -------------------------------------------------------------------------------------------------------------------
   // neighbour access variables
   // -------------------------------------------------------------------------------------------------------------------
-  
-  TComDataCU*   m_pcCUAboveLeft;      ///< pointer of above-left CU
-  TComDataCU*   m_pcCUAboveRight;     ///< pointer of above-right CU
-  TComDataCU*   m_pcCUAbove;          ///< pointer of above CU
-  TComDataCU*   m_pcCULeft;           ///< pointer of left CU
-  TComDataCU*   m_apcCUColocated[2];  ///< pointer of temporally colocated CU's for both directions
+
+  TComDataCU*   m_pCtuAboveLeft;      ///< pointer of above-left CTU.
+  TComDataCU*   m_pCtuAboveRight;     ///< pointer of above-right CTU.
+  TComDataCU*   m_pCtuAbove;          ///< pointer of above CTU.
+  TComDataCU*   m_pCtuLeft;           ///< pointer of left CTU
+  TComDataCU*   m_apcCUColocated[NUM_REF_PIC_LIST_01];  ///< pointer of temporally colocated CU's for both directions
   TComMvField   m_cMvFieldA;          ///< motion vector of position A
   TComMvField   m_cMvFieldB;          ///< motion vector of position B
   TComMvField   m_cMvFieldC;          ///< motion vector of position C
   TComMv        m_cMvPred;            ///< motion vector predictor
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // coding tool information
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   Bool*         m_pbMergeFlag;        ///< array of merge flags
   UChar*        m_puhMergeIndex;      ///< array of merge candidate indices
@@ -163,9 +162,8 @@
   Bool          m_bIsMergeAMP;
 #endif
-  UChar*        m_puhLumaIntraDir;    ///< array of intra directions (luma)
-  UChar*        m_puhChromaIntraDir;  ///< array of intra directions (chroma)
+  UChar*        m_puhIntraDir[MAX_NUM_CHANNEL_TYPE]; // 0-> Luma, 1-> Chroma
   UChar*        m_puhInterDir;        ///< array of inter directions
-  Char*         m_apiMVPIdx[2];       ///< array of motion vector predictor candidates
-  Char*         m_apiMVPNum[2];       ///< array of number of possible motion vectors predictors
+  Char*         m_apiMVPIdx[NUM_REF_PIC_LIST_01];       ///< array of motion vector predictor candidates
+  Char*         m_apiMVPNum[NUM_REF_PIC_LIST_01];       ///< array of number of possible motion vectors predictors
   Bool*         m_pbIPCMFlag;         ///< array of intra_pcm flags
 #if H_3D_NBDV
@@ -206,19 +204,19 @@
   Bool          m_bAvailableFlagB2;    ///< B2 available flag
 #endif
+
+
   // -------------------------------------------------------------------------------------------------------------------
   // misc. variables
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   Bool          m_bDecSubCu;          ///< indicates decoder-mode
   Double        m_dTotalCost;         ///< sum of partition RD costs
-#if H_3D_VSO
+#if NH_3D_VSO
   Dist          m_uiTotalDistortion;  ///< sum of partition distortion
 #else
-  UInt          m_uiTotalDistortion;  ///< sum of partition distortion
+  Distortion    m_uiTotalDistortion;  ///< sum of partition distortion
 #endif
   UInt          m_uiTotalBits;        ///< sum of partition bits
-  UInt          m_uiTotalBins;       ///< sum of partition bins
-  UInt*         m_sliceStartCU;    ///< Start CU address of current slice
-  UInt*         m_sliceSegmentStartCU; ///< Start CU address of current slice
+  UInt          m_uiTotalBins;        ///< sum of partition bins
   Char          m_codedQP;
 #if H_3D
@@ -230,6 +228,8 @@
 #endif
 
+  UChar*        m_explicitRdpcmMode[MAX_NUM_COMPONENT]; ///< Stores the explicit RDPCM mode for all TUs belonging to this CU
+
 protected:
-  
+
   /// add possible motion vector predictor candidates
   Bool          xAddMVPCand           ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
@@ -243,14 +243,11 @@
 
   Void          deriveRightBottomIdx        ( UInt uiPartIdx, UInt& ruiPartIdxRB );
-  Bool          xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx 
+  Bool          xGetColMVP( RefPicList eRefPicList, Int ctuRsAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx
 #if H_3D_TMVP
   ,  Bool bMRG = true
 #endif
-  );
-  
-  /// compute required bits to encode MVD (used in AMVP)
-  UInt          xGetMvdBits           ( TComMv cMvd );
-  UInt          xGetComponentBits     ( Int iVal );
-  
+ );
+
+
   /// compute scaling factor from POC difference
 #if !H_3D_ARP
@@ -267,5 +264,5 @@
   TComDataCU();
   virtual ~TComDataCU();
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // create / destroy / initialize / copy
@@ -274,13 +271,13 @@
   Int           xGetDistScaleFactor   ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
 #endif 
-  Void          create                ( UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+  Void          create                ( ChromaFormat chromaFormatIDC, UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
 #if ADAPTIVE_QP_SELECTION
-    , Bool bGlobalRMARLBuffer = false
-#endif  
+    , TCoeff *pParentARLBuffer = 0
+#endif
     );
   Void          destroy               ();
-  
-  Void          initCU                ( TComPic* pcPic, UInt uiCUAddr );
-  Void          initEstData           ( UInt uiDepth, Int qp, Bool bTransquantBypass );
+
+  Void          initCtu               ( TComPic* pcPic, UInt ctuRsAddr );
+  Void          initEstData           ( const UInt uiDepth, const Int qp, const Bool bTransquantBypass );
   Void          initSubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp );
   Void          setOutsideCUPart      ( UInt uiAbsPartIdx, UInt uiDepth );
@@ -288,44 +285,42 @@
   Void          copyDVInfoFrom (TComDataCU* pcCU, UInt uiAbsPartIdx);
 #endif
-  Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
-  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList
+
+  Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx );
+  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList 
 #if H_3D_NBDV
   , Bool bNBDV = false
 #endif
-  );
+);
   Void          copyPartFrom          ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
-  
+
   Void          copyToPic             ( UChar uiDepth );
-  Void          copyToPic             ( UChar uiDepth, UInt uiPartIdx, UInt uiPartDepth );
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for CU description
   // -------------------------------------------------------------------------------------------------------------------
-  
-  TComPic*      getPic                ()                        { return m_pcPic;           }
-  TComSlice*    getSlice              ()                        { return m_pcSlice;         }
-#if H_3D_DISABLE_CHROMA
-  Void         setSlice              ( TComSlice* pcSlice)     { m_pcSlice = pcSlice;       }
-#endif
-  UInt&         getAddr               ()                        { return m_uiCUAddr;        }
-  UInt&         getZorderIdxInCU      ()                        { return m_uiAbsIdxInLCU; }
-  UInt          getSCUAddr            ();
-  UInt          getCUPelX             ()                        { return m_uiCUPelX;        }
-  UInt          getCUPelY             ()                        { return m_uiCUPelY;        }
-  TComPattern*  getPattern            ()                        { return m_pcPattern;       }
-  
+
+  TComPic*        getPic              ()                        { return m_pcPic;           }
+  const TComPic*  getPic              () const                  { return m_pcPic;           }
+  TComSlice*       getSlice           ()                        { return m_pcSlice;         }
+  const TComSlice* getSlice           () const                  { return m_pcSlice;         }
+  UInt&         getCtuRsAddr          ()                        { return m_ctuRsAddr;       }
+  UInt          getCtuRsAddr          () const                  { return m_ctuRsAddr;       }
+  UInt          getZorderIdxInCtu     () const                  { return m_absZIdxInCtu;    }
+  UInt          getCUPelX             () const                  { return m_uiCUPelX;        }
+  UInt          getCUPelY             () const                  { return m_uiCUPelY;        }
+
   UChar*        getDepth              ()                        { return m_puhDepth;        }
-  UChar         getDepth              ( UInt uiIdx )            { return m_puhDepth[uiIdx]; }
+  UChar         getDepth              ( UInt uiIdx ) const      { return m_puhDepth[uiIdx]; }
   Void          setDepth              ( UInt uiIdx, UChar  uh ) { m_puhDepth[uiIdx] = uh;   }
-  
+
   Void          setDepthSubParts      ( UInt uiDepth, UInt uiAbsPartIdx );
-#if H_3D
-  Void          getPosInPic           ( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY );
-#endif
-  
+#if NH_3D_VSO
+  Void          getPosInPic           ( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY ) const;
+#endif
+
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for CU data
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   Char*         getPartitionSize      ()                        { return m_pePartSize;        }
   PartSize      getPartitionSize      ( UInt uiIdx )            { return static_cast<PartSize>( m_pePartSize[uiIdx] ); }
@@ -333,13 +328,13 @@
   Void          setPartSizeSubParts   ( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth );
   Void          setCUTransquantBypassSubParts( Bool flag, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
 #if H_3D_DBBP
   Pel*          getVirtualDepthBlock(UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt& uiDepthStride);
 #endif
   
-  Bool*        getSkipFlag            ()                        { return m_skipFlag;          }
-  Bool         getSkipFlag            (UInt idx)                { return m_skipFlag[idx];     }
-  Void         setSkipFlag           ( UInt idx, Bool skip)     { m_skipFlag[idx] = skip;   }
-  Void         setSkipFlagSubParts   ( Bool skip, UInt absPartIdx, UInt depth );
+  Bool*         getSkipFlag            ()                        { return m_skipFlag;          }
+  Bool          getSkipFlag            (UInt idx)                { return m_skipFlag[idx];     }
+  Void          setSkipFlag           ( UInt idx, Bool skip)     { m_skipFlag[idx] = skip;   }
+  Void          setSkipFlagSubParts   ( Bool skip, UInt absPartIdx, UInt depth );
 #if H_3D
   Bool*        getDISFlag            ()                         { return m_bDISFlag;          }
@@ -355,9 +350,7 @@
   Char*         getPredictionMode     ()                        { return m_pePredMode;        }
   PredMode      getPredictionMode     ( UInt uiIdx )            { return static_cast<PredMode>( m_pePredMode[uiIdx] ); }
-  Bool*         getCUTransquantBypass ()                        { return m_CUTransquantBypass;        }
-  Bool          getCUTransquantBypass( UInt uiIdx )             { return m_CUTransquantBypass[uiIdx]; }
   Void          setPredictionMode     ( UInt uiIdx, PredMode uh){ m_pePredMode[uiIdx] = uh;   }
   Void          setPredModeSubParts   ( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
 #if H_3D_DBBP
   Bool*         getDBBPFlag           ()                        { return m_pbDBBPFlag;               }
@@ -367,70 +360,87 @@
   DbbpTmpData*  getDBBPTmpData        () { return &m_sDBBPTmpData; }
 #endif
-  
+
+  Char*         getCrossComponentPredictionAlpha( ComponentID compID )             { return m_crossComponentPredictionAlpha[compID];         }
+  Char          getCrossComponentPredictionAlpha( UInt uiIdx, ComponentID compID ) { return m_crossComponentPredictionAlpha[compID][uiIdx];  }
+
+  Bool*         getCUTransquantBypass ()                        { return m_CUTransquantBypass;        }
+  Bool          getCUTransquantBypass( UInt uiIdx )             { return m_CUTransquantBypass[uiIdx]; }
+
   UChar*        getWidth              ()                        { return m_puhWidth;          }
   UChar         getWidth              ( UInt uiIdx )            { return m_puhWidth[uiIdx];   }
   Void          setWidth              ( UInt uiIdx, UChar  uh ) { m_puhWidth[uiIdx] = uh;     }
-  
+
   UChar*        getHeight             ()                        { return m_puhHeight;         }
   UChar         getHeight             ( UInt uiIdx )            { return m_puhHeight[uiIdx];  }
   Void          setHeight             ( UInt uiIdx, UChar  uh ) { m_puhHeight[uiIdx] = uh;    }
-  
+
   Void          setSizeSubParts       ( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
   Char*         getQP                 ()                        { return m_phQP;              }
-  Char          getQP                 ( UInt uiIdx )            { return m_phQP[uiIdx];       }
+  Char          getQP                 ( UInt uiIdx ) const      { return m_phQP[uiIdx];       }
   Void          setQP                 ( UInt uiIdx, Char value ){ m_phQP[uiIdx] =  value;     }
   Void          setQPSubParts         ( Int qp,   UInt uiAbsPartIdx, UInt uiDepth );
   Int           getLastValidPartIdx   ( Int iAbsPartIdx );
   Char          getLastCodedQP        ( UInt uiAbsPartIdx );
-  Void          setQPSubCUs           ( Int qp, TComDataCU* pcCU, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf );
+  Void          setQPSubCUs           ( Int qp, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf );
   Void          setCodedQP            ( Char qp )               { m_codedQP = qp;             }
   Char          getCodedQP            ()                        { return m_codedQP;           }
 
-  Bool          isLosslessCoded(UInt absPartIdx);
-  
+  UChar*        getChromaQpAdj        ()                        { return m_ChromaQpAdj;       } ///< array of chroma QP adjustments (indexed). when value = 0, cu_chroma_qp_offset_flag=0; when value>0, indicates cu_chroma_qp_offset_flag=1 and cu_chroma_qp_offset_idx=value-1
+  UChar         getChromaQpAdj        (Int idx)           const { return m_ChromaQpAdj[idx];  } ///< When value = 0, cu_chroma_qp_offset_flag=0; when value>0, indicates cu_chroma_qp_offset_flag=1 and cu_chroma_qp_offset_idx=value-1
+  Void          setChromaQpAdj        (Int idx, UChar val)      { m_ChromaQpAdj[idx] = val;   } ///< When val = 0,   cu_chroma_qp_offset_flag=0; when val>0,   indicates cu_chroma_qp_offset_flag=1 and cu_chroma_qp_offset_idx=val-1
+  Void          setChromaQpAdjSubParts( UChar val, Int absPartIdx, Int depth );
+  Void          setCodedChromaQpAdj   ( Char qp )               { m_codedChromaQpAdj = qp;    }
+  Char          getCodedChromaQpAdj   ()                        { return m_codedChromaQpAdj;  }
+
+  Bool          isLosslessCoded       ( UInt absPartIdx );
+
   UChar*        getTransformIdx       ()                        { return m_puhTrIdx;          }
   UChar         getTransformIdx       ( UInt uiIdx )            { return m_puhTrIdx[uiIdx];   }
   Void          setTrIdxSubParts      ( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth );
 
-  UChar*        getTransformSkip      ( TextType eType)    { return m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]];}
-  UChar         getTransformSkip      ( UInt uiIdx,TextType eType)    { return m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]][uiIdx];}
-  Void          setTransformSkipSubParts  ( UInt useTransformSkip, TextType eType, UInt uiAbsPartIdx, UInt uiDepth); 
-  Void          setTransformSkipSubParts  ( UInt useTransformSkipY, UInt useTransformSkipU, UInt useTransformSkipV, UInt uiAbsPartIdx, UInt uiDepth );
-
-  UInt          getQuadtreeTULog2MinSizeInCU( UInt absPartIdx );
-  
+  UChar*        getTransformSkip      ( ComponentID compID )    { return m_puhTransformSkip[compID];}
+  UChar         getTransformSkip      ( UInt uiIdx, ComponentID compID)    { return m_puhTransformSkip[compID][uiIdx];}
+  Void          setTransformSkipSubParts  ( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth);
+  Void          setTransformSkipSubParts  ( const UInt useTransformSkip[MAX_NUM_COMPONENT], UInt uiAbsPartIdx, UInt uiDepth );
+
+  UChar*        getExplicitRdpcmMode      ( ComponentID component ) { return m_explicitRdpcmMode[component]; }
+  UChar         getExplicitRdpcmMode      ( ComponentID component, UInt partIdx ) {return m_explicitRdpcmMode[component][partIdx]; }
+  Void          setExplicitRdpcmModePartRange ( UInt rdpcmMode, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
+
+  Bool          isRDPCMEnabled         ( UInt uiAbsPartIdx )  { return getSlice()->getSPS()->getSpsRangeExtension().getRdpcmEnabledFlag(isIntra(uiAbsPartIdx) ? RDPCM_SIGNAL_IMPLICIT : RDPCM_SIGNAL_EXPLICIT); }
+
+  Void          setCrossComponentPredictionAlphaPartRange    ( Char alphaValue, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
+  Void          setTransformSkipPartRange                    ( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
+
+  UInt          getQuadtreeTULog2MinSizeInCU( UInt uiIdx );
+
   TComCUMvField* getCUMvField         ( RefPicList e )          { return  &m_acCUMvField[e];  }
-  
-  TCoeff*&      getCoeffY             ()                        { return m_pcTrCoeffY;        }
-  TCoeff*&      getCoeffCb            ()                        { return m_pcTrCoeffCb;       }
-  TCoeff*&      getCoeffCr            ()                        { return m_pcTrCoeffCr;       }
+
+  TCoeff*       getCoeff              (ComponentID component)   { return m_pcTrCoeff[component]; }
+
 #if ADAPTIVE_QP_SELECTION
-  Int*&         getArlCoeffY          ()                        { return m_pcArlCoeffY;       }
-  Int*&         getArlCoeffCb         ()                        { return m_pcArlCoeffCb;      }
-  Int*&         getArlCoeffCr         ()                        { return m_pcArlCoeffCr;      }
-#endif
-  
-  Pel*&         getPCMSampleY         ()                        { return m_pcIPCMSampleY;     }
-  Pel*&         getPCMSampleCb        ()                        { return m_pcIPCMSampleCb;    }
-  Pel*&         getPCMSampleCr        ()                        { return m_pcIPCMSampleCr;    }
-
-  UChar         getCbf    ( UInt uiIdx, TextType eType )                  { return m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx];  }
-  UChar*        getCbf    ( TextType eType )                              { return m_puhCbf[g_aucConvertTxtTypeToIdx[eType]];         }
-
-  UChar         getCbf    ( UInt uiIdx, TextType eType, UInt uiTrDepth )  { return ( ( getCbf( uiIdx, eType ) >> uiTrDepth ) & 0x1 ); }
-  Void          setCbf    ( UInt uiIdx, TextType eType, UChar uh )        { m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx] = uh;    }
-
-  Void          clearCbf  ( UInt uiIdx, TextType eType, UInt uiNumParts );
-  UChar         getQtRootCbf          ( UInt uiIdx )                      { return getCbf( uiIdx, TEXT_LUMA, 0 ) || getCbf( uiIdx, TEXT_CHROMA_U, 0 ) || getCbf( uiIdx, TEXT_CHROMA_V, 0 ); }
-  
-  Void          setCbfSubParts        ( UInt uiCbfY, UInt uiCbfU, UInt uiCbfV, UInt uiAbsPartIdx, UInt uiDepth          );
-  Void          setCbfSubParts        ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiDepth                    );
-  Void          setCbfSubParts        ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth    );
-  
+  TCoeff*       getArlCoeff           ( ComponentID component ) { return m_pcArlCoeff[component]; }
+#endif
+  Pel*          getPCMSample          ( ComponentID component ) { return m_pcIPCMSample[component]; }
+
+  UChar         getCbf    ( UInt uiIdx, ComponentID eType )                  { return m_puhCbf[eType][uiIdx];  }
+  UChar*        getCbf    ( ComponentID eType )                              { return m_puhCbf[eType];         }
+  UChar         getCbf    ( UInt uiIdx, ComponentID eType, UInt uiTrDepth )  { return ( ( getCbf( uiIdx, eType ) >> uiTrDepth ) & 0x1 ); }
+  Void          setCbf    ( UInt uiIdx, ComponentID eType, UChar uh )        { m_puhCbf[eType][uiIdx] = uh;    }
+  Void          clearCbf  ( UInt uiIdx, ComponentID eType, UInt uiNumParts );
+  UChar         getQtRootCbf          ( UInt uiIdx );
+
+  Void          setCbfSubParts        ( const UInt uiCbf[MAX_NUM_COMPONENT],  UInt uiAbsPartIdx, UInt uiDepth           );
+  Void          setCbfSubParts        ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth                    );
+  Void          setCbfSubParts        ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth    );
+
+  Void          setCbfPartRange       ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes      );
+  Void          bitwiseOrCbfPartRange ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes      );
+
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for coding tool information
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   Bool*         getMergeFlag          ()                        { return m_pbMergeFlag;               }
   Bool          getMergeFlag          ( UInt uiIdx )            { return m_pbMergeFlag[uiIdx];        }
@@ -443,9 +453,10 @@
   Void          setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
   template <typename T>
-  Void          setSubPart            ( T bParameter, T* pbBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
+  Void          setSubPart            ( T bParameter, T* pbBaseCtu, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
 #if H_3D_VSP
   template<typename T>
   Void          setSubPartT           ( T uiParameter, T* puhBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
 #endif
+
 #if AMP_MRG
   Void          setMergeAMP( Bool b )      { m_bIsMergeAMP = b; }
@@ -453,14 +464,12 @@
 #endif
 
-  UChar*        getLumaIntraDir       ()                        { return m_puhLumaIntraDir;           }
-  UChar         getLumaIntraDir       ( UInt uiIdx )            { return m_puhLumaIntraDir[uiIdx];    }
-  Void          setLumaIntraDir       ( UInt uiIdx, UChar  uh ) { m_puhLumaIntraDir[uiIdx] = uh;      }
-  Void          setLumaIntraDirSubParts( UInt uiDir,  UInt uiAbsPartIdx, UInt uiDepth );
-  
-  UChar*        getChromaIntraDir     ()                        { return m_puhChromaIntraDir;         }
-  UChar         getChromaIntraDir     ( UInt uiIdx )            { return m_puhChromaIntraDir[uiIdx];  }
-  Void          setChromaIntraDir     ( UInt uiIdx, UChar  uh ) { m_puhChromaIntraDir[uiIdx] = uh;    }
-  Void          setChromIntraDirSubParts( UInt uiDir,  UInt uiAbsPartIdx, UInt uiDepth );
-  
+  UChar*        getIntraDir         ( const ChannelType channelType )                   const { return m_puhIntraDir[channelType];         }
+  UChar         getIntraDir         ( const ChannelType channelType, const UInt uiIdx ) const { return m_puhIntraDir[channelType][uiIdx];  }
+
+  Void          setIntraDirSubParts ( const ChannelType channelType,
+                                      const UInt uiDir,
+                                      const UInt uiAbsPartIdx,
+                                      const UInt uiDepth );
+
   UChar*        getInterDir           ()                        { return m_puhInterDir;               }
   UChar         getInterDir           ( UInt uiIdx )            { return m_puhInterDir[uiIdx];        }
@@ -538,8 +547,8 @@
   // member functions for accessing partition information
   // -------------------------------------------------------------------------------------------------------------------
-  
-  Void          getPartIndexAndSize   ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight );
-#endif
-UChar         getNumPartitions       ();
+
+  Void          getPartIndexAndSize   ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight ); // This is for use by a leaf/sub CU object only, with no additional AbsPartIdx
+#endif
+  UChar         getNumPartitions      ( const UInt uiAbsPartIdx = 0 );
   Bool          isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth);
 
@@ -574,10 +583,11 @@
   // member functions for motion vector
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   Void          getMvField            ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField );
-  
+
   Void          fillMvpCand           ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo );
   Bool          isDiffMER             ( Int xN, Int yN, Int xP, Int yP);
   Void          getPartPosition       ( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH);
+
   Void          setMVPIdx             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPIdx)  { m_apiMVPIdx[eRefPicList][uiIdx] = iMVPIdx;  }
   Int           getMVPIdx             ( RefPicList eRefPicList, UInt uiIdx)               { return m_apiMVPIdx[eRefPicList][uiIdx];     }
@@ -587,10 +597,10 @@
   Int           getMVPNum             ( RefPicList eRefPicList, UInt uiIdx )              { return m_apiMVPNum[eRefPicList][uiIdx];     }
   Char*         getMVPNum             ( RefPicList eRefPicList )                          { return m_apiMVPNum[eRefPicList];            }
-  
+
   Void          setMVPIdxSubParts     ( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
   Void          setMVPNumSubParts     ( Int iMVPNum, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
-  
+
   Void          clipMv                ( TComMv&     rcMv     );
-#if H_MV
+#if NH_MV
   Void          checkMvVertRest (TComMv&  rcMv,  RefPicList eRefPicList, int iRefIdx );
 #endif
@@ -598,5 +608,5 @@
   Void          getMvPredAbove        ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldB.getMv(); }
   Void          getMvPredAboveRight   ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldC.getMv(); }
-#if H_3D
+#if NH_3D
   Void          compressMV            ( Int scale );
 #else            
@@ -606,38 +616,40 @@
   // utility functions for neighbouring information
   // -------------------------------------------------------------------------------------------------------------------
-  
-  TComDataCU*   getCULeft                   () { return m_pcCULeft;       }
-  TComDataCU*   getCUAbove                  () { return m_pcCUAbove;      }
-  TComDataCU*   getCUAboveLeft              () { return m_pcCUAboveLeft;  }
-  TComDataCU*   getCUAboveRight             () { return m_pcCUAboveRight; }
+
+  TComDataCU*   getCtuLeft                  () { return m_pCtuLeft;       }
+  TComDataCU*   getCtuAbove                 () { return m_pCtuAbove;      }
+  TComDataCU*   getCtuAboveLeft             () { return m_pCtuAboveLeft;  }
+  TComDataCU*   getCtuAboveRight            () { return m_pCtuAboveRight; }
   TComDataCU*   getCUColocated              ( RefPicList eRefPicList ) { return m_apcCUColocated[eRefPicList]; }
-
-
-  TComDataCU*   getPULeft                   ( UInt&  uiLPartUnitIdx, 
-                                              UInt uiCurrPartUnitIdx, 
-                                              Bool bEnforceSliceRestriction=true, 
+  Bool          CUIsFromSameSlice           ( const TComDataCU *pCU /* Can be NULL */) const { return ( pCU!=NULL && pCU->getSlice()->getSliceCurStartCtuTsAddr() == getSlice()->getSliceCurStartCtuTsAddr() ); }
+  Bool          CUIsFromSameTile            ( const TComDataCU *pCU /* Can be NULL */) const;
+  Bool          CUIsFromSameSliceAndTile    ( const TComDataCU *pCU /* Can be NULL */) const;
+  Bool          CUIsFromSameSliceTileAndWavefrontRow( const TComDataCU *pCU /* Can be NULL */) const;
+  Bool          isLastSubCUOfCtu(const UInt absPartIdx);
+
+
+  TComDataCU*   getPULeft                   ( UInt&  uiLPartUnitIdx,
+                                              UInt uiCurrPartUnitIdx,
+                                              Bool bEnforceSliceRestriction=true,
                                               Bool bEnforceTileRestriction=true );
   TComDataCU*   getPUAbove                  ( UInt&  uiAPartUnitIdx,
-                                              UInt uiCurrPartUnitIdx, 
-                                              Bool bEnforceSliceRestriction=true, 
-                                              Bool planarAtLCUBoundary = false,
+                                              UInt uiCurrPartUnitIdx,
+                                              Bool bEnforceSliceRestriction=true,
+                                              Bool planarAtCTUBoundary = false,
                                               Bool bEnforceTileRestriction=true );
   TComDataCU*   getPUAboveLeft              ( UInt&  uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true );
-  TComDataCU*   getPUAboveRight             ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true );
-  TComDataCU*   getPUBelowLeft              ( UInt&  uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true );
-
-  TComDataCU*   getQpMinCuLeft              ( UInt&  uiLPartUnitIdx , UInt uiCurrAbsIdxInLCU );
-  TComDataCU*   getQpMinCuAbove             ( UInt&  aPartUnitIdx , UInt currAbsIdxInLCU );
-  Char          getRefQP                    ( UInt   uiCurrAbsIdxInLCU                       );
-
-  TComDataCU*   getPUAboveRightAdi          ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true );
-  TComDataCU*   getPUBelowLeftAdi           ( UInt&  uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true );
-  
+
+  TComDataCU*   getQpMinCuLeft              ( UInt&  uiLPartUnitIdx , UInt uiCurrAbsIdxInCtu );
+  TComDataCU*   getQpMinCuAbove             ( UInt&  uiAPartUnitIdx , UInt uiCurrAbsIdxInCtu );
+  Char          getRefQP                    ( UInt   uiCurrAbsIdxInCtu                       );
+
+  /// returns CU and part index of the PU above the top row of the current uiCurrPartUnitIdx of the CU, at a horizontal offset (to the right) of uiPartUnitOffset (in parts)
+  TComDataCU*   getPUAboveRight             ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true );
+  /// returns CU and part index of the PU left of the lefthand column of the current uiCurrPartUnitIdx of the CU, at a vertical offset (below) of uiPartUnitOffset (in parts)
+  TComDataCU*   getPUBelowLeft              ( UInt&  uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true );
+
   Void          deriveLeftRightTopIdx       ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
   Void          deriveLeftBottomIdx         ( UInt uiPartIdx, UInt& ruiPartIdxLB );
-  
-  Void          deriveLeftRightTopIdxAdi    ( UInt& ruiPartIdxLT, UInt& ruiPartIdxRT, UInt uiPartOffset, UInt uiPartDepth );
-  Void          deriveLeftBottomIdxAdi      ( UInt& ruiPartIdxLB, UInt  uiPartOffset, UInt uiPartDepth );
-  
+
   Bool          hasEqualMotion              ( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx );
 
@@ -661,11 +673,9 @@
   Void          xGetInterMergeCandidates ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours
 #else
-  Void          getInterMergeCandidates ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours
+  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 );
 #endif
 #if H_3D_SPIVMP
                                             , TComMvField* pcMvFieldSP, UChar* puhInterDirSP
 #endif
-                                            , Int& numValidMergeCand, Int mrgCandIdx = -1
-                                            );
 
 #if H_3D_VSP
@@ -685,12 +695,12 @@
   Void          deriveLeftRightTopIdxGeneral  ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
   Void          deriveLeftBottomIdxGeneral    ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB );
-  
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for modes
   // -------------------------------------------------------------------------------------------------------------------
-  
-  Bool          isIntra   ( UInt uiPartIdx )  { return m_pePredMode[ uiPartIdx ] == MODE_INTRA; }
-  Bool          isSkipped ( UInt uiPartIdx );                                                     ///< SKIP (no residual)
+
+  Bool          isIntra            ( UInt uiPartIdx )  const { return m_pePredMode[ uiPartIdx ] == MODE_INTRA;                                              }
+  Bool          isInter            ( UInt uiPartIdx )  const { return m_pePredMode[ uiPartIdx ] == MODE_INTER;                                              }
+  Bool          isSkipped          ( UInt uiPartIdx );                                                     ///< returns true, if the partiton is skipped
   Bool          isBipredRestriction( UInt puIdx );
 
@@ -702,41 +712,38 @@
   // member functions for symbol prediction (most probable / mode conversion)
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   UInt          getIntraSizeIdx                 ( UInt uiAbsPartIdx                                       );
-  
+
   Void          getAllowedChromaDir             ( UInt uiAbsPartIdx, UInt* uiModeList );
-  Int           getIntraDirLumaPredictor        ( UInt uiAbsPartIdx, Int* uiIntraDirPred, Int* piMode = NULL );
-  
+  Void          getIntraDirPredictor            ( UInt uiAbsPartIdx, Int uiIntraDirPred[NUM_MOST_PROBABLE_MODES], const ComponentID compID, Int* piMode = NULL );
+
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for SBAC context
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   UInt          getCtxSplitFlag                 ( UInt   uiAbsPartIdx, UInt uiDepth                   );
-  UInt          getCtxQtCbf                     ( TextType eType, UInt uiTrDepth );
+  UInt          getCtxQtCbf                     ( TComTU &rTu, const ChannelType chType );
 
   UInt          getCtxSkipFlag                  ( UInt   uiAbsPartIdx                                 );
   UInt          getCtxInterDir                  ( UInt   uiAbsPartIdx                                 );
-  
 #if H_3D_ARP
   UInt          getCTXARPWFlag                  ( UInt   uiAbsPartIdx                                 );
 #endif  
-  UInt          getSliceStartCU         ( UInt pos )                  { return m_sliceStartCU[pos-m_uiAbsIdxInLCU];                                                                                          }
-  UInt          getSliceSegmentStartCU  ( UInt pos )                  { return m_sliceSegmentStartCU[pos-m_uiAbsIdxInLCU];                                                                                   }
-  UInt&         getTotalBins            ()                            { return m_uiTotalBins;                                                                                                  }
+
+  UInt&         getTotalBins            ()                            { return m_uiTotalBins;                              }
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for RD cost storage
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   Double&       getTotalCost()                  { return m_dTotalCost;        }
-#if H_3D_VSO
+#if NH_3D_VSO
   Dist&         getTotalDistortion()            { return m_uiTotalDistortion; }
 #else
-  UInt&         getTotalDistortion()            { return m_uiTotalDistortion; }
+  Distortion&   getTotalDistortion()            { return m_uiTotalDistortion; }
 #endif
   UInt&         getTotalBits()                  { return m_uiTotalBits;       }
   UInt&         getTotalNumPart()               { return m_uiNumPartition;    }
 
-  UInt          getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra);
-
+  UInt          getCoefScanIdx(const UInt uiAbsPartIdx, const UInt uiWidth, const UInt uiHeight, const ComponentID compID) const ;
 
 #if H_3D_DIM
@@ -760,5 +767,5 @@
     return (( addrA ^ addrB ) &  ( numUnitsPerRow - 1 ) ) == 0;
   }
-  
+
   /** Check whether 2 addresses point to the same row
    * \param addrA          First address in raster scan order
@@ -772,5 +779,5 @@
     return (( addrA ^ addrB ) &~ ( numUnitsPerRow - 1 ) ) == 0;
   }
-  
+
   /** Check whether 2 addresses point to the same row or column
    * \param addrA          First address in raster scan order
@@ -783,5 +790,5 @@
     return isEqualCol( addrA, addrB, numUnitsPerRow ) | isEqualRow( addrA, addrB, numUnitsPerRow );
   }
-  
+
   /** Check whether one address points to the first column
    * \param addr           Address in raster scan order
@@ -794,5 +801,5 @@
     return ( addr & ( numUnitsPerRow - 1 ) ) == 0;
   }
-  
+
   /** Check whether one address points to the first row
    * \param addr           Address in raster scan order
@@ -805,5 +812,5 @@
     return ( addr &~ ( numUnitsPerRow - 1 ) ) == 0;
   }
-  
+
   /** Check whether one address points to a column whose index is smaller than a given value
    * \param addr           Address in raster scan order
@@ -817,5 +824,5 @@
     return ( addr & ( numUnitsPerRow - 1 ) ) < val;
   }
-  
+
   /** Check whether one address points to a row whose index is smaller than a given value
    * \param addr           Address in raster scan order
@@ -829,5 +836,5 @@
     return addr < val * numUnitsPerRow;
   }
-};
+}
 
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,4 +45,6 @@
 #include <assert.h>
 
+#include "TComChromaFormat.h"
+
 
 //! \ingroup TLibCommon
@@ -53,5 +55,5 @@
 // ====================================================================================================================
 
-const Short TComInterpolationFilter::m_lumaFilter[4][NTAPS_LUMA] =
+const TFilterCoeff TComInterpolationFilter::m_lumaFilter[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][NTAPS_LUMA] =
 {
   {  0, 0,   0, 64,  0,   0, 0,  0 },
@@ -61,5 +63,5 @@
 };
 
-const Short TComInterpolationFilter::m_chromaFilter[8][NTAPS_CHROMA] =
+const TFilterCoeff TComInterpolationFilter::m_chromaFilter[CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][NTAPS_CHROMA] =
 {
   {  0, 64,  0,  0 },
@@ -111,8 +113,8 @@
  * \param isLast     Flag indicating whether it is the last filtering operation
  */
-Void TComInterpolationFilter::filterCopy(Int bitDepth, const Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast)
+Void TComInterpolationFilter::filterCopy(Int bitDepth, const Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast)
 {
   Int row, col;
-  
+
   if ( isFirst == isLast )
   {
@@ -123,46 +125,51 @@
         dst[col] = src[col];
       }
-      
+
       src += srcStride;
       dst += dstStride;
-    }              
+    }
   }
   else if ( isFirst )
   {
-    Int shift = IF_INTERNAL_PREC - bitDepth;
-    
+    const Int shift = std::max<Int>(2, (IF_INTERNAL_PREC - bitDepth));
+
     for (row = 0; row < height; row++)
     {
       for (col = 0; col < width; col++)
       {
-        Short val = src[col] << shift;
-        dst[col] = val - (Short)IF_INTERNAL_OFFS;
-      }
-      
+        Pel val = leftShift_round(src[col], shift);
+        dst[col] = val - (Pel)IF_INTERNAL_OFFS;
+      }
+
       src += srcStride;
       dst += dstStride;
-    }          
-  }
-  else
-  {
-    Int shift = IF_INTERNAL_PREC - bitDepth;
-    Short offset = IF_INTERNAL_OFFS;
-    offset += shift?(1 << (shift - 1)):0;
-    Short maxVal = (1 << bitDepth) - 1;
-    Short minVal = 0;
+    }
+  }
+  else
+  {
+    const Int shift = std::max<Int>(2, (IF_INTERNAL_PREC - bitDepth));
+
+    Pel maxVal = (1 << bitDepth) - 1;
+    Pel minVal = 0;
     for (row = 0; row < height; row++)
     {
       for (col = 0; col < width; col++)
       {
-        Short val = src[ col ];
-        val = ( val + offset ) >> shift;
-        if (val < minVal) val = minVal;
-        if (val > maxVal) val = maxVal;
+        Pel val = src[ col ];
+        val = rightShift_round((val + IF_INTERNAL_OFFS), shift);
+        if (val < minVal)
+        {
+          val = minVal;
+        }
+        if (val > maxVal)
+        {
+          val = maxVal;
+        }
         dst[col] = val;
       }
-      
+
       src += srcStride;
       dst += dstStride;
-    }              
+    }
   }
 }
@@ -185,9 +192,9 @@
  */
 template<Int N, Bool isVertical, Bool isFirst, Bool isLast>
-Void TComInterpolationFilter::filter(Int bitDepth, Short const *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Short const *coeff)
+Void TComInterpolationFilter::filter(Int bitDepth, Pel const *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, TFilterCoeff const *coeff)
 {
   Int row, col;
-  
-  Short c[8];
+
+  Pel c[8];
   c[0] = coeff[0];
   c[1] = coeff[1];
@@ -207,12 +214,16 @@
     c[7] = coeff[7];
   }
-  
+
   Int cStride = ( isVertical ) ? srcStride : 1;
   src -= ( N/2 - 1 ) * cStride;
 
   Int offset;
-  Short maxVal;
-  Int headRoom = IF_INTERNAL_PREC - bitDepth;
-  Int shift = IF_FILTER_PREC;
+  Pel maxVal;
+  Int headRoom = std::max<Int>(2, (IF_INTERNAL_PREC - bitDepth));
+  Int shift    = IF_FILTER_PREC;
+  // with the current settings (IF_INTERNAL_PREC = 14 and IF_FILTER_PREC = 6), though headroom can be
+  // negative for bit depths greater than 14, shift will remain non-negative for bit depths of 8->20
+  assert(shift >= 0);
+
   if ( isLast )
   {
@@ -228,5 +239,5 @@
     maxVal = 0;
   }
-  
+
   for (row = 0; row < height; row++)
   {
@@ -234,5 +245,5 @@
     {
       Int sum;
-      
+
       sum  = src[ col + 0 * cStride] * c[0];
       sum += src[ col + 1 * cStride] * c[1];
@@ -250,19 +261,19 @@
       {
         sum += src[ col + 6 * cStride] * c[6];
-        sum += src[ col + 7 * cStride] * c[7];        
-      }
-      
-      Short val = ( sum + offset ) >> shift;
+        sum += src[ col + 7 * cStride] * c[7];
+      }
+
+      Pel val = ( sum + offset ) >> shift;
       if ( isLast )
       {
         val = ( val < 0 ) ? 0 : val;
-        val = ( val > maxVal ) ? maxVal : val;        
+        val = ( val > maxVal ) ? maxVal : val;
       }
       dst[col] = val;
     }
-    
+
     src += srcStride;
     dst += dstStride;
-  }    
+  }
 }
 
@@ -282,5 +293,5 @@
  */
 template<Int N>
-Void TComInterpolationFilter::filterHor(Int bitDepth, Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isLast, Short const *coeff)
+Void TComInterpolationFilter::filterHor(Int bitDepth, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Bool isLast, TFilterCoeff const *coeff)
 {
   if ( isLast )
@@ -298,5 +309,5 @@
  *
  * \tparam N          Number of taps
- * \param  bitDpeth   Sample bit depth
+ * \param  bitDepth   Bit depth
  * \param  src        Pointer to source samples
  * \param  srcStride  Stride of source samples
@@ -310,5 +321,5 @@
  */
 template<Int N>
-Void TComInterpolationFilter::filterVer(Int bitDepth, Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, Short const *coeff)
+Void TComInterpolationFilter::filterVer(Int bitDepth, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, TFilterCoeff const *coeff)
 {
   if ( isFirst && isLast )
@@ -327,5 +338,5 @@
   {
     filter<N, true, false, false>(bitDepth, src, srcStride, dst, dstStride, width, height, coeff);
-  }      
+  }
 }
 
@@ -335,6 +346,7 @@
 
 /**
- * \brief Filter a block of luma samples (horizontal)
- *
+ * \brief Filter a block of Luma/Chroma samples (horizontal)
+ *
+ * \param  compID     Chroma component ID
  * \param  src        Pointer to source samples
  * \param  srcStride  Stride of source samples
@@ -345,18 +357,18 @@
  * \param  frac       Fractional sample offset
  * \param  isLast     Flag indicating whether it is the last filtering operation
- */
-Void TComInterpolationFilter::filterHorLuma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast 
+ * \param  fmt        Chroma format
+ * \param  bitDepth   Bit depth
+ */
+Void TComInterpolationFilter::filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast, const ChromaFormat fmt, const Int bitDepth 
 #if H_3D_ARP
     , Bool filterType
 #endif
-  )
-{
-  assert(frac >= 0 && frac < 4);
-  
+)
+{
   if ( frac == 0 )
   {
-    filterCopy(g_bitDepthY, src, srcStride, dst, dstStride, width, height, true, isLast );
-  }
-  else
+    filterCopy(bitDepth, src, srcStride, dst, dstStride, width, height, true, isLast );
+  }
+  else if (isLuma(compID))
   {
 #if H_3D_ARP
@@ -368,14 +380,25 @@
     {
 #endif
-    filterHor<NTAPS_LUMA>(g_bitDepthY, src, srcStride, dst, dstStride, width, height, isLast, m_lumaFilter[frac]);
-#if H_3D_ARP
-    }
-#endif
-  }
-}
-
-/**
- * \brief Filter a block of luma samples (vertical)
- *
+
+    assert(frac >= 0 && frac < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
+    filterHor<NTAPS_LUMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isLast, m_lumaFilter[frac]);
+#if H_3D_ARP
+    }
+#endif
+
+  }
+  else
+  {
+    const UInt csx = getComponentScaleX(compID, fmt);
+    assert(frac >=0 && csx<2 && (frac<<(1-csx)) < CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
+    filterHor<NTAPS_CHROMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isLast, m_chromaFilter[frac<<(1-csx)]);
+  }
+}
+
+
+/**
+ * \brief Filter a block of Luma/Chroma samples (vertical)
+ *
+ * \param  compID     Colour component ID
  * \param  src        Pointer to source samples
  * \param  srcStride  Stride of source samples
@@ -387,18 +410,18 @@
  * \param  isFirst    Flag indicating whether it is the first filtering operation
  * \param  isLast     Flag indicating whether it is the last filtering operation
- */
-Void TComInterpolationFilter::filterVerLuma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast 
+ * \param  fmt        Chroma format
+ * \param  bitDepth   Bit depth
+ */
+Void TComInterpolationFilter::filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth 
 #if H_3D_ARP
     , Bool filterType
 #endif
-  )
-{
-  assert(frac >= 0 && frac < 4);
-  
+)
+{
   if ( frac == 0 )
   {
-    filterCopy(g_bitDepthY, src, srcStride, dst, dstStride, width, height, isFirst, isLast );
-  }
-  else
+    filterCopy(bitDepth, src, srcStride, dst, dstStride, width, height, isFirst, isLast );
+  }
+  else if (isLuma(compID))
   {
 #if H_3D_ARP
@@ -410,37 +433,23 @@
     {
 #endif
-    filterVer<NTAPS_LUMA>(g_bitDepthY, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilter[frac]);
-#if H_3D_ARP
-    }
-#endif
-  }
-}
-
-/**
- * \brief Filter a block of chroma samples (horizontal)
- *
- * \param  src        Pointer to source samples
- * \param  srcStride  Stride of source samples
- * \param  dst        Pointer to destination samples
- * \param  dstStride  Stride of destination samples
- * \param  width      Width of block
- * \param  height     Height of block
- * \param  frac       Fractional sample offset
- * \param  isLast     Flag indicating whether it is the last filtering operation
- */
-Void TComInterpolationFilter::filterHorChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast 
+    assert(frac >= 0 && frac < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
+    filterVer<NTAPS_LUMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilter[frac]);
+#if H_3D_ARP
+    }
+#endif
+
+  }
+  else
+  {
+    const UInt csy = getComponentScaleY(compID, fmt);
+    assert(frac >=0 && csy<2 && (frac<<(1-csy)) < CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
+    filterVer<NTAPS_CHROMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilter[frac<<(1-csy)]);
+  }
+}
+
 #if H_3D_ARP
     , Bool filterType
 #endif
-  )
-{
-  assert(frac >= 0 && frac < 8);
-  
-  if ( frac == 0 )
-  {
-    filterCopy(g_bitDepthC, src, srcStride, dst, dstStride, width, height, true, isLast );
-  }
-  else
-  {
+
 #if H_3D_ARP
     if(filterType)
@@ -451,38 +460,10 @@
     {
 #endif
-    filterHor<NTAPS_CHROMA>(g_bitDepthC, src, srcStride, dst, dstStride, width, height, isLast, m_chromaFilter[frac]);
-#if H_3D_ARP
-    }
-#endif
-  }
-}
-
-/**
- * \brief Filter a block of chroma samples (vertical)
- *
- * \param  src        Pointer to source samples
- * \param  srcStride  Stride of source samples
- * \param  dst        Pointer to destination samples
- * \param  dstStride  Stride of destination samples
- * \param  width      Width of block
- * \param  height     Height of block
- * \param  frac       Fractional sample offset
- * \param  isFirst    Flag indicating whether it is the first filtering operation
- * \param  isLast     Flag indicating whether it is the last filtering operation
- */
-Void TComInterpolationFilter::filterVerChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast 
+#if H_3D_ARP
+    }
+#endif
 #if H_3D_ARP
     , Bool filterType
 #endif
-  )
-{
-  assert(frac >= 0 && frac < 8);
-  
-  if ( frac == 0 )
-  {
-    filterCopy(g_bitDepthC, src, srcStride, dst, dstStride, width, height, isFirst, isLast );
-  }
-  else
-  {
 #if H_3D_ARP
     if(filterType)
@@ -493,10 +474,9 @@
     {
 #endif
-    filterVer<NTAPS_CHROMA>(g_bitDepthC, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilter[frac]);
-#if H_3D_ARP
-    }
-#endif
-  }
-}
+#if H_3D_ARP
+    }
+#endif
+
+
 
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,8 +37,8 @@
  */
 
-#ifndef __HM_TCOMINTERPOLATIONFILTER_H__
-#define __HM_TCOMINTERPOLATIONFILTER_H__
+#ifndef __TCOMINTERPOLATIONFILTER__
+#define __TCOMINTERPOLATIONFILTER__
 
-#include "TypeDef.h"
+#include "CommonDef.h"
 
 //! \ingroup TLibCommon
@@ -61,19 +61,20 @@
 class TComInterpolationFilter
 {
-  static const Short m_lumaFilter[4][NTAPS_LUMA];     ///< Luma filter taps
-  static const Short m_chromaFilter[8][NTAPS_CHROMA]; ///< Chroma filter taps
+  static const TFilterCoeff m_lumaFilter[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][NTAPS_LUMA];     ///< Luma filter taps
+  static const TFilterCoeff m_chromaFilter[CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][NTAPS_CHROMA]; ///< Chroma filter taps
 #if H_3D_ARP
   static const Short m_lumaFilterARP  [4][NTAPS_LUMA_ARP];     ///< Luma filter taps for ARP
   static const Short m_chromaFilterARP[8][NTAPS_CHROMA_ARP];   ///< Chroma filter taps for ARP
 #endif
-  static Void filterCopy(Int bitDepth, const Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast);
-  
+
+  static Void filterCopy(Int bitDepth, const Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast);
+
   template<Int N, Bool isVertical, Bool isFirst, Bool isLast>
-  static Void filter(Int bitDepth, Pel const *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Short const *coeff);
+  static Void filter(Int bitDepth, Pel const *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, TFilterCoeff const *coeff);
 
   template<Int N>
-  static Void filterHor(Int bitDepth, Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height,               Bool isLast, Short const *coeff);
+  static Void filterHor(Int bitDepth, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height,               Bool isLast, TFilterCoeff const *coeff);
   template<Int N>
-  static Void filterVer(Int bitDepth, Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, Short const *coeff);
+  static Void filterVer(Int bitDepth, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, TFilterCoeff const *coeff);
 
 public:
@@ -81,25 +82,22 @@
   ~TComInterpolationFilter() {}
 
-  Void filterHorLuma  (Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast 
+  Void filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast, const ChromaFormat fmt, const Int bitDepth 
 #if H_3D_ARP
     , Bool filterType = false
 #endif
-    );
-  Void filterVerLuma  (Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast 
+);
+  Void filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth 
 #if H_3D_ARP
     , Bool filterType = false
 #endif
-    );
-  Void filterHorChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast 
+);
+};
+
 #if H_3D_ARP
     , Bool filterType = false
 #endif
-    );
-  Void filterVerChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast 
 #if H_3D_ARP
     , Bool filterType = false
 #endif
-    );
-};
 
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComList.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComList.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComList.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,6 +36,6 @@
 */
 
-#ifndef _TCOMLIST_
-#define _TCOMLIST_
+#ifndef __TCOMLIST__
+#define __TCOMLIST__
 
 #if _MSC_VER > 1000
@@ -59,9 +59,9 @@
 /// list template
 template< class C >
-class TComList : public std::list< C >
+class TComList : public std::list< C > // NOTE: should not inherit from STL classes
 {
 public:
   typedef typename std::list<C>::iterator TComIterator;
-  
+
   TComList& operator += ( const TComList& rcTComList)
   {
@@ -72,5 +72,5 @@
     return *this;
   } // leszek
-  
+
   C popBack()
   {
@@ -79,5 +79,5 @@
     return cT;
   }
-  
+
   C popFront()
   {
@@ -86,5 +86,5 @@
     return cT;
   }
-  
+
   Void pushBack( const C& rcT )
   {
@@ -95,5 +95,5 @@
     }
   }
-  
+
   Void pushFront( const C& rcT )
   {
@@ -104,8 +104,8 @@
     }
   }
-  
+
   TComIterator find( const C& rcT ) // leszek
   {
-    return find( this->begin(), this->end(), rcT );
+    return std::list< C >::find( this->begin(), this->end(), rcT );
   }
 };
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,4 +39,5 @@
 #include "TComSlice.h"
 #include "TComMv.h"
+#include "TComTU.h"
 
 //! \ingroup TLibCommon
@@ -47,7 +48,6 @@
 // ====================================================================================================================
 
-#define   EDGE_VER    0
-#define   EDGE_HOR    1
-#define   QpUV(iQpY)  ( ((iQpY) < 0) ? (iQpY) : (((iQpY) > 57) ? ((iQpY)-6) : g_aucChromaScale[(iQpY)]) )
+//#define   EDGE_VER    0
+//#define   EDGE_HOR    1
 
 #define DEFAULT_INTRA_TC_OFFSET 2 ///< Default intra TC offset
@@ -57,10 +57,10 @@
 // ====================================================================================================================
 
-const UChar TComLoopFilter::sm_tcTable[54] =
+const UChar TComLoopFilter::sm_tcTable[MAX_QP + 1 + DEFAULT_INTRA_TC_OFFSET] =
 {
   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,5,5,6,6,7,8,9,10,11,13,14,16,18,20,22,24
 };
 
-const UChar TComLoopFilter::sm_betaTable[52] =
+const UChar TComLoopFilter::sm_betaTable[MAX_QP + 1] =
 {
   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,7,8,9,10,11,12,13,14,15,16,17,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64
@@ -75,8 +75,8 @@
 , m_bLFCrossTileBoundary(true)
 {
-  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
-  {
-    m_aapucBS       [uiDir] = NULL;
-    m_aapbEdgeFilter[uiDir] = NULL;
+  for( Int edgeDir = 0; edgeDir < NUM_EDGE_DIR; edgeDir++ )
+  {
+    m_aapucBS       [edgeDir] = NULL;
+    m_aapbEdgeFilter[edgeDir] = NULL;
   }
 }
@@ -98,8 +98,8 @@
   destroy();
   m_uiNumPartitions = 1 << ( uiMaxCUDepth<<1 );
-  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
-  {
-    m_aapucBS       [uiDir] = new UChar[m_uiNumPartitions];
-    m_aapbEdgeFilter[uiDir] = new Bool [m_uiNumPartitions];
+  for( Int edgeDir = 0; edgeDir < NUM_EDGE_DIR; edgeDir++ )
+  {
+    m_aapucBS       [edgeDir] = new UChar[m_uiNumPartitions];
+    m_aapbEdgeFilter[edgeDir] = new Bool [m_uiNumPartitions];
   }
 }
@@ -107,15 +107,16 @@
 Void TComLoopFilter::destroy()
 {
-  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
-  {
-    if (m_aapucBS)
-    {
-      delete [] m_aapucBS       [uiDir];
-      m_aapucBS [uiDir] = NULL;
-    }
-    if (m_aapbEdgeFilter[uiDir])
-    {
-      delete [] m_aapbEdgeFilter[uiDir];
-      m_aapbEdgeFilter[uiDir] = NULL;
+  for( Int edgeDir = 0; edgeDir < NUM_EDGE_DIR; edgeDir++ )
+  {
+    if (m_aapucBS[edgeDir] != NULL)
+    {
+      delete [] m_aapucBS[edgeDir];
+      m_aapucBS[edgeDir] = NULL;
+    }
+
+    if (m_aapbEdgeFilter[edgeDir])
+    {
+      delete [] m_aapbEdgeFilter[edgeDir];
+      m_aapbEdgeFilter[edgeDir] = NULL;
     }
   }
@@ -130,7 +131,7 @@
 {
   // Horizontal filtering
-  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
-  {
-    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+  for ( UInt ctuRsAddr = 0; ctuRsAddr < pcPic->getNumberOfCtusInFrame(); ctuRsAddr++ )
+  {
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
 
     ::memset( m_aapucBS       [EDGE_VER], 0, sizeof( UChar ) * m_uiNumPartitions );
@@ -138,11 +139,11 @@
 
     // CU-based deblocking
-    xDeblockCU( pcCU, 0, 0, EDGE_VER );
+    xDeblockCU( pCtu, 0, 0, EDGE_VER );
   }
 
   // Vertical filtering
-  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
-  {
-    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+  for ( UInt ctuRsAddr = 0; ctuRsAddr < pcPic->getNumberOfCtusInFrame(); ctuRsAddr++ )
+  {
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
 
     ::memset( m_aapucBS       [EDGE_HOR], 0, sizeof( UChar ) * m_uiNumPartitions );
@@ -150,5 +151,5 @@
 
     // CU-based deblocking
-    xDeblockCU( pcCU, 0, 0, EDGE_HOR );
+    xDeblockCU( pCtu, 0, 0, EDGE_HOR );
   }
 }
@@ -160,18 +161,22 @@
 
 /**
- - Deblocking filter process in CU-based (the same function as conventional's)
- .
- \param Edge          the direction of the edge in block boundary (horizonta/vertical), which is added newly
+ Deblocking filter process in CU-based (the same function as conventional's)
+
+ \param pcCU             Pointer to CTU/CU structure
+ \param uiAbsZorderIdx   Position in CU
+ \param uiDepth          Depth in CU
+ \param edgeDir          the direction of the edge in block boundary (horizontal/vertical), which is added newly
 */
-Void TComLoopFilter::xDeblockCU( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge )
-{
-  if(pcCU->getPic()==0||pcCU->getPartitionSize(uiAbsZorderIdx)==SIZE_NONE)
+Void TComLoopFilter::xDeblockCU( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, DeblockEdgeDir edgeDir )
+{
+  if(pcCU->getPic()==0||pcCU->getPartitionSize(uiAbsZorderIdx)==NUMBER_OF_PART_SIZES)
   {
     return;
   }
   TComPic* pcPic     = pcCU->getPic();
-  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiCurNumParts = pcPic->getNumPartitionsInCtu() >> (uiDepth<<1);
   UInt uiQNumParts   = uiCurNumParts>>2;
-  
+  const TComSPS &sps = *(pcCU->getSlice()->getSPS());
+
   if( pcCU->getDepth(uiAbsZorderIdx) > uiDepth )
   {
@@ -180,24 +185,25 @@
       UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
       UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
-      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
-      {
-        xDeblockCU( pcCU, uiAbsZorderIdx, uiDepth+1, Edge );
+      if( ( uiLPelX < sps.getPicWidthInLumaSamples() ) && ( uiTPelY < sps.getPicHeightInLumaSamples() ) )
+      {
+        xDeblockCU( pcCU, uiAbsZorderIdx, uiDepth+1, edgeDir );
       }
     }
     return;
   }
-  
+
   xSetLoopfilterParam( pcCU, uiAbsZorderIdx );
-  
-  xSetEdgefilterTU   ( pcCU, uiAbsZorderIdx , uiAbsZorderIdx, uiDepth );
+  TComTURecurse tuRecurse(pcCU, uiAbsZorderIdx);
+  xSetEdgefilterTU   ( tuRecurse );
   xSetEdgefilterPU   ( pcCU, uiAbsZorderIdx );
-  
-  Int iDir = Edge;
+
+  const UInt uiPelsInPart = sps.getMaxCUWidth() >> sps.getMaxTotalCUDepth();
+
   for( UInt uiPartIdx = uiAbsZorderIdx; uiPartIdx < uiAbsZorderIdx + uiCurNumParts; uiPartIdx++ )
   {
     UInt uiBSCheck;
-    if( (g_uiMaxCUWidth >> g_uiMaxCUDepth) == 4 ) 
-    {
-      uiBSCheck = (iDir == EDGE_VER && uiPartIdx%2 == 0) || (iDir == EDGE_HOR && (uiPartIdx-((uiPartIdx>>2)<<2))/2 == 0);
+    if( uiPelsInPart == 4 )
+    {
+      uiBSCheck = (edgeDir == EDGE_VER && uiPartIdx%2 == 0) || (edgeDir == EDGE_HOR && (uiPartIdx-((uiPartIdx>>2)<<2))/2 == 0);
     }
     else
@@ -205,37 +211,51 @@
       uiBSCheck = 1;
     }
-    
-    if ( m_aapbEdgeFilter[iDir][uiPartIdx] && uiBSCheck )
-    {
-      xGetBoundaryStrengthSingle ( pcCU, iDir, uiPartIdx );
-    }
-  }
-  
-  UInt uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+
+    if ( m_aapbEdgeFilter[edgeDir][uiPartIdx] && uiBSCheck )
+    {
+      xGetBoundaryStrengthSingle ( pcCU, edgeDir, uiPartIdx );
+    }
+  }
+
   UInt PartIdxIncr = DEBLOCK_SMALLEST_BLOCK / uiPelsInPart ? DEBLOCK_SMALLEST_BLOCK / uiPelsInPart : 1 ;
-  
-  UInt uiSizeInPU = pcPic->getNumPartInWidth()>>(uiDepth);
-  
-  for ( UInt iEdge = 0; iEdge < uiSizeInPU ; iEdge+=PartIdxIncr)
-  {
-    xEdgeFilterLuma     ( pcCU, uiAbsZorderIdx, uiDepth, iDir, iEdge );
-    if ( (uiPelsInPart>DEBLOCK_SMALLEST_BLOCK) || (iEdge % ( (DEBLOCK_SMALLEST_BLOCK<<1)/uiPelsInPart ) ) == 0 )
-    {
-      xEdgeFilterChroma   ( pcCU, uiAbsZorderIdx, uiDepth, iDir, iEdge );
-    }
-  }
-}
-
-Void TComLoopFilter::xSetEdgefilterMultiple( TComDataCU* pcCU, UInt uiScanIdx, UInt uiDepth, Int iDir, Int iEdgeIdx, Bool bValue,UInt uiWidthInBaseUnits, UInt uiHeightInBaseUnits )
-{  
+
+  UInt uiSizeInPU = pcPic->getNumPartInCtuWidth()>>(uiDepth);
+  const ChromaFormat chFmt=pcPic->getChromaFormat();
+  const UInt shiftFactor  = edgeDir == EDGE_VER ? pcPic->getComponentScaleX(COMPONENT_Cb) : pcPic->getComponentScaleY(COMPONENT_Cb);
+  const Bool bAlwaysDoChroma=chFmt==CHROMA_444;
+
+  for ( Int iEdge = 0; iEdge < uiSizeInPU ; iEdge+=PartIdxIncr)
+  {
+    xEdgeFilterLuma     ( pcCU, uiAbsZorderIdx, uiDepth, edgeDir, iEdge );
+    if ( chFmt!=CHROMA_400 && (bAlwaysDoChroma ||
+                               (uiPelsInPart>DEBLOCK_SMALLEST_BLOCK) ||
+                               (iEdge % ( (DEBLOCK_SMALLEST_BLOCK<<shiftFactor)/uiPelsInPart ) ) == 0
+                              )
+       )
+    {
+      xEdgeFilterChroma   ( pcCU, uiAbsZorderIdx, uiDepth, edgeDir, iEdge );
+    }
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterMultiple( TComDataCU*    pcCU,
+                                             UInt           uiAbsZorderIdx,
+                                             UInt           uiDepth,
+                                             DeblockEdgeDir edgeDir,
+                                             Int            iEdgeIdx,
+                                             Bool           bValue,
+                                             UInt           uiWidthInBaseUnits,
+                                             UInt           uiHeightInBaseUnits,
+                                             const TComRectangle *rect)
+{
   if ( uiWidthInBaseUnits == 0 )
   {
-    uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
+    uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInCtuWidth () >> uiDepth;
   }
   if ( uiHeightInBaseUnits == 0 )
   {
-    uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> uiDepth;
-  }
-  const UInt uiNumElem = iDir == 0 ? uiHeightInBaseUnits : uiWidthInBaseUnits;
+    uiHeightInBaseUnits = pcCU->getPic()->getNumPartInCtuHeight() >> uiDepth;
+  }
+  const UInt uiNumElem = edgeDir == EDGE_VER ? uiHeightInBaseUnits : uiWidthInBaseUnits;
   assert( uiNumElem > 0 );
   assert( uiWidthInBaseUnits > 0 );
@@ -243,35 +263,36 @@
   for( UInt ui = 0; ui < uiNumElem; ui++ )
   {
-    const UInt uiBsIdx = xCalcBsIdx( pcCU, uiScanIdx, iDir, iEdgeIdx, ui );
-    m_aapbEdgeFilter[iDir][uiBsIdx] = bValue;
+    const UInt uiBsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, edgeDir, iEdgeIdx, ui, rect );
+    m_aapbEdgeFilter[edgeDir][uiBsIdx] = bValue;
     if (iEdgeIdx == 0)
     {
-      m_aapucBS[iDir][uiBsIdx] = bValue;
-    }
-  }
-}
-
-Void TComLoopFilter::xSetEdgefilterTU( TComDataCU* pcCU, UInt absTUPartIdx, UInt uiAbsZorderIdx, UInt uiDepth )
-{
-  if( pcCU->getTransformIdx( uiAbsZorderIdx ) + pcCU->getDepth( uiAbsZorderIdx) > uiDepth )
-  {
-    const UInt uiCurNumParts = pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1);
-    const UInt uiQNumParts   = uiCurNumParts>>2;
-    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
-    {
-      UInt nsAddr = uiAbsZorderIdx;
-      xSetEdgefilterTU( pcCU,nsAddr, uiAbsZorderIdx, uiDepth + 1 );
-    }
+      m_aapucBS[edgeDir][uiBsIdx] = bValue;
+    }
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterTU(  TComTU &rTu )
+{
+  TComDataCU* pcCU  = rTu.getCU();
+  UInt uiTransDepthTotal = rTu.GetTransformDepthTotal();
+
+  if( pcCU->getTransformIdx( rTu.GetAbsPartIdxTU() ) + pcCU->getDepth( rTu.GetAbsPartIdxTU()) > uiTransDepthTotal )
+  {
+    TComTURecurse tuChild(rTu, false);
+    do
+    {
+      xSetEdgefilterTU( tuChild );
+    } while (tuChild.nextSection(rTu));
     return;
   }
 
-  Int trWidth  = pcCU->getWidth( uiAbsZorderIdx ) >> pcCU->getTransformIdx( uiAbsZorderIdx );
-  Int trHeight = pcCU->getHeight( uiAbsZorderIdx ) >> pcCU->getTransformIdx( uiAbsZorderIdx );
-  
-  UInt uiWidthInBaseUnits  = trWidth / (g_uiMaxCUWidth >> g_uiMaxCUDepth);
-  UInt uiHeightInBaseUnits = trHeight / (g_uiMaxCUWidth >> g_uiMaxCUDepth);
-
-  xSetEdgefilterMultiple( pcCU, absTUPartIdx, uiDepth, EDGE_VER, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits );
-  xSetEdgefilterMultiple( pcCU, absTUPartIdx, uiDepth, EDGE_HOR, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits );
+  const TComRectangle &rect = rTu.getRect(COMPONENT_Y);
+  const TComSPS &sps=*(pcCU->getSlice()->getSPS());
+
+  const UInt uiWidthInBaseUnits  = rect.width  / (sps.getMaxCUWidth()  >> sps.getMaxTotalCUDepth());
+  const UInt uiHeightInBaseUnits = rect.height / (sps.getMaxCUHeight() >> sps.getMaxTotalCUDepth());
+
+  xSetEdgefilterMultiple( pcCU, rTu.GetAbsPartIdxCU(), uiTransDepthTotal, EDGE_VER, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits, &rect );
+  xSetEdgefilterMultiple( pcCU, rTu.GetAbsPartIdxCU(), uiTransDepthTotal, EDGE_HOR, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits, &rect );
 }
 
@@ -279,14 +300,14 @@
 {
   const UInt uiDepth = pcCU->getDepth( uiAbsZorderIdx );
-  const UInt uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
-  const UInt uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> uiDepth;
+  const UInt uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInCtuWidth () >> uiDepth;
+  const UInt uiHeightInBaseUnits = pcCU->getPic()->getNumPartInCtuHeight() >> uiDepth;
   const UInt uiHWidthInBaseUnits  = uiWidthInBaseUnits  >> 1;
   const UInt uiHHeightInBaseUnits = uiHeightInBaseUnits >> 1;
   const UInt uiQWidthInBaseUnits  = uiWidthInBaseUnits  >> 2;
   const UInt uiQHeightInBaseUnits = uiHeightInBaseUnits >> 2;
-  
+
   xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, 0, m_stLFCUParam.bLeftEdge );
   xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, 0, m_stLFCUParam.bTopEdge );
-  
+
   switch ( pcCU->getPartitionSize( uiAbsZorderIdx ) )
   {
@@ -343,10 +364,10 @@
   UInt uiX           = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsZorderIdx ] ];
   UInt uiY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsZorderIdx ] ];
-  
+
   TComDataCU* pcTempCU;
   UInt        uiTempPartIdx;
 
   m_stLFCUParam.bInternalEdge = ! pcCU->getSlice()->getDeblockingFilterDisable();
-  
+
   if ( (uiX == 0) || pcCU->getSlice()->getDeblockingFilterDisable() )
   {
@@ -360,5 +381,6 @@
   {
     pcTempCU = pcCU->getPULeft( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
-    if ( pcTempCU )
+
+    if ( pcTempCU != NULL )
     {
       m_stLFCUParam.bLeftEdge = true;
@@ -369,5 +391,5 @@
     }
   }
-  
+
   if ( (uiY == 0 ) || pcCU->getSlice()->getDeblockingFilterDisable() )
   {
@@ -382,5 +404,5 @@
     pcTempCU = pcCU->getPUAbove( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
 
-    if ( pcTempCU )
+    if ( pcTempCU != NULL )
     {
       m_stLFCUParam.bTopEdge = true;
@@ -393,25 +415,27 @@
 }
 
-Void TComLoopFilter::xGetBoundaryStrengthSingle ( TComDataCU* pcCU, Int iDir, UInt uiAbsPartIdx )
-{
-  TComSlice* const pcSlice = pcCU->getSlice();
-  
-  const UInt uiPartQ = uiAbsPartIdx;
-  TComDataCU* const pcCUQ = pcCU;
-  
+Void TComLoopFilter::xGetBoundaryStrengthSingle ( TComDataCU* pCtu, DeblockEdgeDir edgeDir, UInt uiAbsPartIdx4x4BlockWithinCtu )
+{
+  TComSlice * const pcSlice = pCtu->getSlice();
+
+  const Bool lfCrossSliceBoundaryFlag=pCtu->getSlice()->getLFCrossSliceBoundaryFlag();
+
+  const UInt uiPartQ = uiAbsPartIdx4x4BlockWithinCtu;
+  TComDataCU* const pcCUQ = pCtu;
+
   UInt uiPartP;
   TComDataCU* pcCUP;
   UInt uiBs = 0;
-  
+
   //-- Calculate Block Index
-  if (iDir == EDGE_VER)
-  {
-    pcCUP = pcCUQ->getPULeft(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
-  }
-  else  // (iDir == EDGE_HOR)
-  {
-    pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
-  }
-  
+  if (edgeDir == EDGE_VER)
+  {
+    pcCUP = pcCUQ->getPULeft(uiPartP, uiPartQ, !lfCrossSliceBoundaryFlag, !m_bLFCrossTileBoundary);
+  }
+  else  // (edgeDir == EDGE_HOR)
+  {
+    pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pCtu->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+  }
+
   //-- Set BS for Intra MB : BS = 4 or 3
   if ( pcCUP->isIntra(uiPartP) || pcCUQ->isIntra(uiPartQ) )
@@ -419,5 +443,5 @@
     uiBs = 2;
   }
-  
+
   //-- Set BS for not Intra MB : BS = 2 or 1 or 0
   if ( !pcCUP->isIntra(uiPartP) && !pcCUQ->isIntra(uiPartQ) )
@@ -425,6 +449,6 @@
     UInt nsPartQ = uiPartQ;
     UInt nsPartP = uiPartP;
-    
-    if ( m_aapucBS[iDir][uiAbsPartIdx] && (pcCUQ->getCbf( nsPartQ, TEXT_LUMA, pcCUQ->getTransformIdx(nsPartQ)) != 0 || pcCUP->getCbf( nsPartP, TEXT_LUMA, pcCUP->getTransformIdx(nsPartP) ) != 0) )
+
+    if ( m_aapucBS[edgeDir][uiAbsPartIdx4x4BlockWithinCtu] && (pcCUQ->getCbf( nsPartQ, COMPONENT_Y, pcCUQ->getTransformIdx(nsPartQ)) != 0 || pcCUP->getCbf( nsPartP, COMPONENT_Y, pcCUP->getTransformIdx(nsPartP) ) != 0) )
     {
       uiBs = 1;
@@ -432,8 +456,4 @@
     else
     {
-      if (iDir == EDGE_HOR)
-      {
-        pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
-      }
       if (pcSlice->isInterB() || pcCUP->getSlice()->isInterB())
       {
@@ -448,5 +468,5 @@
         iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartQ);
         piRefQ1 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx);
-        
+
         TComMv pcMvP0 = pcCUP->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartP);
         TComMv pcMvP1 = pcCUP->getCUMvField(REF_PIC_LIST_1)->getMv(uiPartP);
@@ -454,8 +474,20 @@
         TComMv pcMvQ1 = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getMv(uiPartQ);
 
-        if (piRefP0 == NULL) pcMvP0.setZero();
-        if (piRefP1 == NULL) pcMvP1.setZero();
-        if (piRefQ0 == NULL) pcMvQ0.setZero();
-        if (piRefQ1 == NULL) pcMvQ1.setZero();
+        if (piRefP0 == NULL)
+        {
+          pcMvP0.setZero();
+        }
+        if (piRefP1 == NULL)
+        {
+          pcMvP1.setZero();
+        }
+        if (piRefQ0 == NULL)
+        {
+          pcMvQ0.setZero();
+        }
+        if (piRefQ1 == NULL)
+        {
+          pcMvQ1.setZero();
+        }
 
         if ( ((piRefP0==piRefQ0)&&(piRefP1==piRefQ1)) || ((piRefP0==piRefQ1)&&(piRefP1==piRefQ0)) )
@@ -506,7 +538,13 @@
         TComMv pcMvQ0 = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartQ);
 
-        if (piRefP0 == NULL) pcMvP0.setZero();
-        if (piRefQ0 == NULL) pcMvQ0.setZero();
-        
+        if (piRefP0 == NULL)
+        {
+          pcMvP0.setZero();
+        }
+        if (piRefQ0 == NULL)
+        {
+          pcMvQ0.setZero();
+        }
+
         uiBs  = ((piRefP0 != piRefQ0) ||
                  (abs(pcMvQ0.getHor() - pcMvP0.getHor()) >= 4) ||
@@ -515,36 +553,40 @@
     }   // enf of "if( one of BCBP == 0 )"
   }   // enf of "if( not Intra )"
-  
-  m_aapucBS[iDir][uiAbsPartIdx] = uiBs;
-}
-
-
-Void TComLoopFilter::xEdgeFilterLuma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge  )
-{
-  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
-  Pel* piSrc    = pcPicYuvRec->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx );
-  Pel* piTmpSrc = piSrc;
-  
-  Int  iStride = pcPicYuvRec->getStride();
+
+  m_aapucBS[edgeDir][uiAbsPartIdx4x4BlockWithinCtu] = uiBs;
+}
+
+
+Void TComLoopFilter::xEdgeFilterLuma( TComDataCU* const pcCU, const UInt uiAbsZorderIdx, const UInt uiDepth, const DeblockEdgeDir edgeDir, const Int iEdge  )
+{
+        TComPicYuv *pcPicYuvRec                   = pcCU->getPic()->getPicYuvRec();
+        Pel        *piSrc                         = pcPicYuvRec->getAddr(COMPONENT_Y, pcCU->getCtuRsAddr(), uiAbsZorderIdx );
+        Pel        *piTmpSrc                      = piSrc;
+  const TComSPS    &sps                           = *(pcCU->getSlice()->getSPS());
+  const Bool        ppsTransquantBypassEnableFlag = pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag();
+  const Int         bitDepthLuma                  = sps.getBitDepth(CHANNEL_TYPE_LUMA);
+  const Bool        lfCrossSliceBoundaryFlag      = pcCU->getSlice()->getLFCrossSliceBoundaryFlag();
+
+  Int  iStride = pcPicYuvRec->getStride(COMPONENT_Y);
   Int iQP = 0;
   Int iQP_P = 0;
   Int iQP_Q = 0;
-  UInt uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
-  
-  UInt  uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt uiNumParts = pcCU->getPic()->getNumPartInCtuWidth()>>uiDepth;
+
+  UInt  uiPelsInPart = sps.getMaxCUWidth() >> sps.getMaxTotalCUDepth();
   UInt  uiBsAbsIdx = 0, uiBs = 0;
   Int   iOffset, iSrcStep;
-  
-  Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
+
+  Bool  bPCMFilter = (sps.getUsePCM() && sps.getPCMFilterDisableFlag())? true : false;
   Bool  bPartPNoFilter = false;
-  Bool  bPartQNoFilter = false; 
+  Bool  bPartQNoFilter = false;
   UInt  uiPartPIdx = 0;
   UInt  uiPartQIdx = 0;
-  TComDataCU* pcCUP = pcCU; 
+  TComDataCU* pcCUP = pcCU;
   TComDataCU* pcCUQ = pcCU;
   Int  betaOffsetDiv2 = pcCUQ->getSlice()->getDeblockingFilterBetaOffsetDiv2();
   Int  tcOffsetDiv2 = pcCUQ->getSlice()->getDeblockingFilterTcOffsetDiv2();
 
-  if (iDir == EDGE_VER)
+  if (edgeDir == EDGE_VER)
   {
     iOffset = 1;
@@ -552,5 +594,5 @@
     piTmpSrc += iEdge*uiPelsInPart;
   }
-  else  // (iDir == EDGE_HOR)
+  else  // (edgeDir == EDGE_HOR)
   {
     iOffset = iStride;
@@ -558,9 +600,11 @@
     piTmpSrc += iEdge*uiPelsInPart*iStride;
   }
-  
+
+  const Int iBitdepthScale = 1 << (bitDepthLuma-8);
+
   for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
   {
-    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
-    uiBs = m_aapucBS[iDir][uiBsAbsIdx];
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, edgeDir, iEdge, iIdx);
+    uiBs = m_aapucBS[edgeDir][uiBsAbsIdx];
     if ( uiBs )
     {
@@ -568,24 +612,24 @@
       uiPartQIdx = uiBsAbsIdx;
       // Derive neighboring PU index
-      if (iDir == EDGE_VER)
-      {
-        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
+      if (edgeDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!lfCrossSliceBoundaryFlag, !m_bLFCrossTileBoundary);
       }
       else  // (iDir == EDGE_HOR)
       {
-        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!lfCrossSliceBoundaryFlag, false, !m_bLFCrossTileBoundary);
       }
 
       iQP_P = pcCUP->getQP(uiPartPIdx);
       iQP = (iQP_P + iQP_Q + 1) >> 1;
-      Int iBitdepthScale = 1 << (g_bitDepthY-8);
-      
+
       Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, Int(iQP + DEFAULT_INTRA_TC_OFFSET*(uiBs-1) + (tcOffsetDiv2 << 1)));
       Int iIndexB = Clip3(0, MAX_QP, iQP + (betaOffsetDiv2 << 1));
-      
+
       Int iTc =  sm_tcTable[iIndexTC]*iBitdepthScale;
       Int iBeta = sm_betaTable[iIndexB]*iBitdepthScale;
       Int iSideThreshold = (iBeta+(iBeta>>1))>>3;
       Int iThrCut = iTc*10;
+
 
       UInt  uiBlocksInPart = uiPelsInPart / 4 ? uiPelsInPart / 4 : 1;
@@ -598,10 +642,10 @@
         Int d0 = dp0 + dq0;
         Int d3 = dp3 + dq3;
-        
+
         Int dp = dp0 + dp3;
         Int dq = dq0 + dq3;
         Int d =  d0 + d3;
-        
-        if (bPCMFilter || pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+
+        if (bPCMFilter || ppsTransquantBypassEnableFlag)
         {
           // Check if each of PUs is I_PCM with LF disabling
@@ -615,14 +659,14 @@
 
         if (d < iBeta)
-        { 
+        {
           Bool bFilterP = (dp < iSideThreshold);
           Bool bFilterQ = (dq < iSideThreshold);
-          
+
           Bool sw =  xUseStrongFiltering( iOffset, 2*d0, iBeta, iTc, piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+0))
           && xUseStrongFiltering( iOffset, 2*d3, iBeta, iTc, piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+3));
-          
+
           for ( Int i = 0; i < DEBLOCK_SMALLEST_BLOCK/2; i++)
           {
-            xPelFilterLuma( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+i), iOffset, iTc, sw, bPartPNoFilter, bPartQNoFilter, iThrCut, bFilterP, bFilterQ);
+            xPelFilterLuma( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+i), iOffset, iTc, sw, bPartPNoFilter, bPartQNoFilter, iThrCut, bFilterP, bFilterQ, bitDepthLuma);
           }
         }
@@ -633,83 +677,99 @@
 
 
-Void TComLoopFilter::xEdgeFilterChroma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge )
-{
-  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
-  Int         iStride     = pcPicYuvRec->getCStride();
-  Pel*        piSrcCb     = pcPicYuvRec->getCbAddr( pcCU->getAddr(), uiAbsZorderIdx );
-  Pel*        piSrcCr     = pcPicYuvRec->getCrAddr( pcCU->getAddr(), uiAbsZorderIdx );
+Void TComLoopFilter::xEdgeFilterChroma( TComDataCU* const pcCU, const UInt uiAbsZorderIdx, const UInt uiDepth, const DeblockEdgeDir edgeDir, const Int iEdge )
+{
+        TComPicYuv *pcPicYuvRec    = pcCU->getPic()->getPicYuvRec();
+        Int         iStride        = pcPicYuvRec->getStride(COMPONENT_Cb);
+        Pel        *piSrcCb        = pcPicYuvRec->getAddr( COMPONENT_Cb, pcCU->getCtuRsAddr(), uiAbsZorderIdx );
+        Pel        *piSrcCr        = pcPicYuvRec->getAddr( COMPONENT_Cr, pcCU->getCtuRsAddr(), uiAbsZorderIdx );
+  const TComSPS    &sps            = *(pcCU->getSlice()->getSPS());
+  const Int         bitDepthChroma = sps.getBitDepth(CHANNEL_TYPE_CHROMA);
+
+  const UInt  uiPelsInPartChromaH = sps.getMaxCUWidth() >> (sps.getMaxTotalCUDepth()+pcPicYuvRec->getComponentScaleX(COMPONENT_Cb));
+  const UInt  uiPelsInPartChromaV = sps.getMaxCUHeight() >> (sps.getMaxTotalCUDepth()+pcPicYuvRec->getComponentScaleY(COMPONENT_Cb));
+
   Int iQP = 0;
   Int iQP_P = 0;
   Int iQP_Q = 0;
-  
-  UInt  uiPelsInPartChroma = g_uiMaxCUWidth >> (g_uiMaxCUDepth+1);
-  
+
   Int   iOffset, iSrcStep;
-  
-  const UInt uiLCUWidthInBaseUnits = pcCU->getPic()->getNumPartInWidth();
-  
+  UInt  uiLoopLength;
+
+  const UInt uiCtuWidthInBaseUnits = pcCU->getPic()->getNumPartInCtuWidth();
+
   Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
   Bool  bPartPNoFilter = false;
-  Bool  bPartQNoFilter = false; 
-  UInt  uiPartPIdx;
-  UInt  uiPartQIdx;
-  TComDataCU* pcCUP; 
+  Bool  bPartQNoFilter = false;
   TComDataCU* pcCUQ = pcCU;
   Int tcOffsetDiv2 = pcCU->getSlice()->getDeblockingFilterTcOffsetDiv2();
-  
+
   // Vertical Position
-  UInt uiEdgeNumInLCUVert = g_auiZscanToRaster[uiAbsZorderIdx]%uiLCUWidthInBaseUnits + iEdge;
-  UInt uiEdgeNumInLCUHor = g_auiZscanToRaster[uiAbsZorderIdx]/uiLCUWidthInBaseUnits + iEdge;
-  
-  if ( (uiPelsInPartChroma < DEBLOCK_SMALLEST_BLOCK) && (( (uiEdgeNumInLCUVert%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChroma))&&(iDir==0) ) || ( (uiEdgeNumInLCUHor%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChroma))&& iDir ) ))
+  UInt uiEdgeNumInCtuVert = g_auiZscanToRaster[uiAbsZorderIdx]%uiCtuWidthInBaseUnits + iEdge;
+  UInt uiEdgeNumInCtuHor = g_auiZscanToRaster[uiAbsZorderIdx]/uiCtuWidthInBaseUnits + iEdge;
+
+  if ( (uiPelsInPartChromaH < DEBLOCK_SMALLEST_BLOCK) && (uiPelsInPartChromaV < DEBLOCK_SMALLEST_BLOCK) &&
+       (
+         ( (uiEdgeNumInCtuVert%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChromaH)) && (edgeDir==EDGE_VER) ) ||
+         ( (uiEdgeNumInCtuHor %(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChromaV)) && (edgeDir==EDGE_HOR) )
+       )
+     )
   {
     return;
   }
-  
-  UInt  uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
-  
+
+
+  const Bool lfCrossSliceBoundaryFlag=pcCU->getSlice()->getLFCrossSliceBoundaryFlag();
+
+  UInt  uiNumParts = pcCU->getPic()->getNumPartInCtuWidth()>>uiDepth;
+
   UInt  uiBsAbsIdx;
   UChar ucBs;
-  
+
   Pel* piTmpSrcCb = piSrcCb;
   Pel* piTmpSrcCr = piSrcCr;
-  
-  
-  if (iDir == EDGE_VER)
+
+  if (edgeDir == EDGE_VER)
   {
     iOffset   = 1;
     iSrcStep  = iStride;
-    piTmpSrcCb += iEdge*uiPelsInPartChroma;
-    piTmpSrcCr += iEdge*uiPelsInPartChroma;
-  }
-  else  // (iDir == EDGE_HOR)
+    piTmpSrcCb += iEdge*uiPelsInPartChromaH;
+    piTmpSrcCr += iEdge*uiPelsInPartChromaH;
+    uiLoopLength=uiPelsInPartChromaV;
+  }
+  else  // (edgeDir == EDGE_HOR)
   {
     iOffset   = iStride;
     iSrcStep  = 1;
-    piTmpSrcCb += iEdge*iStride*uiPelsInPartChroma;
-    piTmpSrcCr += iEdge*iStride*uiPelsInPartChroma;
-  }
-  
+    piTmpSrcCb += iEdge*iStride*uiPelsInPartChromaV;
+    piTmpSrcCr += iEdge*iStride*uiPelsInPartChromaV;
+    uiLoopLength=uiPelsInPartChromaH;
+  }
+
+  const Int iBitdepthScale = 1 << (pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_CHROMA)-8);
+
   for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
   {
-    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
-    ucBs = m_aapucBS[iDir][uiBsAbsIdx];
-    
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, edgeDir, iEdge, iIdx);
+    ucBs = m_aapucBS[edgeDir][uiBsAbsIdx];
+
     if ( ucBs > 1)
     {
       iQP_Q = pcCU->getQP( uiBsAbsIdx );
-      uiPartQIdx = uiBsAbsIdx;
+      UInt  uiPartQIdx = uiBsAbsIdx;
       // Derive neighboring PU index
-      if (iDir == EDGE_VER)
-      {
-        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
-      }
-      else  // (iDir == EDGE_HOR)
-      {
-        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+      TComDataCU* pcCUP;
+      UInt  uiPartPIdx;
+
+      if (edgeDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!lfCrossSliceBoundaryFlag, !m_bLFCrossTileBoundary);
+      }
+      else  // (edgeDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!lfCrossSliceBoundaryFlag, false, !m_bLFCrossTileBoundary);
       }
 
       iQP_P = pcCUP->getQP(uiPartPIdx);
-      
+
       if (bPCMFilter || pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
       {
@@ -722,19 +782,33 @@
         bPartQNoFilter = bPartQNoFilter || (pcCUQ->isLosslessCoded(uiPartQIdx));
       }
-      
+
       for ( UInt chromaIdx = 0; chromaIdx < 2; chromaIdx++ )
       {
-        Int chromaQPOffset  = (chromaIdx == 0) ? pcCU->getSlice()->getPPS()->getChromaCbQpOffset() : pcCU->getSlice()->getPPS()->getChromaCrQpOffset();
+        Int chromaQPOffset  = pcCU->getSlice()->getPPS()->getQpOffset(ComponentID(chromaIdx + 1));
         Pel* piTmpSrcChroma = (chromaIdx == 0) ? piTmpSrcCb : piTmpSrcCr;
 
-        iQP = QpUV( ((iQP_P + iQP_Q + 1) >> 1) + chromaQPOffset );
-        Int iBitdepthScale = 1 << (g_bitDepthC-8);
+        iQP = ((iQP_P + iQP_Q + 1) >> 1) + chromaQPOffset;
+        if (iQP >= chromaQPMappingTableSize)
+        {
+          if (pcPicYuvRec->getChromaFormat()==CHROMA_420)
+          {
+            iQP -=6;
+          }
+          else if (iQP>51)
+          {
+            iQP=51;
+          }
+        }
+        else if (iQP >= 0 )
+        {
+          iQP = getScaledChromaQP(iQP, pcPicYuvRec->getChromaFormat());
+        }
 
         Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, iQP + DEFAULT_INTRA_TC_OFFSET*(ucBs - 1) + (tcOffsetDiv2 << 1));
         Int iTc =  sm_tcTable[iIndexTC]*iBitdepthScale;
 
-        for ( UInt uiStep = 0; uiStep < uiPelsInPartChroma; uiStep++ )
-        {
-          xPelFilterChroma( piTmpSrcChroma + iSrcStep*(uiStep+iIdx*uiPelsInPartChroma), iOffset, iTc , bPartPNoFilter, bPartQNoFilter);
+        for ( UInt uiStep = 0; uiStep < uiLoopLength; uiStep++ )
+        {
+          xPelFilterChroma( piTmpSrcChroma + iSrcStep*(uiStep+iIdx*uiLoopLength), iOffset, iTc , bPartPNoFilter, bPartQNoFilter, bitDepthChroma);
         }
       }
@@ -755,9 +829,10 @@
  \param bFilterSecondP  decision weak filter/no filter for partP
  \param bFilterSecondQ  decision weak filter/no filter for partQ
+ \param bitDepthLuma    luma bit depth
 */
-__inline Void TComLoopFilter::xPelFilterLuma( Pel* piSrc, Int iOffset, Int tc , Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ)
+__inline Void TComLoopFilter::xPelFilterLuma( Pel* piSrc, Int iOffset, Int tc, Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ, const Int bitDepthLuma)
 {
   Int delta;
-  
+
   Pel m4  = piSrc[0];
   Pel m3  = piSrc[-iOffset];
@@ -785,7 +860,7 @@
     if ( abs(delta) < iThrCut )
     {
-      delta = Clip3(-tc, tc, delta);        
-      piSrc[-iOffset] = ClipY((m3+delta));
-      piSrc[0] = ClipY((m4-delta));
+      delta = Clip3(-tc, tc, delta);
+      piSrc[-iOffset] = ClipBD((m3+delta), bitDepthLuma);
+      piSrc[0] = ClipBD((m4-delta), bitDepthLuma);
 
       Int tc2 = tc>>1;
@@ -793,10 +868,10 @@
       {
         Int delta1 = Clip3(-tc2, tc2, (( ((m1+m3+1)>>1)- m2+delta)>>1));
-        piSrc[-iOffset*2] = ClipY((m2+delta1));
+        piSrc[-iOffset*2] = ClipBD((m2+delta1), bitDepthLuma);
       }
       if(bFilterSecondQ)
       {
         Int delta2 = Clip3(-tc2, tc2, (( ((m6+m4+1)>>1)- m5-delta)>>1));
-        piSrc[ iOffset] = ClipY((m5+delta2));
+        piSrc[ iOffset] = ClipBD((m5+delta2), bitDepthLuma);
       }
     }
@@ -825,17 +900,18 @@
  \param bPartPNoFilter  indicator to disable filtering on partP
  \param bPartQNoFilter  indicator to disable filtering on partQ
+ \param bitDepthChroma  chroma bit depth
  */
-__inline Void TComLoopFilter::xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter)
+__inline Void TComLoopFilter::xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter, const Int bitDepthChroma)
 {
   Int delta;
-  
+
   Pel m4  = piSrc[0];
   Pel m3  = piSrc[-iOffset];
   Pel m5  = piSrc[ iOffset];
   Pel m2  = piSrc[-iOffset*2];
-  
+
   delta = Clip3(-tc,tc, (((( m4 - m3 ) << 2 ) + m2 - m5 + 4 ) >> 3) );
-  piSrc[-iOffset] = ClipC(m3+delta);
-  piSrc[0] = ClipC(m4-delta);
+  piSrc[-iOffset] = ClipBD((m3+delta), bitDepthChroma);
+  piSrc[0] = ClipBD((m4-delta), bitDepthChroma);
 
   if(bPartPNoFilter)
@@ -874,5 +950,5 @@
   return abs( piSrc[-iOffset*3] - 2*piSrc[-iOffset*2] + piSrc[-iOffset] ) ;
 }
-  
+
 __inline Int TComLoopFilter::xCalcDQ( Pel* piSrc, Int iOffset)
 {
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComLoopFilter.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComLoopFilter.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -55,48 +55,65 @@
 {
 private:
+
   UInt      m_uiNumPartitions;
-  UChar*    m_aapucBS[2];              ///< Bs for [Ver/Hor][Y/U/V][Blk_Idx]
-  Bool*     m_aapbEdgeFilter[2];
-  LFCUParam m_stLFCUParam;                  ///< status structure
-  
+  UChar*    m_aapucBS[NUM_EDGE_DIR];         ///< Bs for [Ver/Hor][Y/U/V][Blk_Idx]
+  Bool*     m_aapbEdgeFilter[NUM_EDGE_DIR];
+  LFCUParam m_stLFCUParam;                   ///< status structure
+
   Bool      m_bLFCrossTileBoundary;
 
 protected:
   /// CU-level deblocking function
-  Void xDeblockCU                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge );
+  Void xDeblockCU                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, DeblockEdgeDir edgeDir );
 
   // set / get functions
   Void xSetLoopfilterParam        ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
   // filtering functions
-  Void xSetEdgefilterTU           ( TComDataCU* pcCU, UInt absTUPartIdx, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void xSetEdgefilterTU           ( TComTU &rTu );
   Void xSetEdgefilterPU           ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
-  Void xGetBoundaryStrengthSingle ( TComDataCU* pcCU, Int iDir, UInt uiPartIdx );
-  UInt xCalcBsIdx                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, Int iEdgeIdx, Int iBaseUnitIdx )
+  Void xGetBoundaryStrengthSingle ( TComDataCU* pCtu, DeblockEdgeDir edgeDir, UInt uiPartIdx );
+  UInt xCalcBsIdx                 ( TComDataCU* pcCU, UInt absZIdxInCtu, DeblockEdgeDir edgeDir, Int iEdgeIdx, Int iBaseUnitIdx, const struct TComRectangle *rect=NULL )
   {
     TComPic* const pcPic = pcCU->getPic();
-    const UInt uiLCUWidthInBaseUnits = pcPic->getNumPartInWidth();
-    if( iDir == 0 )
+    const UInt ctuWidthInBaseUnits = pcPic->getNumPartInCtuWidth();
+    Int rasterOffsetTU=0;
+    if (rect != NULL)
     {
-      return g_auiRasterToZscan[g_auiZscanToRaster[uiAbsZorderIdx] + iBaseUnitIdx * uiLCUWidthInBaseUnits + iEdgeIdx ];
+      const UInt minCuWidth =pcPic->getMinCUWidth();
+      const UInt minCuHeight=pcPic->getMinCUHeight();
+      rasterOffsetTU = rect->x0/minCuWidth + (rect->y0/minCuHeight)*ctuWidthInBaseUnits;
+    }
+    if( edgeDir == EDGE_VER )
+    {
+      return g_auiRasterToZscan[g_auiZscanToRaster[absZIdxInCtu] + iBaseUnitIdx * ctuWidthInBaseUnits + iEdgeIdx + rasterOffsetTU ];
     }
     else
     {
-      return g_auiRasterToZscan[g_auiZscanToRaster[uiAbsZorderIdx] + iEdgeIdx * uiLCUWidthInBaseUnits + iBaseUnitIdx ];
+      return g_auiRasterToZscan[g_auiZscanToRaster[absZIdxInCtu] + iEdgeIdx * ctuWidthInBaseUnits + iBaseUnitIdx + rasterOffsetTU ];
     }
-  } 
-  
-  Void xSetEdgefilterMultiple( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdgeIdx, Bool bValue ,UInt uiWidthInBaseUnits = 0, UInt uiHeightInBaseUnits = 0 );
-  
-  Void xEdgeFilterLuma            ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge );
-  Void xEdgeFilterChroma          ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge );
-  
-  __inline Void xPelFilterLuma( Pel* piSrc, Int iOffset, Int tc, Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ);
-  __inline Void xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter);
-  
+  }
+
+  Void xSetEdgefilterMultiple( TComDataCU* pcCU,
+                               UInt uiAbsZorderIdx,
+                               UInt uiDepth,
+                               DeblockEdgeDir edgeDir,
+                               Int iEdgeIdx,
+                               Bool bValue,
+                               UInt uiWidthInBaseUnits = 0,
+                               UInt uiHeightInBaseUnits = 0,
+                               const TComRectangle *rect = 0
+                               );
+
+  Void xEdgeFilterLuma            ( TComDataCU* const pcCU, const UInt uiAbsZorderIdx, const UInt uiDepth, const DeblockEdgeDir edgeDir, const Int iEdge );
+  Void xEdgeFilterChroma          ( TComDataCU* const pcCU, const UInt uiAbsZorderIdx, const UInt uiDepth, const DeblockEdgeDir edgeDir, const Int iEdge );
+
+  __inline Void xPelFilterLuma( Pel* piSrc, Int iOffset, Int tc, Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ, const Int bitDepthLuma);
+  __inline Void xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter, const Int bitDepthChroma);
+
 
   __inline Bool xUseStrongFiltering( Int offset, Int d, Int beta, Int tc, Pel* piSrc);
   __inline Int xCalcDP( Pel* piSrc, Int iOffset);
   __inline Int xCalcDQ( Pel* piSrc, Int iOffset);
-  
+
   static const UChar sm_tcTable[54];
   static const UChar sm_betaTable[52];
@@ -105,11 +122,11 @@
   TComLoopFilter();
   virtual ~TComLoopFilter();
-  
+
   Void  create                    ( UInt uiMaxCUDepth );
   Void  destroy                   ();
-  
+
   /// set configuration
   Void setCfg( Bool bLFCrossTileBoundary );
-  
+
   /// picture-level deblocking filter
   Void loopFilterPic( TComPic* pcPic );
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -61,9 +61,9 @@
   assert(m_pcMvd    == NULL);
   assert(m_piRefIdx == NULL);
-  
+
   m_pcMv     = new TComMv[ uiNumPartition ];
   m_pcMvd    = new TComMv[ uiNumPartition ];
   m_piRefIdx = new Char  [ uiNumPartition ];
-  
+
   m_uiNumPartition = uiNumPartition;
 }
@@ -74,13 +74,13 @@
   assert(m_pcMvd    != NULL);
   assert(m_piRefIdx != NULL);
-  
+
   delete[] m_pcMv;
   delete[] m_pcMvd;
   delete[] m_piRefIdx;
-  
+
   m_pcMv     = NULL;
   m_pcMvd    = NULL;
   m_piRefIdx = NULL;
-  
+
   m_uiNumPartition = 0;
 }
@@ -95,5 +95,5 @@
   {
     m_pcMv [ i ].setZero();
-    m_pcMvd[ i ].setZero();      
+    m_pcMvd[ i ].setZero();
   }
   assert( sizeof( *m_piRefIdx ) == 1 );
@@ -104,5 +104,5 @@
 {
   Int iSizeInTComMv = sizeof( TComMv ) * iNumPartSrc;
-  
+
   memcpy( m_pcMv     + iPartAddrDst, pcCUMvFieldSrc->m_pcMv,     iSizeInTComMv );
   memcpy( m_pcMvd    + iPartAddrDst, pcCUMvFieldSrc->m_pcMvd,    iSizeInTComMv );
@@ -119,5 +119,5 @@
   Int iSizeInTComMv = sizeof( TComMv ) * uiNumPart;
   Int iOffset = uiOffset + iPartAddrDst;
-  
+
   memcpy( pcCUMvFieldDst->m_pcMv     + iOffset, m_pcMv     + uiOffset, iSizeInTComMv );
   memcpy( pcCUMvFieldDst->m_pcMvd    + iOffset, m_pcMvd    + uiOffset, iSizeInTComMv );
@@ -135,5 +135,5 @@
   p += iPartAddr;
   Int numElements = m_uiNumPartition >> ( 2 * uiDepth );
-  
+
   switch( eCUMode )
   {
@@ -144,5 +144,5 @@
       }
       break;
-      
+
     case SIZE_2NxN:
       numElements >>= 1;
@@ -152,5 +152,5 @@
       }
       break;
-      
+
     case SIZE_Nx2N:
       numElements >>= 2;
@@ -161,5 +161,5 @@
       }
       break;
-      
+
     case SIZE_NxN:
       numElements >>= 2;
@@ -360,13 +360,12 @@
   Int N = scale * scale;
   assert( N > 0 && N <= m_uiNumPartition);
-  
+
   for ( Int uiPartIdx = 0; uiPartIdx < m_uiNumPartition; uiPartIdx += N )
   {
-    TComMv cMv(0,0); 
-    PredMode predMode = MODE_INTRA;
+    TComMv cMv(0,0);
     Int iRefIdx = 0;
-    
+
     cMv = m_pcMv[ uiPartIdx ];
-    predMode = static_cast<PredMode>( pePredMode[ uiPartIdx ] );
+    PredMode predMode = static_cast<PredMode>( pePredMode[ uiPartIdx ] );
     iRefIdx = m_piRefIdx[ uiPartIdx ];
     for ( Int i = 0; i < N; i++ )
@@ -377,4 +376,4 @@
     }
   }
-} 
+}
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComMv.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComMv.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComMv.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -40,5 +40,7 @@
 
 #include "CommonDef.h"
+#if NH_3D
 #include <cstdlib>
+#endif
 
 //! \ingroup TLibCommon
@@ -62,9 +64,9 @@
 #endif
 public:
-  
+
   // ------------------------------------------------------------------------------------------------------------------
   // constructors
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   TComMv() :
   m_iHor(0),
@@ -78,5 +80,5 @@
   {
   }
-  
+
   TComMv( Short iHor, Short iVer ) :
   m_iHor(iHor),
@@ -90,18 +92,18 @@
   {
   }
-  
+
   // ------------------------------------------------------------------------------------------------------------------
   // set
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   Void  set       ( Short iHor, Short iVer)     { m_iHor = iHor;  m_iVer = iVer;            }
   Void  setHor    ( Short i )                   { m_iHor = i;                               }
   Void  setVer    ( Short i )                   { m_iVer = i;                               }
-  Void  setZero   ()                            { m_iHor = m_iVer = 0;  
+  Void  setZero   ()                            { m_iHor = m_iVer = 0; 
  #if H_3D_NBDV
    m_bIDV = false; m_iIDVHor = m_iIDVVer = 0;
    m_iIDVVId = 0; 
 #endif
-  }
+ }
 #if H_3D_NBDV
   Void   setIDVHor  (Short i)                    {m_iIDVHor = i;}
@@ -113,5 +115,5 @@
   // get
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   Int   getHor    () const { return m_iHor;          }
   Int   getVer    () const { return m_iVer;          }
@@ -128,5 +130,5 @@
   // operations
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   const TComMv& operator += (const TComMv& rcMv)
   {
@@ -135,5 +137,5 @@
     return  *this;
   }
-  
+
   const TComMv& operator-= (const TComMv& rcMv)
   {
@@ -142,5 +144,5 @@
     return  *this;
   }
-  
+
   const TComMv& operator>>= (const Int i)
   {
@@ -149,5 +151,5 @@
     return  *this;
   }
-  
+
   const TComMv& operator<<= (const Int i)
   {
@@ -156,25 +158,25 @@
     return  *this;
   }
-  
+
   const TComMv operator - ( const TComMv& rcMv ) const
   {
     return TComMv( m_iHor - rcMv.m_iHor, m_iVer - rcMv.m_iVer );
   }
-  
+
   const TComMv operator + ( const TComMv& rcMv ) const
   {
     return TComMv( m_iHor + rcMv.m_iHor, m_iVer + rcMv.m_iVer );
   }
-  
+
   Bool operator== ( const TComMv& rcMv ) const
   {
     return (m_iHor==rcMv.m_iHor && m_iVer==rcMv.m_iVer);
   }
-  
+
   Bool operator!= ( const TComMv& rcMv ) const
   {
     return (m_iHor!=rcMv.m_iHor || m_iVer!=rcMv.m_iVer);
   }
-  
+
   const TComMv scaleMv( Int iScale ) const
   {
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPattern.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPattern.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,20 +39,37 @@
 #include "TComPattern.h"
 #include "TComDataCU.h"
+#include "TComTU.h"
+#include "Debug.h"
+#include "TComPrediction.h"
 
 //! \ingroup TLibCommon
 //! \{
 
-// ====================================================================================================================
-// Tables
-// ====================================================================================================================
-
-const UChar TComPattern::m_aucIntraFilter[5] =
-{
-  10, //4x4
-  7, //8x8
-  1, //16x16
-  0, //32x32
-  10, //64x64
-};
+// Forward declarations
+
+/// padding of unavailable reference samples for intra prediction
+Void fillReferenceSamples( const Int bitDepth, 
+#if O0043_BEST_EFFORT_DECODING
+                           const Int bitDepthDelta, 
+#endif
+                           const Pel* piRoiOrigin, 
+                                 Pel* piIntraTemp,
+                           const Bool* bNeighborFlags,
+                           const Int iNumIntraNeighbor, 
+                           const Int unitWidth, 
+                           const Int unitHeight, 
+                           const Int iAboveUnits, 
+                           const Int iLeftUnits,
+                           const UInt uiWidth, 
+                           const UInt uiHeight, 
+                           const Int iPicStride );
+
+/// constrained intra prediction
+Bool  isAboveLeftAvailable  ( TComDataCU* pcCU, UInt uiPartIdxLT );
+Int   isAboveAvailable      ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
+Int   isLeftAvailable       ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
+Int   isAboveRightAvailable ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
+Int   isBelowLeftAvailable  ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
+
 
 // ====================================================================================================================
@@ -60,10 +77,10 @@
 // ====================================================================================================================
 
-/** \param  piTexture     pixel data
+/** 
+ \param  piTexture     pixel data
  \param  iRoiWidth     pattern width
  \param  iRoiHeight    pattern height
  \param  iStride       buffer stride
- \param  iOffsetLeft   neighbour offset (left)
- \param  iOffsetAbove  neighbour offset (above)
+ \param  bitDepth      bit depth
  */
 Void TComPatternParam::setPatternParamPel ( Pel* piTexture,
@@ -71,58 +88,12 @@
                                            Int iRoiHeight,
                                            Int iStride,
-                                           Int iOffsetLeft,
-                                           Int iOffsetAbove )
-{
-  m_piPatternOrigin = piTexture;
-  m_iROIWidth       = iRoiWidth;
-  m_iROIHeight      = iRoiHeight;
-  m_iPatternStride  = iStride;
-  m_iOffsetLeft     = iOffsetLeft;
-  m_iOffsetAbove    = iOffsetAbove;
-}
-
-/**
- \param  pcCU          CU data structure
- \param  iComp         component index (0=Y, 1=Cb, 2=Cr)
- \param  iRoiWidth     pattern width
- \param  iRoiHeight    pattern height
- \param  iStride       buffer stride
- \param  iOffsetLeft   neighbour offset (left)
- \param  iOffsetAbove  neighbour offset (above)
- \param  uiAbsPartIdx  part index
- */
-Void TComPatternParam::setPatternParamCU( TComDataCU* pcCU,
-                                         UChar       iComp,
-                                         UChar       iRoiWidth,
-                                         UChar       iRoiHeight,
-                                         Int         iOffsetLeft,
-                                         Int         iOffsetAbove,
-                                         UInt        uiAbsPartIdx )
-{
-  m_iOffsetLeft   = iOffsetLeft;
-  m_iOffsetAbove  = iOffsetAbove;
-  
-  m_iROIWidth     = iRoiWidth;
-  m_iROIHeight    = iRoiHeight;
-  
-  UInt uiAbsZorderIdx = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-  
-  if ( iComp == 0 )
-  {
-    m_iPatternStride  = pcCU->getPic()->getStride();
-    m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
-  }
-  else
-  {
-    m_iPatternStride = pcCU->getPic()->getCStride();
-    if ( iComp == 1 )
-    {
-      m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
-    }
-    else
-    {
-      m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
-    }
-  }
+                                           Int bitDepth
+                                           )
+{
+  m_piROIOrigin    = piTexture;
+  m_iROIWidth      = iRoiWidth;
+  m_iROIHeight     = iRoiHeight;
+  m_iPatternStride = iStride;
+  m_bitDepth       = bitDepth;
 }
 
@@ -131,247 +102,245 @@
 // ====================================================================================================================
 
-Void TComPattern::initPattern ( Pel* piY,
-                               Pel* piCb,
-                               Pel* piCr,
+Void TComPattern::initPattern (Pel* piY,
                                Int iRoiWidth,
                                Int iRoiHeight,
                                Int iStride,
-                               Int iOffsetLeft,
-                               Int iOffsetAbove )
-{
-  m_cPatternY. setPatternParamPel( piY,  iRoiWidth,      iRoiHeight,      iStride,      iOffsetLeft,      iOffsetAbove      );
-  m_cPatternCb.setPatternParamPel( piCb, iRoiWidth >> 1, iRoiHeight >> 1, iStride >> 1, iOffsetLeft >> 1, iOffsetAbove >> 1 );
-  m_cPatternCr.setPatternParamPel( piCr, iRoiWidth >> 1, iRoiHeight >> 1, iStride >> 1, iOffsetLeft >> 1, iOffsetAbove >> 1 );
-  
-  return;
-}
-
-Void TComPattern::initPattern( TComDataCU* pcCU, UInt uiPartDepth, UInt uiAbsPartIdx )
-{
-  Int   uiOffsetLeft  = 0;
-  Int   uiOffsetAbove = 0;
-  
-  UChar uiWidth          = pcCU->getWidth (0)>>uiPartDepth;
-  UChar uiHeight         = pcCU->getHeight(0)>>uiPartDepth;
-  
-  UInt  uiAbsZorderIdx   = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-  UInt  uiCurrPicPelX    = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
-  UInt  uiCurrPicPelY    = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
-  
-  if( uiCurrPicPelX != 0 )
-  {
-    uiOffsetLeft = 1;
-  }
-  
-  if( uiCurrPicPelY != 0 )
-  {
-    uiOffsetAbove = 1;
-  }
-  
-  m_cPatternY .setPatternParamCU( pcCU, 0, uiWidth,      uiHeight,      uiOffsetLeft, uiOffsetAbove, uiAbsPartIdx );
-  m_cPatternCb.setPatternParamCU( pcCU, 1, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetAbove, uiAbsPartIdx );
-  m_cPatternCr.setPatternParamCU( pcCU, 2, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetAbove, uiAbsPartIdx );
-}
-
-Void TComPattern::initAdiPattern( TComDataCU* pcCU, UInt uiZorderIdxInPart, UInt uiPartDepth, Int* piAdiBuf, Int iOrgBufStride, Int iOrgBufHeight, Bool& bAbove, Bool& bLeft, Bool bLMmode )
-{
-  Pel*  piRoiOrigin;
-  Int*  piAdiTemp;
-  UInt  uiCuWidth   = pcCU->getWidth(0) >> uiPartDepth;
-  UInt  uiCuHeight  = pcCU->getHeight(0)>> uiPartDepth;
-  UInt  uiCuWidth2  = uiCuWidth<<1;
-  UInt  uiCuHeight2 = uiCuHeight<<1;
-  UInt  uiWidth;
-  UInt  uiHeight;
-  Int   iPicStride = pcCU->getPic()->getStride();
-  Int   iUnitSize = 0;
-  Int   iNumUnitsInCu = 0;
-  Int   iTotalUnits = 0;
-  Bool  bNeighborFlags[4 * MAX_NUM_SPU_W + 1];
+                               Int bitDepthLuma)
+{
+  m_cPatternY. setPatternParamPel( piY,  iRoiWidth, iRoiHeight, iStride, bitDepthLuma);
+}
+
+
+// TODO: move this function to TComPrediction.cpp.
+Void TComPrediction::initIntraPatternChType( TComTU &rTu, Bool& bAbove, Bool& bLeft, const ComponentID compID, const Bool bFilterRefSamples DEBUG_STRING_FN_DECLARE(sDebug))
+{
+  const ChannelType chType    = toChannelType(compID);
+
+  TComDataCU *pcCU=rTu.getCU();
+  const TComSPS &sps = *(pcCU->getSlice()->getSPS());
+  const UInt uiZorderIdxInPart=rTu.GetAbsPartIdxTU();
+  const UInt uiTuWidth        = rTu.getRect(compID).width;
+  const UInt uiTuHeight       = rTu.getRect(compID).height;
+  const UInt uiTuWidth2       = uiTuWidth  << 1;
+  const UInt uiTuHeight2      = uiTuHeight << 1;
+
+  const Int  iBaseUnitSize    = sps.getMaxCUWidth() >> sps.getMaxTotalCUDepth();
+  const Int  iUnitWidth       = iBaseUnitSize  >> pcCU->getPic()->getPicYuvRec()->getComponentScaleX(compID);
+  const Int  iUnitHeight      = iBaseUnitSize  >> pcCU->getPic()->getPicYuvRec()->getComponentScaleY(compID);
+  const Int  iTUWidthInUnits  = uiTuWidth  / iUnitWidth;
+  const Int  iTUHeightInUnits = uiTuHeight / iUnitHeight;
+  const Int  iAboveUnits      = iTUWidthInUnits  << 1;
+  const Int  iLeftUnits       = iTUHeightInUnits << 1;
+  const Int  bitDepthForChannel = sps.getBitDepth(chType);
+
+  assert(iTUHeightInUnits > 0 && iTUWidthInUnits > 0);
+
+  const Int  iPartIdxStride   = pcCU->getPic()->getNumPartInCtuWidth();
+  const UInt uiPartIdxLT      = pcCU->getZorderIdxInCtu() + uiZorderIdxInPart;
+  const UInt uiPartIdxRT      = g_auiRasterToZscan[ g_auiZscanToRaster[ uiPartIdxLT ] +   iTUWidthInUnits  - 1                   ];
+  const UInt uiPartIdxLB      = g_auiRasterToZscan[ g_auiZscanToRaster[ uiPartIdxLT ] + ((iTUHeightInUnits - 1) * iPartIdxStride)];
+
+  Int   iPicStride = pcCU->getPic()->getStride(compID);
+  Bool  bNeighborFlags[4 * MAX_NUM_PART_IDXS_IN_CTU_WIDTH + 1];
   Int   iNumIntraNeighbor = 0;
-  
-  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
-
-  
-  pcCU->deriveLeftRightTopIdxAdi( uiPartIdxLT, uiPartIdxRT, uiZorderIdxInPart, uiPartDepth );
-  pcCU->deriveLeftBottomIdxAdi  ( uiPartIdxLB,              uiZorderIdxInPart, uiPartDepth );
-  
-  iUnitSize      = g_uiMaxCUWidth >> g_uiMaxCUDepth;
-  iNumUnitsInCu  = uiCuWidth / iUnitSize;
-  iTotalUnits    = (iNumUnitsInCu << 2) + 1;
-
-  bNeighborFlags[iNumUnitsInCu*2] = isAboveLeftAvailable( pcCU, uiPartIdxLT );
-  iNumIntraNeighbor  += (Int)(bNeighborFlags[iNumUnitsInCu*2]);
-  iNumIntraNeighbor  += isAboveAvailable     ( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*2)+1 );
-  iNumIntraNeighbor  += isAboveRightAvailable( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*3)+1 );
-  iNumIntraNeighbor  += isLeftAvailable      ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+(iNumUnitsInCu*2)-1 );
-  iNumIntraNeighbor  += isBelowLeftAvailable ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+ iNumUnitsInCu   -1 );
-  
+
+  bNeighborFlags[iLeftUnits] = isAboveLeftAvailable( pcCU, uiPartIdxLT );
+  iNumIntraNeighbor += bNeighborFlags[iLeftUnits] ? 1 : 0;
+  iNumIntraNeighbor  += isAboveAvailable     ( pcCU, uiPartIdxLT, uiPartIdxRT, (bNeighborFlags + iLeftUnits + 1)                    );
+  iNumIntraNeighbor  += isAboveRightAvailable( pcCU, uiPartIdxLT, uiPartIdxRT, (bNeighborFlags + iLeftUnits + 1 + iTUWidthInUnits ) );
+  iNumIntraNeighbor  += isLeftAvailable      ( pcCU, uiPartIdxLT, uiPartIdxLB, (bNeighborFlags + iLeftUnits - 1)                    );
+  iNumIntraNeighbor  += isBelowLeftAvailable ( pcCU, uiPartIdxLT, uiPartIdxLB, (bNeighborFlags + iLeftUnits - 1 - iTUHeightInUnits) );
+
   bAbove = true;
   bLeft  = true;
 
-  uiWidth=uiCuWidth2+1;
-  uiHeight=uiCuHeight2+1;
-  
-  if (((uiWidth<<2)>iOrgBufStride)||((uiHeight<<2)>iOrgBufHeight))
-  {
-    return;
-  }
-  
-  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
-  piAdiTemp   = piAdiBuf;
-
-  fillReferenceSamples (g_bitDepthY, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, bLMmode);
-  
-  Int   i;
-  // generate filtered intra prediction samples
-  Int iBufSize = uiCuHeight2 + uiCuWidth2 + 1;  // left and left above border + above and above right border + top left corner = length of 3. filter buffer
-
-  UInt uiWH = uiWidth * uiHeight;               // number of elements in one buffer
-
-  Int* piFilteredBuf1 = piAdiBuf + uiWH;        // 1. filter buffer
-  Int* piFilteredBuf2 = piFilteredBuf1 + uiWH;  // 2. filter buffer
-  Int* piFilterBuf = piFilteredBuf2 + uiWH;     // buffer for 2. filtering (sequential)
-  Int* piFilterBufN = piFilterBuf + iBufSize;   // buffer for 1. filtering (sequential)
-
-  Int l = 0;
-  // left border from bottom to top
-  for (i = 0; i < uiCuHeight2; i++)
-  {
-    piFilterBuf[l++] = piAdiTemp[uiWidth * (uiCuHeight2 - i)];
-  }
-  // top left corner
-  piFilterBuf[l++] = piAdiTemp[0];
-  // above border from left to right
-  for (i=0; i < uiCuWidth2; i++)
-  {
-    piFilterBuf[l++] = piAdiTemp[1 + i];
-  }
-
-  if (pcCU->getSlice()->getSPS()->getUseStrongIntraSmoothing())
-  {
-    Int blkSize = 32;
-    Int bottomLeft = piFilterBuf[0];
-    Int topLeft = piFilterBuf[uiCuHeight2];
-    Int topRight = piFilterBuf[iBufSize-1];
-    Int threshold = 1 << (g_bitDepthY - 5);
-    Bool bilinearLeft = abs(bottomLeft+topLeft-2*piFilterBuf[uiCuHeight]) < threshold;
-    Bool bilinearAbove  = abs(topLeft+topRight-2*piFilterBuf[uiCuHeight2+uiCuHeight]) < threshold;
-  
-    if (uiCuWidth>=blkSize && (bilinearLeft && bilinearAbove))
-    {
-      Int shift = g_aucConvertToBit[uiCuWidth] + 3;  // log2(uiCuHeight2)
-      piFilterBufN[0] = piFilterBuf[0];
-      piFilterBufN[uiCuHeight2] = piFilterBuf[uiCuHeight2];
-      piFilterBufN[iBufSize - 1] = piFilterBuf[iBufSize - 1];
-      for (i = 1; i < uiCuHeight2; i++)
-      {
-        piFilterBufN[i] = ((uiCuHeight2-i)*bottomLeft + i*topLeft + uiCuHeight) >> shift;
-      }
-  
-      for (i = 1; i < uiCuWidth2; i++)
-      {
-        piFilterBufN[uiCuHeight2 + i] = ((uiCuWidth2-i)*topLeft + i*topRight + uiCuWidth) >> shift;
-      }
-    }
-    else 
-    {
-      // 1. filtering with [1 2 1]
-      piFilterBufN[0] = piFilterBuf[0];
-      piFilterBufN[iBufSize - 1] = piFilterBuf[iBufSize - 1];
-      for (i = 1; i < iBufSize - 1; i++)
-      {
-        piFilterBufN[i] = (piFilterBuf[i - 1] + 2 * piFilterBuf[i]+piFilterBuf[i + 1] + 2) >> 2;
-      }
-    }
-  }
-  else 
-  {
-    // 1. filtering with [1 2 1]
-    piFilterBufN[0] = piFilterBuf[0];
-    piFilterBufN[iBufSize - 1] = piFilterBuf[iBufSize - 1];
-    for (i = 1; i < iBufSize - 1; i++)
-    {
-      piFilterBufN[i] = (piFilterBuf[i - 1] + 2 * piFilterBuf[i]+piFilterBuf[i + 1] + 2) >> 2;
-    }
-  }
-
-  // fill 1. filter buffer with filtered values
-  l=0;
-  for (i = 0; i < uiCuHeight2; i++)
-  {
-    piFilteredBuf1[uiWidth * (uiCuHeight2 - i)] = piFilterBufN[l++];
-  }
-  piFilteredBuf1[0] = piFilterBufN[l++];
-  for (i = 0; i < uiCuWidth2; i++)
-  {
-    piFilteredBuf1[1 + i] = piFilterBufN[l++];
-  }
-}
-
-Void TComPattern::initAdiPatternChroma( TComDataCU* pcCU, UInt uiZorderIdxInPart, UInt uiPartDepth, Int* piAdiBuf, Int iOrgBufStride, Int iOrgBufHeight, Bool& bAbove, Bool& bLeft )
-{
-  Pel*  piRoiOrigin;
-  Int*  piAdiTemp;
-  UInt  uiCuWidth  = pcCU->getWidth (0) >> uiPartDepth;
-  UInt  uiCuHeight = pcCU->getHeight(0) >> uiPartDepth;
-  UInt  uiWidth;
-  UInt  uiHeight;
-  Int   iPicStride = pcCU->getPic()->getCStride();
-
-  Int   iUnitSize = 0;
-  Int   iNumUnitsInCu = 0;
-  Int   iTotalUnits = 0;
-  Bool  bNeighborFlags[4 * MAX_NUM_SPU_W + 1];
-  Int   iNumIntraNeighbor = 0;
-  
-  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
-  
-  pcCU->deriveLeftRightTopIdxAdi( uiPartIdxLT, uiPartIdxRT, uiZorderIdxInPart, uiPartDepth );
-  pcCU->deriveLeftBottomIdxAdi  ( uiPartIdxLB,              uiZorderIdxInPart, uiPartDepth );
-  
-  iUnitSize      = (g_uiMaxCUWidth >> g_uiMaxCUDepth) >> 1; // for chroma
-  iNumUnitsInCu  = (uiCuWidth / iUnitSize) >> 1;            // for chroma
-  iTotalUnits    = (iNumUnitsInCu << 2) + 1;
-
-  bNeighborFlags[iNumUnitsInCu*2] = isAboveLeftAvailable( pcCU, uiPartIdxLT );
-  iNumIntraNeighbor  += (Int)(bNeighborFlags[iNumUnitsInCu*2]);
-  iNumIntraNeighbor  += isAboveAvailable     ( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*2)+1 );
-  iNumIntraNeighbor  += isAboveRightAvailable( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*3)+1 );
-  iNumIntraNeighbor  += isLeftAvailable      ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+(iNumUnitsInCu*2)-1 );
-  iNumIntraNeighbor  += isBelowLeftAvailable ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+ iNumUnitsInCu   -1 );
-  
-  bAbove = true;
-  bLeft  = true;
-  
-  uiCuWidth=uiCuWidth>>1;  // for chroma
-  uiCuHeight=uiCuHeight>>1;  // for chroma
-  
-  uiWidth=uiCuWidth*2+1;
-  uiHeight=uiCuHeight*2+1;
-  
-  if ((4*uiWidth>iOrgBufStride)||(4*uiHeight>iOrgBufHeight))
-  {
-    return;
-  }
-  
-  // get Cb pattern
-  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
-  piAdiTemp   = piAdiBuf;
-
-  fillReferenceSamples (g_bitDepthC, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride);
-  
-  // get Cr pattern
-  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
-  piAdiTemp   = piAdiBuf+uiWidth*uiHeight;
-  
-  fillReferenceSamples (g_bitDepthC, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride);
-}
-
-Void TComPattern::fillReferenceSamples(Int bitDepth, Pel* piRoiOrigin, Int* piAdiTemp, Bool* bNeighborFlags, Int iNumIntraNeighbor, Int iUnitSize, Int iNumUnitsInCu, Int iTotalUnits, UInt uiCuWidth, UInt uiCuHeight, UInt uiWidth, UInt uiHeight, Int iPicStride, Bool bLMmode )
-{
-  Pel* piRoiTemp;
+  const UInt         uiROIWidth  = uiTuWidth2+1;
+  const UInt         uiROIHeight = uiTuHeight2+1;
+
+  assert(uiROIWidth*uiROIHeight <= m_iYuvExtSize);
+
+#if DEBUG_STRING
+  std::stringstream ss(stringstream::out);
+#endif
+
+  {
+    Pel *piIntraTemp   = m_piYuvExt[compID][PRED_BUF_UNFILTERED];
+    Pel *piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu()+uiZorderIdxInPart);
+#if O0043_BEST_EFFORT_DECODING
+    const Int  bitDepthForChannelInStream = sps.getStreamBitDepth(chType);
+    fillReferenceSamples (bitDepthForChannelInStream, bitDepthForChannelInStream - bitDepthForChannel,
+#else
+    fillReferenceSamples (bitDepthForChannel,
+#endif
+                          piRoiOrigin, piIntraTemp, bNeighborFlags, iNumIntraNeighbor,  iUnitWidth, iUnitHeight, iAboveUnits, iLeftUnits,
+                          uiROIWidth, uiROIHeight, iPicStride);
+
+
+#if DEBUG_STRING
+    if (DebugOptionList::DebugString_Pred.getInt()&DebugStringGetPredModeMask(MODE_INTRA))
+    {
+      ss << "###: generating Ref Samples for channel " << compID << " and " << rTu.getRect(compID).width << " x " << rTu.getRect(compID).height << "\n";
+      for (UInt y=0; y<uiROIHeight; y++)
+      {
+        ss << "###: - ";
+        for (UInt x=0; x<uiROIWidth; x++)
+        {
+          if (x==0 || y==0)
+          {
+            ss << piIntraTemp[y*uiROIWidth + x] << ", ";
+//          if (x%16==15) ss << "\nPart size: ~ ";
+          }
+        }
+        ss << "\n";
+      }
+    }
+#endif
+
+    if (bFilterRefSamples)
+    {
+      // generate filtered intra prediction samples
+
+            Int          stride    = uiROIWidth;
+      const Pel         *piSrcPtr  = piIntraTemp                           + (stride * uiTuHeight2); // bottom left
+            Pel         *piDestPtr = m_piYuvExt[compID][PRED_BUF_FILTERED] + (stride * uiTuHeight2); // bottom left
+
+      //------------------------------------------------
+
+      Bool useStrongIntraSmoothing = isLuma(chType) && sps.getUseStrongIntraSmoothing();
+
+      const Pel bottomLeft = piIntraTemp[stride * uiTuHeight2];
+      const Pel topLeft    = piIntraTemp[0];
+      const Pel topRight   = piIntraTemp[uiTuWidth2];
+
+      if (useStrongIntraSmoothing)
+      {
+#if O0043_BEST_EFFORT_DECODING
+        const Int  threshold     = 1 << (bitDepthForChannelInStream - 5);
+#else
+        const Int  threshold     = 1 << (bitDepthForChannel - 5);
+#endif
+        const Bool bilinearLeft  = abs((bottomLeft + topLeft ) - (2 * piIntraTemp[stride * uiTuHeight])) < threshold; //difference between the
+        const Bool bilinearAbove = abs((topLeft    + topRight) - (2 * piIntraTemp[         uiTuWidth ])) < threshold; //ends and the middle
+        if ((uiTuWidth < 32) || (!bilinearLeft) || (!bilinearAbove))
+        {
+          useStrongIntraSmoothing = false;
+        }
+      }
+
+      *piDestPtr = *piSrcPtr; // bottom left is not filtered
+      piDestPtr -= stride;
+      piSrcPtr  -= stride;
+
+      //------------------------------------------------
+
+      //left column (bottom to top)
+
+      if (useStrongIntraSmoothing)
+      {
+        const Int shift = g_aucConvertToBit[uiTuHeight] + 3; //log2(uiTuHeight2)
+
+        for(UInt i=1; i<uiTuHeight2; i++, piDestPtr-=stride)
+        {
+          *piDestPtr = (((uiTuHeight2 - i) * bottomLeft) + (i * topLeft) + uiTuHeight) >> shift;
+        }
+
+        piSrcPtr -= stride * (uiTuHeight2 - 1);
+      }
+      else
+      {
+        for(UInt i=1; i<uiTuHeight2; i++, piDestPtr-=stride, piSrcPtr-=stride)
+        {
+          *piDestPtr = ( piSrcPtr[stride] + 2*piSrcPtr[0] + piSrcPtr[-stride] + 2 ) >> 2;
+        }
+      }
+
+      //------------------------------------------------
+
+      //top-left
+
+      if (useStrongIntraSmoothing)
+      {
+        *piDestPtr = piSrcPtr[0];
+      }
+      else
+      {
+        *piDestPtr = ( piSrcPtr[stride] + 2*piSrcPtr[0] + piSrcPtr[1] + 2 ) >> 2;
+      }
+      piDestPtr += 1;
+      piSrcPtr  += 1;
+
+      //------------------------------------------------
+
+      //top row (left-to-right)
+
+      if (useStrongIntraSmoothing)
+      {
+        const Int shift = g_aucConvertToBit[uiTuWidth] + 3; //log2(uiTuWidth2)
+
+        for(UInt i=1; i<uiTuWidth2; i++, piDestPtr++)
+        {
+          *piDestPtr = (((uiTuWidth2 - i) * topLeft) + (i * topRight) + uiTuWidth) >> shift;
+        }
+
+        piSrcPtr += uiTuWidth2 - 1;
+      }
+      else
+      {
+        for(UInt i=1; i<uiTuWidth2; i++, piDestPtr++, piSrcPtr++)
+        {
+          *piDestPtr = ( piSrcPtr[1] + 2*piSrcPtr[0] + piSrcPtr[-1] + 2 ) >> 2;
+        }
+      }
+
+      //------------------------------------------------
+
+      *piDestPtr=*piSrcPtr; // far right is not filtered
+
+#if DEBUG_STRING
+    if (DebugOptionList::DebugString_Pred.getInt()&DebugStringGetPredModeMask(MODE_INTRA))
+    {
+      ss << "###: filtered result for channel " << compID <<"\n";
+      for (UInt y=0; y<uiROIHeight; y++)
+      {
+        ss << "###: - ";
+        for (UInt x=0; x<uiROIWidth; x++)
+        {
+          if (x==0 || y==0)
+          {
+            ss << m_piYuvExt[compID][PRED_BUF_FILTERED][y*uiROIWidth + x] << ", ";
+//          if (x%16==15) ss << "\nPart size: ~ ";
+          }
+        }
+        ss << "\n";
+      }
+    }
+#endif
+
+
+    }
+  }
+  DEBUG_STRING_APPEND(sDebug, ss.str())
+}
+
+Void fillReferenceSamples( const Int bitDepth, 
+#if O0043_BEST_EFFORT_DECODING
+                           const Int bitDepthDelta, 
+#endif
+                           const Pel* piRoiOrigin, 
+                                 Pel* piIntraTemp,
+                           const Bool* bNeighborFlags,
+                           const Int iNumIntraNeighbor, 
+                           const Int unitWidth, 
+                           const Int unitHeight, 
+                           const Int iAboveUnits, 
+                           const Int iLeftUnits,
+                           const UInt uiWidth, 
+                           const UInt uiHeight, 
+                           const Int iPicStride )
+{
+  const Pel* piRoiTemp;
   Int  i, j;
   Int  iDCValue = 1 << (bitDepth - 1);
+  const Int iTotalUnits = iAboveUnits + iLeftUnits + 1; //+1 for top-left
 
   if (iNumIntraNeighbor == 0)
@@ -380,229 +349,225 @@
     for (i=0; i<uiWidth; i++)
     {
-      piAdiTemp[i] = iDCValue;
+      piIntraTemp[i] = iDCValue;
     }
     for (i=1; i<uiHeight; i++)
     {
-      piAdiTemp[i*uiWidth] = iDCValue;
+      piIntraTemp[i*uiWidth] = iDCValue;
     }
   }
   else if (iNumIntraNeighbor == iTotalUnits)
   {
-    // Fill top-left border with rec. samples
+    // Fill top-left border and top and top right with rec. samples
     piRoiTemp = piRoiOrigin - iPicStride - 1;
-    piAdiTemp[0] = piRoiTemp[0];
-
-    // Fill left border with rec. samples
+
+    for (i=0; i<uiWidth; i++)
+    {
+#if O0043_BEST_EFFORT_DECODING
+      piIntraTemp[i] = piRoiTemp[i] << bitDepthDelta;
+#else
+      piIntraTemp[i] = piRoiTemp[i];
+#endif
+    }
+
+    // Fill left and below left border with rec. samples
     piRoiTemp = piRoiOrigin - 1;
 
-    if (bLMmode)
-    {
-      piRoiTemp --; // move to the second left column
-    }
-
-    for (i=0; i<uiCuHeight; i++)
-    {
-      piAdiTemp[(1+i)*uiWidth] = piRoiTemp[0];
+    for (i=1; i<uiHeight; i++)
+    {
+#if O0043_BEST_EFFORT_DECODING
+      piIntraTemp[i*uiWidth] = (*(piRoiTemp)) << bitDepthDelta;
+#else
+      piIntraTemp[i*uiWidth] = *(piRoiTemp);
+#endif
       piRoiTemp += iPicStride;
     }
-
-    // Fill below left border with rec. samples
-    for (i=0; i<uiCuHeight; i++)
-    {
-      piAdiTemp[(1+uiCuHeight+i)*uiWidth] = piRoiTemp[0];
-      piRoiTemp += iPicStride;
-    }
-
-    // Fill top border with rec. samples
-    piRoiTemp = piRoiOrigin - iPicStride;
-    for (i=0; i<uiCuWidth; i++)
-    {
-      piAdiTemp[1+i] = piRoiTemp[i];
-    }
-    
-    // Fill top right border with rec. samples
-    piRoiTemp = piRoiOrigin - iPicStride + uiCuWidth;
-    for (i=0; i<uiCuWidth; i++)
-    {
-      piAdiTemp[1+uiCuWidth+i] = piRoiTemp[i];
-    }
   }
   else // reference samples are partially available
   {
-    Int  iNumUnits2 = iNumUnitsInCu<<1;
-    Int  iTotalSamples = iTotalUnits*iUnitSize;
-    Pel  piAdiLine[5 * MAX_CU_SIZE];
-    Pel  *piAdiLineTemp; 
-    Bool *pbNeighborFlags;
-    Int  iNext, iCurr;
-    Pel  piRef = 0;
+    // all above units have "unitWidth" samples each, all left/below-left units have "unitHeight" samples each
+    const Int  iTotalSamples = (iLeftUnits * unitHeight) + ((iAboveUnits + 1) * unitWidth);
+    Pel  piIntraLine[5 * MAX_CU_SIZE];
+    Pel  *piIntraLineTemp;
+    const Bool *pbNeighborFlags;
+
 
     // Initialize
     for (i=0; i<iTotalSamples; i++)
     {
-      piAdiLine[i] = iDCValue;
-    }
-    
+      piIntraLine[i] = iDCValue;
+    }
+
     // Fill top-left sample
     piRoiTemp = piRoiOrigin - iPicStride - 1;
-    piAdiLineTemp = piAdiLine + (iNumUnits2*iUnitSize);
-    pbNeighborFlags = bNeighborFlags + iNumUnits2;
+    piIntraLineTemp = piIntraLine + (iLeftUnits * unitHeight);
+    pbNeighborFlags = bNeighborFlags + iLeftUnits;
     if (*pbNeighborFlags)
     {
-      piAdiLineTemp[0] = piRoiTemp[0];
-      for (i=1; i<iUnitSize; i++)
-      {
-        piAdiLineTemp[i] = piAdiLineTemp[0];
-      }
-    }
-
-    // Fill left & below-left samples
+#if O0043_BEST_EFFORT_DECODING
+      Pel topLeftVal=piRoiTemp[0] << bitDepthDelta;
+#else
+      Pel topLeftVal=piRoiTemp[0];
+#endif
+      for (i=0; i<unitWidth; i++)
+      {
+        piIntraLineTemp[i] = topLeftVal;
+      }
+    }
+
+    // Fill left & below-left samples (downwards)
     piRoiTemp += iPicStride;
-    if (bLMmode)
-    {
-      piRoiTemp --; // move the second left column
-    }
-    piAdiLineTemp--;
+    piIntraLineTemp--;
     pbNeighborFlags--;
-    for (j=0; j<iNumUnits2; j++)
+
+    for (j=0; j<iLeftUnits; j++)
     {
       if (*pbNeighborFlags)
       {
-        for (i=0; i<iUnitSize; i++)
-        {
-          piAdiLineTemp[-i] = piRoiTemp[i*iPicStride];
-        }
-      }
-      piRoiTemp += iUnitSize*iPicStride;
-      piAdiLineTemp -= iUnitSize;
+        for (i=0; i<unitHeight; i++)
+        {
+#if O0043_BEST_EFFORT_DECODING
+          piIntraLineTemp[-i] = piRoiTemp[i*iPicStride] << bitDepthDelta;
+#else
+          piIntraLineTemp[-i] = piRoiTemp[i*iPicStride];
+#endif
+        }
+      }
+      piRoiTemp += unitHeight*iPicStride;
+      piIntraLineTemp -= unitHeight;
       pbNeighborFlags--;
     }
 
-    // Fill above & above-right samples
+    // Fill above & above-right samples (left-to-right) (each unit has "unitWidth" samples)
     piRoiTemp = piRoiOrigin - iPicStride;
-    piAdiLineTemp = piAdiLine + ((iNumUnits2+1)*iUnitSize);
-    pbNeighborFlags = bNeighborFlags + iNumUnits2 + 1;
-    for (j=0; j<iNumUnits2; j++)
+    // offset line buffer by iNumUints2*unitHeight (for left/below-left) + unitWidth (for above-left)
+    piIntraLineTemp = piIntraLine + (iLeftUnits * unitHeight) + unitWidth;
+    pbNeighborFlags = bNeighborFlags + iLeftUnits + 1;
+    for (j=0; j<iAboveUnits; j++)
     {
       if (*pbNeighborFlags)
       {
-        for (i=0; i<iUnitSize; i++)
-        {
-          piAdiLineTemp[i] = piRoiTemp[i];
-        }
-      }
-      piRoiTemp += iUnitSize;
-      piAdiLineTemp += iUnitSize;
+        for (i=0; i<unitWidth; i++)
+        {
+#if O0043_BEST_EFFORT_DECODING
+          piIntraLineTemp[i] = piRoiTemp[i] << bitDepthDelta;
+#else
+          piIntraLineTemp[i] = piRoiTemp[i];
+#endif
+        }
+      }
+      piRoiTemp += unitWidth;
+      piIntraLineTemp += unitWidth;
       pbNeighborFlags++;
     }
 
     // Pad reference samples when necessary
-    iCurr = 0;
-    iNext = 1;
-    piAdiLineTemp = piAdiLine;
-    while (iCurr < iTotalUnits)
-    {
-      if (!bNeighborFlags[iCurr])
-      {
-        if(iCurr == 0)
-        {
-          while (iNext < iTotalUnits && !bNeighborFlags[iNext])
+    Int iCurrJnit = 0;
+    Pel  *piIntraLineCur   = piIntraLine;
+    const UInt piIntraLineTopRowOffset = iLeftUnits * (unitHeight - unitWidth);
+
+    if (!bNeighborFlags[0])
+    {
+      // very bottom unit of bottom-left; at least one unit will be valid.
+      {
+        Int   iNext = 1;
+        while (iNext < iTotalUnits && !bNeighborFlags[iNext])
+        {
+          iNext++;
+        }
+        Pel *piIntraLineNext = piIntraLine + ((iNext < iLeftUnits) ? (iNext * unitHeight) : (piIntraLineTopRowOffset + (iNext * unitWidth)));
+        const Pel refSample = *piIntraLineNext;
+        // Pad unavailable samples with new value
+        Int iNextOrTop = std::min<Int>(iNext, iLeftUnits);
+        // fill left column
+        while (iCurrJnit < iNextOrTop)
+        {
+          for (i=0; i<unitHeight; i++)
           {
-            iNext++;
+            piIntraLineCur[i] = refSample;
           }
-          piRef = piAdiLine[iNext*iUnitSize];
-          // Pad unavailable samples with new value
-          while (iCurr < iNext)
+          piIntraLineCur += unitHeight;
+          iCurrJnit++;
+        }
+        // fill top row
+        while (iCurrJnit < iNext)
+        {
+          for (i=0; i<unitWidth; i++)
           {
-            for (i=0; i<iUnitSize; i++)
-            {
-              piAdiLineTemp[i] = piRef;
-            }
-            piAdiLineTemp += iUnitSize;
-            iCurr++;
+            piIntraLineCur[i] = refSample;
           }
-        }
-        else
-        {
-          piRef = piAdiLine[iCurr*iUnitSize-1];
-          for (i=0; i<iUnitSize; i++)
+          piIntraLineCur += unitWidth;
+          iCurrJnit++;
+        }
+      }
+    }
+
+    // pad all other reference samples.
+    while (iCurrJnit < iTotalUnits)
+    {
+      if (!bNeighborFlags[iCurrJnit]) // samples not available
+      {
+        {
+          const Int numSamplesInCurrUnit = (iCurrJnit >= iLeftUnits) ? unitWidth : unitHeight;
+          const Pel refSample = *(piIntraLineCur-1);
+          for (i=0; i<numSamplesInCurrUnit; i++)
           {
-            piAdiLineTemp[i] = piRef;
+            piIntraLineCur[i] = refSample;
           }
-          piAdiLineTemp += iUnitSize;
-          iCurr++;
-        }
-      }
-      else
-      {
-        piAdiLineTemp += iUnitSize;
-        iCurr++;
+          piIntraLineCur += numSamplesInCurrUnit;
+          iCurrJnit++;
+        }
+      }
+      else
+      {
+        piIntraLineCur += (iCurrJnit >= iLeftUnits) ? unitWidth : unitHeight;
+        iCurrJnit++;
       }
     }
 
     // Copy processed samples
-    piAdiLineTemp = piAdiLine + uiHeight + iUnitSize - 2;
+
+    piIntraLineTemp = piIntraLine + uiHeight + unitWidth - 2;
+    // top left, top and top right samples
     for (i=0; i<uiWidth; i++)
     {
-      piAdiTemp[i] = piAdiLineTemp[i];
-    }
-    piAdiLineTemp = piAdiLine + uiHeight - 1;
+      piIntraTemp[i] = piIntraLineTemp[i];
+    }
+
+    piIntraLineTemp = piIntraLine + uiHeight - 1;
     for (i=1; i<uiHeight; i++)
     {
-      piAdiTemp[i*uiWidth] = piAdiLineTemp[-i];
-    }
-  }
-}
-
-Int* TComPattern::getAdiOrgBuf( Int /*iCuWidth*/, Int /*iCuHeight*/, Int* piAdiBuf)
-{
-  return piAdiBuf;
-}
-
-Int* TComPattern::getAdiCbBuf( Int /*iCuWidth*/, Int /*iCuHeight*/, Int* piAdiBuf)
-{
-  return piAdiBuf;
-}
-
-Int* TComPattern::getAdiCrBuf(Int iCuWidth,Int iCuHeight, Int* piAdiBuf)
-{
-  return piAdiBuf+(iCuWidth*2+1)*(iCuHeight*2+1);
-}
-
-/** Get pointer to reference samples for intra prediction
- * \param uiDirMode   prediction mode index
- * \param log2BlkSize size of block (2 = 4x4, 3 = 8x8, 4 = 16x16, 5 = 32x32, 6 = 64x64)
- * \param piAdiBuf    pointer to unfiltered reference samples
- * \return            pointer to (possibly filtered) reference samples
- *
- * The prediction mode index is used to determine whether a smoothed reference sample buffer is returned.
- */
-Int* TComPattern::getPredictorPtr( UInt uiDirMode, UInt log2BlkSize, Int* piAdiBuf )
-{
-  Int* piSrc;
-  assert(log2BlkSize >= 2 && log2BlkSize < 7);
-  Int diff = min<Int>(abs((Int) uiDirMode - HOR_IDX), abs((Int)uiDirMode - VER_IDX));
-  UChar ucFiltIdx = diff > m_aucIntraFilter[log2BlkSize - 2] ? 1 : 0;
-  if (uiDirMode == DC_IDX)
-  {
-    ucFiltIdx = 0; //no smoothing for DC or LM chroma
-  }
-
-  assert( ucFiltIdx <= 1 );
-
-  Int width  = 1 << log2BlkSize;
-  Int height = 1 << log2BlkSize;
-  
-  piSrc = getAdiOrgBuf( width, height, piAdiBuf );
-
-  if ( ucFiltIdx )
-  {
-    piSrc += (2 * width + 1) * (2 * height + 1);
-  }
-
-  return piSrc;
-}
-
-Bool TComPattern::isAboveLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT )
+      piIntraTemp[i*uiWidth] = piIntraLineTemp[-i];
+    }
+  }
+}
+
+Bool TComPrediction::filteringIntraReferenceSamples(const ComponentID compID, UInt uiDirMode, UInt uiTuChWidth, UInt uiTuChHeight, const ChromaFormat chFmt, const Bool intraReferenceSmoothingDisabled)
+{
+  Bool bFilter;
+
+  if (!filterIntraReferenceSamples(toChannelType(compID), chFmt, intraReferenceSmoothingDisabled))
+  {
+    bFilter=false;
+  }
+  else
+  {
+    assert(uiTuChWidth>=4 && uiTuChHeight>=4 && uiTuChWidth<128 && uiTuChHeight<128);
+
+    if (uiDirMode == DC_IDX)
+    {
+      bFilter=false; //no smoothing for DC or LM chroma
+    }
+    else
+    {
+      Int diff = min<Int>(abs((Int) uiDirMode - HOR_IDX), abs((Int)uiDirMode - VER_IDX));
+      UInt sizeIndex=g_aucConvertToBit[uiTuChWidth];
+      assert(sizeIndex < MAX_INTRA_FILTER_DEPTHS);
+      bFilter = diff > m_aucIntraFilter[toChannelType(compID)][sizeIndex];
+    }
+  }
+  return bFilter;
+}
+
+Bool isAboveLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT )
 {
   Bool bAboveLeftFlag;
@@ -611,5 +576,5 @@
   if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
   {
-    bAboveLeftFlag = ( pcCUAboveLeft && pcCUAboveLeft->getPredictionMode( uiPartAboveLeft ) == MODE_INTRA );
+    bAboveLeftFlag = ( pcCUAboveLeft && pcCUAboveLeft->isIntra( uiPartAboveLeft ) );
   }
   else
@@ -620,5 +585,5 @@
 }
 
-Int TComPattern::isAboveAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+Int isAboveAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
 {
   const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
@@ -634,5 +599,5 @@
     if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
     {
-      if ( pcCUAbove && pcCUAbove->getPredictionMode( uiPartAbove ) == MODE_INTRA )
+      if ( pcCUAbove && pcCUAbove->isIntra( uiPartAbove ) )
       {
         iNumIntra++;
@@ -661,9 +626,9 @@
 }
 
-Int TComPattern::isLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+Int isLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
 {
   const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
   const UInt uiRasterPartEnd = g_auiZscanToRaster[uiPartIdxLB]+1;
-  const UInt uiIdxStep = pcCU->getPic()->getNumPartInWidth();
+  const UInt uiIdxStep = pcCU->getPic()->getNumPartInCtuWidth();
   Bool *pbValidFlags = bValidFlags;
   Int iNumIntra = 0;
@@ -675,5 +640,5 @@
     if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
     {
-      if ( pcCULeft && pcCULeft->getPredictionMode( uiPartLeft ) == MODE_INTRA )
+      if ( pcCULeft && pcCULeft->isIntra( uiPartLeft ) )
       {
         iNumIntra++;
@@ -703,5 +668,5 @@
 }
 
-Int TComPattern::isAboveRightAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+Int isAboveRightAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
 {
   const UInt uiNumUnitsInPU = g_auiZscanToRaster[uiPartIdxRT] - g_auiZscanToRaster[uiPartIdxLT] + 1;
@@ -712,8 +677,8 @@
   {
     UInt uiPartAboveRight;
-    TComDataCU* pcCUAboveRight = pcCU->getPUAboveRightAdi( uiPartAboveRight, uiPartIdxRT, uiOffset );
+    TComDataCU* pcCUAboveRight = pcCU->getPUAboveRight( uiPartAboveRight, uiPartIdxRT, uiOffset );
     if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
     {
-      if ( pcCUAboveRight && pcCUAboveRight->getPredictionMode( uiPartAboveRight ) == MODE_INTRA )
+      if ( pcCUAboveRight && pcCUAboveRight->isIntra( uiPartAboveRight ) )
       {
         iNumIntra++;
@@ -743,7 +708,7 @@
 }
 
-Int TComPattern::isBelowLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
-{
-  const UInt uiNumUnitsInPU = (g_auiZscanToRaster[uiPartIdxLB] - g_auiZscanToRaster[uiPartIdxLT]) / pcCU->getPic()->getNumPartInWidth() + 1;
+Int isBelowLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+{
+  const UInt uiNumUnitsInPU = (g_auiZscanToRaster[uiPartIdxLB] - g_auiZscanToRaster[uiPartIdxLT]) / pcCU->getPic()->getNumPartInCtuWidth() + 1;
   Bool *pbValidFlags = bValidFlags;
   Int iNumIntra = 0;
@@ -752,8 +717,8 @@
   {
     UInt uiPartBelowLeft;
-    TComDataCU* pcCUBelowLeft = pcCU->getPUBelowLeftAdi( uiPartBelowLeft, uiPartIdxLB, uiOffset );
+    TComDataCU* pcCUBelowLeft = pcCU->getPUBelowLeft( uiPartBelowLeft, uiPartIdxLB, uiOffset );
     if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
     {
-      if ( pcCUBelowLeft && pcCUBelowLeft->getPredictionMode( uiPartBelowLeft ) == MODE_INTRA )
+      if ( pcCUBelowLeft && pcCUBelowLeft->isIntra( uiPartBelowLeft ) )
       {
         iNumIntra++;
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPattern.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPattern.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -40,5 +40,4 @@
 
 // Include files
-#include <stdio.h>
 #include "CommonDef.h"
 
@@ -51,4 +50,5 @@
 
 class TComDataCU;
+class TComTU;
 
 /// neighbouring pixel access class for one component
@@ -56,38 +56,20 @@
 {
 private:
-  Int   m_iOffsetLeft;
-  Int   m_iOffsetAbove;
-  Pel*  m_piPatternOrigin;
-  
+  Pel*  m_piROIOrigin;
+
 public:
   Int   m_iROIWidth;
   Int   m_iROIHeight;
   Int   m_iPatternStride;
-  
-  /// return starting position of buffer
-  Pel*  getPatternOrigin()        { return  m_piPatternOrigin; }
-  
+  Int   m_bitDepth;
+
   /// return starting position of ROI (ROI = &pattern[AboveOffset][LeftOffset])
   __inline Pel*  getROIOrigin()
   {
-    return  m_piPatternOrigin + m_iPatternStride * m_iOffsetAbove + m_iOffsetLeft;
+    return  m_piROIOrigin;
   }
-  
+
   /// set parameters from Pel buffer for accessing neighbouring pixels
-  Void setPatternParamPel ( Pel*        piTexture,
-                           Int         iRoiWidth,
-                           Int         iRoiHeight,
-                           Int         iStride,
-                           Int         iOffsetLeft,
-                           Int         iOffsetAbove );
-  
-  /// set parameters of one color component from CU data for accessing neighbouring pixels
-  Void setPatternParamCU  ( TComDataCU* pcCU,
-                           UChar       iComp,
-                           UChar       iRoiWidth,
-                           UChar       iRoiHeight,
-                           Int         iOffsetLeft,
-                           Int         iOffsetAbove,
-                           UInt        uiAbsZorderIdx );
+  Void setPatternParamPel( Pel* piTexture, Int iRoiWidth, Int iRoiHeight, Int iStride, Int bitDepth );
 };
 
@@ -97,6 +79,6 @@
 private:
   TComPatternParam  m_cPatternY;
-  TComPatternParam  m_cPatternCb;
-  TComPatternParam  m_cPatternCr;
+//  TComPatternParam  m_cPatternCb;
+  //TComPatternParam  m_cPatternCr;
 #if H_3D_IC
   Bool              m_bICFlag;
@@ -105,8 +87,8 @@
   Bool              m_bSDCMRSADFlag;
 #endif
-  static const UChar m_aucIntraFilter[5];
-  
+
+
 public:
-  
+
   // ROI & pattern information, (ROI = &pattern[AboveOffset][LeftOffset])
   Pel*  getROIY()                 { return m_cPatternY.getROIOrigin();    }
@@ -114,4 +96,5 @@
   Int   getROIYHeight()           { return m_cPatternY.m_iROIHeight;      }
   Int   getPatternLStride()       { return m_cPatternY.m_iPatternStride;  }
+  Int   getBitDepthY()            { return m_cPatternY.m_bitDepth; }
 
 #if H_3D_IC
@@ -124,64 +107,10 @@
 #endif
 
-  // access functions of ADI buffers
-  Int*  getAdiOrgBuf              ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
-  Int*  getAdiCbBuf               ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
-  Int*  getAdiCrBuf               ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
-  
-  Int*  getPredictorPtr           ( UInt uiDirMode, UInt uiWidthBits, Int* piAdiBuf );
   // -------------------------------------------------------------------------------------------------------------------
   // initialization functions
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   /// set parameters from Pel buffers for accessing neighbouring pixels
-  Void initPattern            ( Pel*        piY,
-                               Pel*        piCb,
-                               Pel*        piCr,
-                               Int         iRoiWidth,
-                               Int         iRoiHeight,
-                               Int         iStride,
-                               Int         iOffsetLeft,
-                               Int         iOffsetAbove );
-  
-  /// set parameters from CU data for accessing neighbouring pixels
-  Void  initPattern           ( TComDataCU* pcCU,
-                               UInt        uiPartDepth,
-                               UInt        uiAbsPartIdx );
-  
-  /// set luma parameters from CU data for accessing ADI data
-  Void  initAdiPattern        ( TComDataCU* pcCU,
-                               UInt        uiZorderIdxInPart,
-                               UInt        uiPartDepth,
-                               Int*        piAdiBuf,
-                               Int         iOrgBufStride,
-                               Int         iOrgBufHeight,
-                               Bool&       bAbove,
-                               Bool&       bLeft
-                              ,Bool        bLMmode = false // using for LM chroma or not
-                               );
-  
-  /// set chroma parameters from CU data for accessing ADI data
-  Void  initAdiPatternChroma  ( TComDataCU* pcCU,
-                               UInt        uiZorderIdxInPart,
-                               UInt        uiPartDepth,
-                               Int*        piAdiBuf,
-                               Int         iOrgBufStride,
-                               Int         iOrgBufHeight,
-                               Bool&       bAbove,
-                               Bool&       bLeft );
-
-private:
-
-  /// padding of unavailable reference samples for intra prediction
-  Void  fillReferenceSamples        (Int bitDepth, Pel* piRoiOrigin, Int* piAdiTemp, Bool* bNeighborFlags, Int iNumIntraNeighbor, Int iUnitSize, Int iNumUnitsInCu, Int iTotalUnits, UInt uiCuWidth, UInt uiCuHeight, UInt uiWidth, UInt uiHeight, Int iPicStride, Bool bLMmode = false);
-  
-
-  /// constrained intra prediction
-  Bool  isAboveLeftAvailable  ( TComDataCU* pcCU, UInt uiPartIdxLT );
-  Int   isAboveAvailable      ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
-  Int   isLeftAvailable       ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
-  Int   isAboveRightAvailable ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
-  Int   isBelowLeftAvailable  ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
-
+  Void initPattern( Pel* piY, Int iRoiWidth, Int iRoiHeight, Int iStride, Int bitDepthLuma );
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPic.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPic.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -50,15 +50,14 @@
 , m_bUsedByCurr                           (false)
 , m_bIsLongTerm                           (false)
-, m_apcPicSym                             (NULL)
 , m_pcPicYuvPred                          (NULL)
 , m_pcPicYuvResi                          (NULL)
 , m_bReconstructed                        (false)
 , m_bNeededForOutput                      (false)
-#if H_MV
+#if NH_MV
 , m_bPicOutputFlag                        (false)
 #endif
 , m_uiCurrSliceIdx                        (0)
 , m_bCheckLTMSB                           (false)
-#if H_MV
+#if NH_MV
 , m_layerId                               (0)
 , m_viewId                                (0)
@@ -70,7 +69,10 @@
 #endif
 #endif
-{
-  m_apcPicYuv[0]      = NULL;
-  m_apcPicYuv[1]      = NULL;
+
+{
+  for(UInt i=0; i<NUM_PIC_YUV; i++)
+  {
+    m_apcPicYuv[i]      = NULL;
+  }
 #if H_3D_QTLPC
   m_bReduceBitsQTL    = 0;
@@ -87,15 +89,21 @@
 }
 
-Void TComPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Window &conformanceWindow, Window &defaultDisplayWindow,
-                      Int *numReorderPics, Bool bIsVirtual)
-
-{
-  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+Void TComPic::create( const TComSPS &sps, const TComPPS &pps, const Bool bIsVirtual)
+{
+  const ChromaFormat chromaFormatIDC = sps.getChromaFormatIdc();
+  const Int          iWidth          = sps.getPicWidthInLumaSamples();
+  const Int          iHeight         = sps.getPicHeightInLumaSamples();
+  const UInt         uiMaxCuWidth    = sps.getMaxCUWidth();
+  const UInt         uiMaxCuHeight   = sps.getMaxCUHeight();
+  const UInt         uiMaxDepth      = sps.getMaxTotalCUDepth();
+
+  m_picSym.create( sps, pps, uiMaxDepth );
   if (!bIsVirtual)
   {
-    m_apcPicYuv[0]  = new TComPicYuv;  m_apcPicYuv[0]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
-  }
-  m_apcPicYuv[1]  = new TComPicYuv;  m_apcPicYuv[1]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
-  
+    m_apcPicYuv[PIC_YUV_ORG    ]   = new TComPicYuv;  m_apcPicYuv[PIC_YUV_ORG     ]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
+    m_apcPicYuv[PIC_YUV_TRUE_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_TRUE_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
+  }
+  m_apcPicYuv[PIC_YUV_REC]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_REC]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
+
   // there are no SEI messages associated with this picture initially
   if (m_SEIs.size() > 0)
@@ -104,13 +112,4 @@
   }
   m_bUsedByCurr = false;
-
-  /* store conformance window parameters with picture */
-  m_conformanceWindow = conformanceWindow;
-  
-  /* store display window parameters with picture */
-  m_defaultDisplayWindow = defaultDisplayWindow;
-
-  /* store number of reorder pics with picture */
-  memcpy(m_numReorderPics, numReorderPics, MAX_TLAYER*sizeof(Int));
 
 #if H_3D_FCO
@@ -125,33 +124,23 @@
 #endif
 
-  return;
 }
 
 Void TComPic::destroy()
 {
-  if (m_apcPicSym)
-  {
-    m_apcPicSym->destroy();
-    delete m_apcPicSym;
-    m_apcPicSym = NULL;
-  }
-  
-  if (m_apcPicYuv[0])
-  {
-    m_apcPicYuv[0]->destroy();
-    delete m_apcPicYuv[0];
-    m_apcPicYuv[0]  = NULL;
-  }
-  
-  if (m_apcPicYuv[1])
-  {
-    m_apcPicYuv[1]->destroy();
-    delete m_apcPicYuv[1];
-    m_apcPicYuv[1]  = NULL;
-  }
-  
+  m_picSym.destroy();
+
+  for(UInt i=0; i<NUM_PIC_YUV; i++)
+  {
+    if (m_apcPicYuv[i])
+    {
+      m_apcPicYuv[i]->destroy();
+      delete m_apcPicYuv[i];
+      m_apcPicYuv[i]  = NULL;
+    }
+  }
+
   deleteSEIs(m_SEIs);
 }
-#if H_3D
+#if NH_3D
 Void TComPic::compressMotion(Int scale)
 #else
@@ -159,24 +148,62 @@
 #endif
 {
-  TComPicSym* pPicSym = getPicSym(); 
-  for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getFrameHeightInCU()*pPicSym->getFrameWidthInCU(); uiCUAddr++ )
-  {
-    TComDataCU* pcCU = pPicSym->getCU(uiCUAddr);
-#if H_3D
-    pcCU->compressMV(scale); 
+  TComPicSym* pPicSym = getPicSym();
+  for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getNumberOfCtusInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pCtu = pPicSym->getCtu(uiCUAddr);
+#if NH_3D
+    pCtu->compressMV(scale); 
 #else
-    pcCU->compressMV(); 
-#endif
-  } 
+    pCtu->compressMV();
+#endif
+    
+  }
 }
 
 Bool  TComPic::getSAOMergeAvailability(Int currAddr, Int mergeAddr)
 {
-  Bool mergeCtbInSliceSeg = (mergeAddr >= getPicSym()->getCUOrderMap(getCU(currAddr)->getSlice()->getSliceCurStartCUAddr()/getNumPartInCU()));
+  Bool mergeCtbInSliceSeg = (mergeAddr >= getPicSym()->getCtuTsToRsAddrMap(getCtu(currAddr)->getSlice()->getSliceCurStartCtuTsAddr()));
   Bool mergeCtbInTile     = (getPicSym()->getTileIdxMap(mergeAddr) == getPicSym()->getTileIdxMap(currAddr));
   return (mergeCtbInSliceSeg && mergeCtbInTile);
 }
 
-#if H_MV
+UInt TComPic::getSubstreamForCtuAddr(const UInt ctuAddr, const Bool bAddressInRaster, TComSlice *pcSlice)
+{
+  UInt subStrm;
+  const bool bWPPEnabled=pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag();
+  const TComPicSym &picSym            = *(getPicSym());
+
+  if ((bWPPEnabled && picSym.getFrameHeightInCtus()>1) || (picSym.getNumTiles()>1)) // wavefronts, and possibly tiles being used.
+  {
+    if (bWPPEnabled)
+    {
+      const UInt ctuRsAddr                = bAddressInRaster?ctuAddr : picSym.getCtuTsToRsAddrMap(ctuAddr);
+      const UInt frameWidthInCtus         = picSym.getFrameWidthInCtus();
+      const UInt tileIndex                = picSym.getTileIdxMap(ctuRsAddr);
+      const UInt numTileColumns           = (picSym.getNumTileColumnsMinus1()+1);
+      const TComTile *pTile               = picSym.getTComTile(tileIndex);
+      const UInt firstCtuRsAddrOfTile     = pTile->getFirstCtuRsAddr();
+      const UInt tileYInCtus              = firstCtuRsAddrOfTile / frameWidthInCtus;
+      // independent tiles => substreams are "per tile"
+      const UInt ctuLine                  = ctuRsAddr / frameWidthInCtus;
+      const UInt startingSubstreamForTile =(tileYInCtus*numTileColumns) + (pTile->getTileHeightInCtus()*(tileIndex%numTileColumns));
+      subStrm = startingSubstreamForTile + (ctuLine - tileYInCtus);
+    }
+    else
+    {
+      const UInt ctuRsAddr                = bAddressInRaster?ctuAddr : picSym.getCtuTsToRsAddrMap(ctuAddr);
+      const UInt tileIndex                = picSym.getTileIdxMap(ctuRsAddr);
+      subStrm=tileIndex;
+    }
+  }
+  else
+  {
+    // dependent tiles => substreams are "per frame".
+    subStrm = 0;
+  }
+  return subStrm;
+}
+
+#if NH_MV
 Void TComPic::print( Bool legend )
 {
@@ -204,5 +231,5 @@
 }
 
-#if H_3D
+#if NH_3D
 TComPic* TComPicLists::getPic( Int viewIndex, Bool depthFlag, Int poc )
 {
@@ -250,5 +277,5 @@
 }
 
-#if H_3D
+#if NH_3D
 TComPicYuv* TComPicLists::getPicYuv( Int viewIndex, Bool depthFlag, Int poc, Bool recon )
 {  
@@ -274,5 +301,5 @@
 #endif
 #endif
-#endif // H_MV
+#endif // NH_MV
 
 #if H_3D_NBDV 
@@ -415,29 +442,28 @@
 #endif
 
-  TComSlice* pcTextSlice = pcTextPic->getSlice(0); // currently only support single slice
-
-  for( Int iTextRefDir = 0; (iTextRefDir < (pcTextSlice->isInterB()? 2:1) ) && !pcTextSlice->isIntra(); iTextRefDir ++ )
-  {
-    for( Int iTextRefIdx =0; iTextRefIdx<pcTextSlice->getNumRefIdx(( RefPicList )iTextRefDir ); iTextRefIdx++)
-    {
-      Int iTextRefPOC    = pcTextSlice->getRefPOC( ( RefPicList )iTextRefDir, iTextRefIdx);
-      Int iTextRefViewId = pcTextSlice->getRefPic( ( RefPicList )iTextRefDir, iTextRefIdx)->getViewIndex();
-      m_aiTexToDepRef[iTextRefDir][iTextRefIdx] = -1;
-      Int iCurrRefDir = iTextRefDir;
-      for( Int iCurrRefIdx =0; ( iCurrRefIdx<pcCurrSlice->getNumRefIdx(( RefPicList )iCurrRefDir ) ) && ( m_aiTexToDepRef[iTextRefDir][iTextRefIdx] < 0 ) ; iCurrRefIdx++)
-      {
-        if( pcCurrSlice->getRefPOC( ( RefPicList )iCurrRefDir, iCurrRefIdx ) == iTextRefPOC && 
-          pcCurrSlice->getRefPic( ( RefPicList )iCurrRefDir, iCurrRefIdx)->getViewIndex() == iTextRefViewId )
-        {  
-          m_aiTexToDepRef[iTextRefDir][iTextRefIdx] = iCurrRefIdx;
+    TComSlice* pcTextSlice = pcTextPic->getSlice(0); // currently only support single slice
+
+    for( Int iTextRefDir = 0; (iTextRefDir < (pcTextSlice->isInterB()? 2:1) ) && !pcTextSlice->isIntra(); iTextRefDir ++ )
+    {
+      for( Int iTextRefIdx =0; iTextRefIdx<pcTextSlice->getNumRefIdx(( RefPicList )iTextRefDir ); iTextRefIdx++)
+      {
+        Int iTextRefPOC    = pcTextSlice->getRefPOC( ( RefPicList )iTextRefDir, iTextRefIdx);
+        Int iTextRefViewId = pcTextSlice->getRefPic( ( RefPicList )iTextRefDir, iTextRefIdx)->getViewIndex();
+        m_aiTexToDepRef[iTextRefDir][iTextRefIdx] = -1;
+        Int iCurrRefDir = iTextRefDir;
+        for( Int iCurrRefIdx =0; ( iCurrRefIdx<pcCurrSlice->getNumRefIdx(( RefPicList )iCurrRefDir ) ) && ( m_aiTexToDepRef[iTextRefDir][iTextRefIdx] < 0 ) ; iCurrRefIdx++)
+        {
+          if( pcCurrSlice->getRefPOC( ( RefPicList )iCurrRefDir, iCurrRefIdx ) == iTextRefPOC && 
+            pcCurrSlice->getRefPic( ( RefPicList )iCurrRefDir, iCurrRefIdx)->getViewIndex() == iTextRefViewId )
+          {  
+            m_aiTexToDepRef[iTextRefDir][iTextRefIdx] = iCurrRefIdx;
+          }
         }
       }
-    }
-
-  }
+
+    }
 #if H_3D_FCO
   }
 #endif
-
 }
 
@@ -447,3 +473,5 @@
 }
 #endif
+
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPic.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPic.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPic.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,5 +36,4 @@
 */
 
-
 #ifndef __TCOMPIC__
 #define __TCOMPIC__
@@ -45,5 +44,4 @@
 #include "TComPicYuv.h"
 #include "TComBitStream.h"
-#include "SEI.h"
 
 //! \ingroup TLibCommon
@@ -55,39 +53,39 @@
 
 /// picture class (symbol + YUV buffers)
+
 class TComPic
 {
+public:
+  typedef enum { PIC_YUV_ORG=0, PIC_YUV_REC=1, PIC_YUV_TRUE_ORG=2, NUM_PIC_YUV=3 } PIC_YUV_T;
+     // TRUE_ORG is the input file without any pre-encoder colour space conversion (but with possible bit depth increment)
+  TComPicYuv*   getPicYuvTrueOrg()        { return  m_apcPicYuv[PIC_YUV_TRUE_ORG]; }
+
 private:
   UInt                  m_uiTLayer;               //  Temporal layer
   Bool                  m_bUsedByCurr;            //  Used by current picture
   Bool                  m_bIsLongTerm;            //  IS long term picture
-  TComPicSym*           m_apcPicSym;              //  Symbol
-  
-  TComPicYuv*           m_apcPicYuv[2];           //  Texture,  0:org / 1:rec
-  
+  TComPicSym            m_picSym;                 //  Symbol
+  TComPicYuv*           m_apcPicYuv[NUM_PIC_YUV];
+
   TComPicYuv*           m_pcPicYuvPred;           //  Prediction
   TComPicYuv*           m_pcPicYuvResi;           //  Residual
   Bool                  m_bReconstructed;
   Bool                  m_bNeededForOutput;
-#if H_MV
+#if NH_MV
   Bool                  m_bPicOutputFlag;         // Semantics variable 
 #endif
   UInt                  m_uiCurrSliceIdx;         // Index of current slice
   Bool                  m_bCheckLTMSB;
-  
-  Int                   m_numReorderPics[MAX_TLAYER];
-  Window                m_conformanceWindow;
-  Window                m_defaultDisplayWindow;
-
-  bool                  m_isTop;
-  bool                  m_isField;
-  
+
+  Bool                  m_isTop;
+  Bool                  m_isField;
+
   std::vector<std::vector<TComDataCU*> > m_vSliceCUDataLink;
 
   SEIMessages  m_SEIs; ///< Any SEI messages that have been received.  If !NULL we own the object.
-
-#if H_MV
+#if NH_MV
   Int                   m_layerId;
   Int                   m_viewId;
-#if H_3D
+#if NH_3D
   Int                   m_viewIndex;
   Bool                  m_isDepth;
@@ -106,22 +104,21 @@
   Int         m_aiTexToDepRef  [2][MAX_NUM_REF];
 #endif
+
 public:
   TComPic();
   virtual ~TComPic();
-  
-  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Window &conformanceWindow, Window &defaultDisplayWindow, 
-                        Int *numReorderPics, Bool bIsVirtual = false );
-                        
+
+  Void          create( const TComSPS &sps, const TComPPS &pps, const Bool bIsVirtual /*= false*/ );
+
   virtual Void  destroy();
-  
-  UInt          getTLayer()                { return m_uiTLayer;   }
+
+  UInt          getTLayer() const               { return m_uiTLayer;   }
   Void          setTLayer( UInt uiTLayer ) { m_uiTLayer = uiTLayer; }
-
-#if H_MV
+#if NH_MV
   Void          setLayerId            ( Int layerId )    { m_layerId      = layerId; }
   Int           getLayerId            ()                 { return m_layerId;    }
   Void          setViewId             ( Int viewId )     { m_viewId = viewId;   }
   Int           getViewId             ()                 { return m_viewId;     }
-#if H_3D
+#if NH_3D
   Void          setViewIndex          ( Int viewIndex )  { m_viewIndex = viewIndex;   }
   Int           getViewIndex          ()                 { return m_viewIndex;     }
@@ -139,74 +136,75 @@
   Void          setReduceBitsFlag ( Bool bFlag ) { m_bReduceBitsQTL = bFlag;    }
 #endif
-  Bool          getUsedByCurr()             { return m_bUsedByCurr; }
+
+  Bool          getUsedByCurr() const            { return m_bUsedByCurr; }
   Void          setUsedByCurr( Bool bUsed ) { m_bUsedByCurr = bUsed; }
-  Bool          getIsLongTerm()             { return m_bIsLongTerm; }
+  Bool          getIsLongTerm() const            { return m_bIsLongTerm; }
   Void          setIsLongTerm( Bool lt ) { m_bIsLongTerm = lt; }
   Void          setCheckLTMSBPresent     (Bool b ) {m_bCheckLTMSB=b;}
   Bool          getCheckLTMSBPresent     () { return m_bCheckLTMSB;}
 
-  TComPicSym*   getPicSym()           { return  m_apcPicSym;    }
-  TComSlice*    getSlice(Int i)       { return  m_apcPicSym->getSlice(i);  }
-  Int           getPOC()              { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getPOC();  }
-  TComDataCU*&  getCU( UInt uiCUAddr )  { return  m_apcPicSym->getCU( uiCUAddr ); }
-  
-  TComPicYuv*   getPicYuvOrg()        { return  m_apcPicYuv[0]; }
-  TComPicYuv*   getPicYuvRec()        { return  m_apcPicYuv[1]; }
-  
+  TComPicSym*   getPicSym()           { return  &m_picSym;    }
+  TComSlice*    getSlice(Int i)       { return  m_picSym.getSlice(i);  }
+  Int           getPOC() const        { return  m_picSym.getSlice(m_uiCurrSliceIdx)->getPOC();  }
+  TComDataCU*   getCtu( UInt ctuRsAddr )           { return  m_picSym.getCtu( ctuRsAddr ); }
+  const TComDataCU* getCtu( UInt ctuRsAddr ) const { return  m_picSym.getCtu( ctuRsAddr ); }
+
+  TComPicYuv*   getPicYuvOrg()        { return  m_apcPicYuv[PIC_YUV_ORG]; }
+  TComPicYuv*   getPicYuvRec()        { return  m_apcPicYuv[PIC_YUV_REC]; }
+
   TComPicYuv*   getPicYuvPred()       { return  m_pcPicYuvPred; }
   TComPicYuv*   getPicYuvResi()       { return  m_pcPicYuvResi; }
   Void          setPicYuvPred( TComPicYuv* pcPicYuv )       { m_pcPicYuvPred = pcPicYuv; }
   Void          setPicYuvResi( TComPicYuv* pcPicYuv )       { m_pcPicYuvResi = pcPicYuv; }
-  
-  UInt          getNumCUsInFrame()      { return m_apcPicSym->getNumberOfCUsInFrame(); }
-  UInt          getNumPartInWidth()     { return m_apcPicSym->getNumPartInWidth();     }
-  UInt          getNumPartInHeight()    { return m_apcPicSym->getNumPartInHeight();    }
-  UInt          getNumPartInCU()        { return m_apcPicSym->getNumPartition();       }
-  UInt          getFrameWidthInCU()     { return m_apcPicSym->getFrameWidthInCU();     }
-  UInt          getFrameHeightInCU()    { return m_apcPicSym->getFrameHeightInCU();    }
-  UInt          getMinCUWidth()         { return m_apcPicSym->getMinCUWidth();         }
-  UInt          getMinCUHeight()        { return m_apcPicSym->getMinCUHeight();        }
-  
-  UInt          getParPelX(UChar uhPartIdx) { return getParPelX(uhPartIdx); }
-  UInt          getParPelY(UChar uhPartIdx) { return getParPelX(uhPartIdx); }
-  
-  Int           getStride()           { return m_apcPicYuv[1]->getStride(); }
-  Int           getCStride()          { return m_apcPicYuv[1]->getCStride(); }
-  
+
+  UInt          getNumberOfCtusInFrame() const     { return m_picSym.getNumberOfCtusInFrame(); }
+  UInt          getNumPartInCtuWidth() const       { return m_picSym.getNumPartInCtuWidth();   }
+  UInt          getNumPartInCtuHeight() const      { return m_picSym.getNumPartInCtuHeight();  }
+  UInt          getNumPartitionsInCtu() const      { return m_picSym.getNumPartitionsInCtu();  }
+  UInt          getFrameWidthInCtus() const        { return m_picSym.getFrameWidthInCtus();    }
+  UInt          getFrameHeightInCtus() const       { return m_picSym.getFrameHeightInCtus();   }
+  UInt          getMinCUWidth() const              { return m_picSym.getMinCUWidth();          }
+  UInt          getMinCUHeight() const             { return m_picSym.getMinCUHeight();         }
+
+  Int           getStride(const ComponentID id) const          { return m_apcPicYuv[PIC_YUV_REC]->getStride(id); }
+  Int           getComponentScaleX(const ComponentID id) const    { return m_apcPicYuv[PIC_YUV_REC]->getComponentScaleX(id); }
+  Int           getComponentScaleY(const ComponentID id) const    { return m_apcPicYuv[PIC_YUV_REC]->getComponentScaleY(id); }
+  ChromaFormat  getChromaFormat() const                           { return m_apcPicYuv[PIC_YUV_REC]->getChromaFormat(); }
+  Int           getNumberValidComponents() const                  { return m_apcPicYuv[PIC_YUV_REC]->getNumberValidComponents(); }
+
   Void          setReconMark (Bool b) { m_bReconstructed = b;     }
-  Bool          getReconMark ()       { return m_bReconstructed;  }
+  Bool          getReconMark () const      { return m_bReconstructed;  }
   Void          setOutputMark (Bool b) { m_bNeededForOutput = b;     }
-  Bool          getOutputMark ()       { return m_bNeededForOutput;  }
- #if H_MV
+  Bool          getOutputMark () const      { return m_bNeededForOutput;  }
+ #if NH_MV
   Void          setPicOutputFlag(Bool b) { m_bPicOutputFlag = b;      }
   Bool          getPicOutputFlag()       { return m_bPicOutputFlag ;  }
 #endif
-
-  Void          setNumReorderPics(Int i, UInt tlayer) { m_numReorderPics[tlayer] = i;    }
-  Int           getNumReorderPics(UInt tlayer)        { return m_numReorderPics[tlayer]; }
-#if H_3D
+#if NH_3D
   Void          compressMotion(Int scale); 
 #else   
-  Void          compressMotion(); 
-#endif
-  UInt          getCurrSliceIdx()            { return m_uiCurrSliceIdx;                }
+  Void          compressMotion();
+#endif
+  UInt          getCurrSliceIdx() const           { return m_uiCurrSliceIdx;                }
   Void          setCurrSliceIdx(UInt i)      { m_uiCurrSliceIdx = i;                   }
-  UInt          getNumAllocatedSlice()       {return m_apcPicSym->getNumAllocatedSlice();}
-  Void          allocateNewSlice()           {m_apcPicSym->allocateNewSlice();         }
-  Void          clearSliceBuffer()           {m_apcPicSym->clearSliceBuffer();         }
-
-  Window&       getConformanceWindow()  { return m_conformanceWindow; }
-  Window&       getDefDisplayWindow()   { return m_defaultDisplayWindow; }
+  UInt          getNumAllocatedSlice() const      {return m_picSym.getNumAllocatedSlice();}
+  Void          allocateNewSlice()           {m_picSym.allocateNewSlice();         }
+  Void          clearSliceBuffer()           {m_picSym.clearSliceBuffer();         }
+
+  const Window& getConformanceWindow() const { return m_picSym.getSPS().getConformanceWindow(); }
+  Window        getDefDisplayWindow() const  { return m_picSym.getSPS().getVuiParametersPresentFlag() ? m_picSym.getSPS().getVuiParameters()->getDefaultDisplayWindow() : Window(); }
 
   Bool          getSAOMergeAvailability(Int currAddr, Int mergeAddr);
 
+  UInt          getSubstreamForCtuAddr(const UInt ctuAddr, const Bool bAddressInRaster, TComSlice *pcSlice);
+
   /* field coding parameters*/
 
-   Void              setTopField(bool b)                  {m_isTop = b;}
-   bool              isTopField()                         {return m_isTop;}
-   Void              setField(bool b)                     {m_isField = b;}
-   bool              isField()                            {return m_isField;}
-
-#if H_MV
+   Void              setTopField(Bool b)                  {m_isTop = b;}
+   Bool              isTopField()                         {return m_isTop;}
+   Void              setField(Bool b)                     {m_isField = b;}
+   Bool              isField()                            {return m_isField;}
+
+#if NH_MV
   Void          print( Bool legend );
 #endif
@@ -224,6 +222,7 @@
   Int           isTextRefValid(Int iTextRefDir, Int iTextRefIdx);
 #endif
+
   /** transfer ownership of seis to this picture */
-  void setSEIs(SEIMessages& seis) { m_SEIs = seis; }
+  Void setSEIs(SEIMessages& seis) { m_SEIs = seis; }
 
   /**
@@ -236,14 +235,13 @@
    * Pointer is valid until this->destroy() is called */
   const SEIMessages& getSEIs() const { return m_SEIs; }
-
 };// END CLASS DEFINITION TComPic
 
-#if H_MV
+#if NH_MV
 class TComPicLists 
 {
 private: 
   TComList<TComList<TComPic*>*> m_lists; 
-#if H_3D
-  TComVPS*                     m_vps; 
+#if NH_3D
+  const TComVPS*                     m_vps; 
 #endif
 public: 
@@ -255,6 +253,6 @@
   TComPic*    getPic   ( Int layerIdInNuh,              Int poc );    
   TComPicYuv* getPicYuv( Int layerIdInNuh,              Int poc, Bool recon ); 
-#if H_3D
-  Void        setVPS   ( TComVPS* vps ) { m_vps = vps;  }; 
+#if NH_3D
+  Void        setVPS   ( const TComVPS* vps ) { m_vps = vps;  }; 
   TComPic*    getPic   ( Int viewIndex, Bool depthFlag, Int poc );
   TComPicYuv* getPicYuv( Int viewIndex, Bool depthFlag, Int poc, Bool recon );
@@ -266,4 +264,5 @@
 
 #endif 
+
 //! \}
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -48,127 +48,134 @@
 
 TComPicSym::TComPicSym()
-:m_uiWidthInCU(0)
-,m_uiHeightInCU(0)
-,m_uiMaxCUWidth(0)
-,m_uiMaxCUHeight(0)
+:m_frameWidthInCtus(0)
+,m_frameHeightInCtus(0)
 ,m_uiMinCUWidth(0)
 ,m_uiMinCUHeight(0)
 ,m_uhTotalDepth(0)
-,m_uiNumPartitions(0)
-,m_uiNumPartInWidth(0)
-,m_uiNumPartInHeight(0)
-,m_uiNumCUsInFrame(0)
-,m_apcTComSlice(NULL)
-,m_uiNumAllocatedSlice (0)
-,m_apcTComDataCU (NULL)
-,m_iNumColumnsMinus1 (0)
-,m_iNumRowsMinus1(0)
-,m_puiCUOrderMap(0)
+,m_numPartitionsInCtu(0)
+,m_numPartInCtuWidth(0)
+,m_numPartInCtuHeight(0)
+,m_numCtusInFrame(0)
+,m_apSlices()
+,m_pictureCtuArray(NULL)
+,m_numTileColumnsMinus1(0)
+,m_numTileRowsMinus1(0)
+,m_ctuTsToRsAddrMap(NULL)
 ,m_puiTileIdxMap(NULL)
-,m_puiInverseCUOrderMap(NULL)
+,m_ctuRsToTsAddrMap(NULL)
 ,m_saoBlkParams(NULL)
-{};
-
-
-Void TComPicSym::create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth )
+#if ADAPTIVE_QP_SELECTION
+,m_pParentARLBuffer(NULL)
+#endif
+{}
+
+
+Void TComPicSym::create  ( const TComSPS &sps, const TComPPS &pps, UInt uiMaxDepth )
 {
   UInt i;
-
-  m_uhTotalDepth      = uiMaxDepth;
-  m_uiNumPartitions   = 1<<(m_uhTotalDepth<<1);
-  
-  m_uiMaxCUWidth      = uiMaxWidth;
-  m_uiMaxCUHeight     = uiMaxHeight;
-  
-  m_uiMinCUWidth      = uiMaxWidth  >> m_uhTotalDepth;
-  m_uiMinCUHeight     = uiMaxHeight >> m_uhTotalDepth;
-  
-  m_uiNumPartInWidth  = m_uiMaxCUWidth  / m_uiMinCUWidth;
-  m_uiNumPartInHeight = m_uiMaxCUHeight / m_uiMinCUHeight;
-  
-  m_uiWidthInCU       = ( iPicWidth %m_uiMaxCUWidth  ) ? iPicWidth /m_uiMaxCUWidth  + 1 : iPicWidth /m_uiMaxCUWidth;
-  m_uiHeightInCU      = ( iPicHeight%m_uiMaxCUHeight ) ? iPicHeight/m_uiMaxCUHeight + 1 : iPicHeight/m_uiMaxCUHeight;
-  
-  m_uiNumCUsInFrame   = m_uiWidthInCU * m_uiHeightInCU;
-  m_apcTComDataCU     = new TComDataCU*[m_uiNumCUsInFrame];
-  
-  if (m_uiNumAllocatedSlice>0)
-  {
-    for ( i=0; i<m_uiNumAllocatedSlice ; i++ )
-    {
-      delete m_apcTComSlice[i];
-    }
-    delete [] m_apcTComSlice;
-  }
-  m_apcTComSlice      = new TComSlice*[m_uiNumCUsInFrame];
-  m_apcTComSlice[0]   = new TComSlice;
-  m_uiNumAllocatedSlice = 1;
-  for ( i=0; i<m_uiNumCUsInFrame ; i++ )
-  {
-    m_apcTComDataCU[i] = new TComDataCU;
-    m_apcTComDataCU[i]->create( m_uiNumPartitions, m_uiMaxCUWidth, m_uiMaxCUHeight, false, m_uiMaxCUWidth >> m_uhTotalDepth
+  m_sps = sps;
+  m_pps = pps;
+
+  const ChromaFormat chromaFormatIDC = sps.getChromaFormatIdc();
+  const Int iPicWidth      = sps.getPicWidthInLumaSamples();
+  const Int iPicHeight     = sps.getPicHeightInLumaSamples();
+  const UInt uiMaxCuWidth  = sps.getMaxCUWidth();
+  const UInt uiMaxCuHeight = sps.getMaxCUHeight();
+
+  m_uhTotalDepth       = uiMaxDepth;
+  m_numPartitionsInCtu = 1<<(m_uhTotalDepth<<1);
+
+  m_uiMinCUWidth       = uiMaxCuWidth  >> m_uhTotalDepth;
+  m_uiMinCUHeight      = uiMaxCuHeight >> m_uhTotalDepth;
+
+  m_numPartInCtuWidth  = uiMaxCuWidth  / m_uiMinCUWidth;  // equivalent to 1<<m_uhTotalDepth
+  m_numPartInCtuHeight = uiMaxCuHeight / m_uiMinCUHeight; // equivalent to 1<<m_uhTotalDepth
+
+  m_frameWidthInCtus   = ( iPicWidth %uiMaxCuWidth  ) ? iPicWidth /uiMaxCuWidth  + 1 : iPicWidth /uiMaxCuWidth;
+  m_frameHeightInCtus  = ( iPicHeight%uiMaxCuHeight ) ? iPicHeight/uiMaxCuHeight + 1 : iPicHeight/uiMaxCuHeight;
+
+  m_numCtusInFrame     = m_frameWidthInCtus * m_frameHeightInCtus;
+  m_pictureCtuArray    = new TComDataCU*[m_numCtusInFrame];
+
+  clearSliceBuffer();
+  allocateNewSlice();
+
 #if ADAPTIVE_QP_SELECTION
-      , true
-#endif     
+  if (m_pParentARLBuffer == NULL)
+  {
+     m_pParentARLBuffer = new TCoeff[uiMaxCuWidth*uiMaxCuHeight*MAX_NUM_COMPONENT];
+  }
+#endif
+
+  for ( i=0; i<m_numCtusInFrame ; i++ )
+  {
+    m_pictureCtuArray[i] = new TComDataCU;
+    m_pictureCtuArray[i]->create( chromaFormatIDC, m_numPartitionsInCtu, uiMaxCuWidth, uiMaxCuHeight, false, uiMaxCuWidth >> m_uhTotalDepth
+#if ADAPTIVE_QP_SELECTION
+      , m_pParentARLBuffer
+#endif
       );
   }
 
-  m_puiCUOrderMap = new UInt[m_uiNumCUsInFrame+1];
-  m_puiTileIdxMap = new UInt[m_uiNumCUsInFrame];
-  m_puiInverseCUOrderMap = new UInt[m_uiNumCUsInFrame+1];
-
-  for( i=0; i<m_uiNumCUsInFrame; i++ )
-  {
-    m_puiCUOrderMap[i] = i;
-    m_puiInverseCUOrderMap[i] = i;
-  }
-
-  m_saoBlkParams = new SAOBlkParam[m_uiNumCUsInFrame];
+  m_ctuTsToRsAddrMap = new UInt[m_numCtusInFrame+1];
+  m_puiTileIdxMap    = new UInt[m_numCtusInFrame];
+  m_ctuRsToTsAddrMap = new UInt[m_numCtusInFrame+1];
+
+  for( i=0; i<m_numCtusInFrame; i++ )
+  {
+    m_ctuTsToRsAddrMap[i] = i;
+    m_ctuRsToTsAddrMap[i] = i;
+  }
+
+  m_saoBlkParams = new SAOBlkParam[m_numCtusInFrame];
+
+
+  xInitTiles();
+  xInitCtuTsRsAddrMaps();
+
 }
 
 Void TComPicSym::destroy()
 {
-  if (m_uiNumAllocatedSlice>0)
-  {
-    for (Int i = 0; i<m_uiNumAllocatedSlice ; i++ )
-    {
-      delete m_apcTComSlice[i];
-    }
-    delete [] m_apcTComSlice;
-  }
-  m_apcTComSlice = NULL;
-  
-  for (Int i = 0; i < m_uiNumCUsInFrame; i++)
-  {
-    m_apcTComDataCU[i]->destroy();
-    delete m_apcTComDataCU[i];
-    m_apcTComDataCU[i] = NULL;
-  }
-  delete [] m_apcTComDataCU;
-  m_apcTComDataCU = NULL;
-
-  delete [] m_puiCUOrderMap;
-  m_puiCUOrderMap = NULL;
+  clearSliceBuffer();
+
+  for (Int i = 0; i < m_numCtusInFrame; i++)
+  {
+    m_pictureCtuArray[i]->destroy();
+    delete m_pictureCtuArray[i];
+    m_pictureCtuArray[i] = NULL;
+  }
+  delete [] m_pictureCtuArray;
+  m_pictureCtuArray = NULL;
+
+  delete [] m_ctuTsToRsAddrMap;
+  m_ctuTsToRsAddrMap = NULL;
 
   delete [] m_puiTileIdxMap;
   m_puiTileIdxMap = NULL;
 
-  delete [] m_puiInverseCUOrderMap;
-  m_puiInverseCUOrderMap = NULL;
-  
+  delete [] m_ctuRsToTsAddrMap;
+  m_ctuRsToTsAddrMap = NULL;
+
   if(m_saoBlkParams)
   {
     delete[] m_saoBlkParams; m_saoBlkParams = NULL;
   }
+
+#if ADAPTIVE_QP_SELECTION
+  delete [] m_pParentARLBuffer;
+  m_pParentARLBuffer = NULL;
+#endif
 }
 
 Void TComPicSym::allocateNewSlice()
 {
-  assert ((m_uiNumAllocatedSlice + 1) <= m_uiNumCUsInFrame);
-  m_apcTComSlice[m_uiNumAllocatedSlice ++] = new TComSlice;
-  if (m_uiNumAllocatedSlice>=2)
-  {
-    m_apcTComSlice[m_uiNumAllocatedSlice-1]->copySliceInfo( m_apcTComSlice[m_uiNumAllocatedSlice-2] );
-    m_apcTComSlice[m_uiNumAllocatedSlice-1]->initSlice();
+  m_apSlices.push_back(new TComSlice);
+  m_apSlices.back()->setPPS(&m_pps);
+  m_apSlices.back()->setSPS(&m_sps);
+  if (m_apSlices.size()>=2)
+  {
+    m_apSlices.back()->copySliceInfo( m_apSlices[m_apSlices.size()-2] );
+    m_apSlices.back()->initSlice();
   }
 }
@@ -176,30 +183,31 @@
 Void TComPicSym::clearSliceBuffer()
 {
-  UInt i;
-  for (i = 1; i < m_uiNumAllocatedSlice; i++)
-  {
-    delete m_apcTComSlice[i];
-  }
-  m_uiNumAllocatedSlice = 1;
-}
-
-UInt TComPicSym::getPicSCUEncOrder( UInt SCUAddr )
-{ 
-  return getInverseCUOrderMap(SCUAddr/m_uiNumPartitions)*m_uiNumPartitions + SCUAddr%m_uiNumPartitions; 
-}
-
-UInt TComPicSym::getPicSCUAddr( UInt SCUEncOrder )
-{
-  return getCUOrderMap(SCUEncOrder/m_uiNumPartitions)*m_uiNumPartitions + SCUEncOrder%m_uiNumPartitions;
-}
-
-Void TComPicSym::initTiles(TComPPS *pps)
+  for (UInt i = 0; i < UInt(m_apSlices.size()); i++)
+  {
+    delete m_apSlices[i];
+  }
+  m_apSlices.clear();
+}
+
+Void TComPicSym::xInitCtuTsRsAddrMaps()
+{
+  //generate the Coding Order Map and Inverse Coding Order Map
+  for(Int ctuTsAddr=0, ctuRsAddr=0; ctuTsAddr<getNumberOfCtusInFrame(); ctuTsAddr++, ctuRsAddr = xCalculateNextCtuRSAddr(ctuRsAddr))
+  {
+    setCtuTsToRsAddrMap(ctuTsAddr, ctuRsAddr);
+    setCtuRsToTsAddrMap(ctuRsAddr, ctuTsAddr);
+  }
+  setCtuTsToRsAddrMap(getNumberOfCtusInFrame(), getNumberOfCtusInFrame());
+  setCtuRsToTsAddrMap(getNumberOfCtusInFrame(), getNumberOfCtusInFrame());
+}
+
+Void TComPicSym::xInitTiles()
 {
   //set NumColumnsMinus1 and NumRowsMinus1
-  setNumColumnsMinus1( pps->getNumTileColumnsMinus1() );
-  setNumRowsMinus1( pps->getTileNumRowsMinus1() );
-
-  const Int numCols = pps->getNumTileColumnsMinus1() + 1;
-  const Int numRows = pps->getTileNumRowsMinus1() + 1;
+  setNumTileColumnsMinus1( m_pps.getNumTileColumnsMinus1() );
+  setNumTileRowsMinus1(    m_pps.getNumTileRowsMinus1()    );
+
+  const Int numCols = m_pps.getNumTileColumnsMinus1() + 1;
+  const Int numRows = m_pps.getNumTileRowsMinus1() + 1;
   const Int numTiles = numRows * numCols;
 
@@ -207,5 +215,5 @@
   m_tileParameters.resize(numTiles);
 
-  if( pps->getTileUniformSpacingFlag() )
+  if( m_pps.getTileUniformSpacingFlag() )
   {
     //set width and height for each (uniform) tile
@@ -215,8 +223,6 @@
       {
         const Int tileIdx = row * numCols + col;
-        m_tileParameters[tileIdx].setTileWidth( (col+1)*getFrameWidthInCU()/numCols
-                                              - (col*getFrameWidthInCU())/numCols );
-        m_tileParameters[tileIdx].setTileHeight( (row+1)*getFrameHeightInCU()/numRows
-                                               - (row*getFrameHeightInCU())/numRows );
+        m_tileParameters[tileIdx].setTileWidthInCtus(  (col+1)*getFrameWidthInCtus( )/numCols - (col*getFrameWidthInCtus( ))/numCols );
+        m_tileParameters[tileIdx].setTileHeightInCtus( (row+1)*getFrameHeightInCtus()/numRows - (row*getFrameHeightInCtus())/numRows );
       }
     }
@@ -228,35 +234,35 @@
     {
       Int cumulativeTileWidth = 0;
-      for(Int col=0; col < getNumColumnsMinus1(); col++)
-  {
-        m_tileParameters[row * numCols + col].setTileWidth( pps->getTileColumnWidth(col) );
-        cumulativeTileWidth += pps->getTileColumnWidth(col);
-  }
-      m_tileParameters[row * numCols + getNumColumnsMinus1()].setTileWidth( getFrameWidthInCU()-cumulativeTileWidth );
-}
+      for(Int col=0; col < getNumTileColumnsMinus1(); col++)
+      {
+        m_tileParameters[row * numCols + col].setTileWidthInCtus( m_pps.getTileColumnWidth(col) );
+        cumulativeTileWidth += m_pps.getTileColumnWidth(col);
+      }
+      m_tileParameters[row * numCols + getNumTileColumnsMinus1()].setTileWidthInCtus( getFrameWidthInCtus()-cumulativeTileWidth );
+    }
 
     //set the height for each tile
     for(Int col=0; col < numCols; col++)
-{
+    {
       Int cumulativeTileHeight = 0;
-      for(Int row=0; row < getNumRowsMinus1(); row++)
-      {
-        m_tileParameters[row * numCols + col].setTileHeight( pps->getTileRowHeight(row) );
-        cumulativeTileHeight += pps->getTileRowHeight(row);
-      }
-      m_tileParameters[getNumRowsMinus1() * numCols + col].setTileHeight( getFrameHeightInCU()-cumulativeTileHeight );
-    }
-  }
-
-#if TILE_SIZE_CHECK
+      for(Int row=0; row < getNumTileRowsMinus1(); row++)
+      {
+        m_tileParameters[row * numCols + col].setTileHeightInCtus( m_pps.getTileRowHeight(row) );
+        cumulativeTileHeight += m_pps.getTileRowHeight(row);
+      }
+      m_tileParameters[getNumTileRowsMinus1() * numCols + col].setTileHeightInCtus( getFrameHeightInCtus()-cumulativeTileHeight );
+    }
+  }
+
+  // Tile size check
   Int minWidth  = 1;
   Int minHeight = 1;
-  const Int profileIdc = pps->getSPS()->getPTL()->getGeneralPTL()->getProfileIdc();
-  if (  profileIdc == Profile::MAIN || profileIdc == Profile::MAIN10)
-  {
-    if (pps->getTilesEnabledFlag())
-    {
-      minHeight = 64  / g_uiMaxCUHeight;
-      minWidth  = 256 / g_uiMaxCUWidth;
+  const Int profileIdc = m_sps.getPTL()->getGeneralPTL()->getProfileIdc();
+  if (  profileIdc == Profile::MAIN || profileIdc == Profile::MAIN10) //TODO: add more profiles to the tile-size check...
+  {
+    if (m_pps.getTilesEnabledFlag())
+    {
+      minHeight = 64  / m_sps.getMaxCUHeight();
+      minWidth  = 256 / m_sps.getMaxCUWidth();
     }
   }
@@ -266,9 +272,8 @@
     {
       const Int tileIdx = row * numCols + col;
-      assert (m_tileParameters[tileIdx].getTileWidth() >= minWidth);
-      assert (m_tileParameters[tileIdx].getTileHeight() >= minHeight);
-    }
-  }
-#endif
+      assert (m_tileParameters[tileIdx].getTileWidthInCtus() >= minWidth);
+      assert (m_tileParameters[tileIdx].getTileHeightInCtus() >= minHeight);
+    }
+  }
 
   //initialize each tile of the current picture
@@ -283,7 +288,7 @@
       for( Int i=0; i <= col; i++ )
       {
-        rightEdgePosInCTU += m_tileParameters[row * numCols + i].getTileWidth();
-      }
-      m_tileParameters[tileIdx].setRightEdgePosInCU(rightEdgePosInCTU-1);
+        rightEdgePosInCTU += m_tileParameters[row * numCols + i].getTileWidthInCtus();
+      }
+      m_tileParameters[tileIdx].setRightEdgePosInCtus(rightEdgePosInCTU-1);
 
       //initialize the BottomEdgePosInCU for each tile
@@ -291,11 +296,11 @@
       for( Int i=0; i <= row; i++ )
       {
-        bottomEdgePosInCTU += m_tileParameters[i * numCols + col].getTileHeight();
-      }
-      m_tileParameters[tileIdx].setBottomEdgePosInCU(bottomEdgePosInCTU-1);
+        bottomEdgePosInCTU += m_tileParameters[i * numCols + col].getTileHeightInCtus();
+      }
+      m_tileParameters[tileIdx].setBottomEdgePosInCtus(bottomEdgePosInCTU-1);
 
       //initialize the FirstCUAddr for each tile
-      m_tileParameters[tileIdx].setFirstCUAddr( (m_tileParameters[tileIdx].getBottomEdgePosInCU() - m_tileParameters[tileIdx].getTileHeight() + 1) * getFrameWidthInCU() + 
-                                                 m_tileParameters[tileIdx].getRightEdgePosInCU() - m_tileParameters[tileIdx].getTileWidth() + 1);
+      m_tileParameters[tileIdx].setFirstCtuRsAddr( (m_tileParameters[tileIdx].getBottomEdgePosInCtus() - m_tileParameters[tileIdx].getTileHeightInCtus() + 1) * getFrameWidthInCtus() +
+                                                    m_tileParameters[tileIdx].getRightEdgePosInCtus()  - m_tileParameters[tileIdx].getTileWidthInCtus()  + 1);
     }
   }
@@ -305,9 +310,9 @@
 
   //initialize the TileIdxMap
-  for( Int i=0; i<m_uiNumCUsInFrame; i++)
+  for( Int i=0; i<m_numCtusInFrame; i++)
   {
     for( Int col=0; col < numCols; col++)
     {
-      if(i % getFrameWidthInCU() <= m_tileParameters[col].getRightEdgePosInCU())
+      if(i % getFrameWidthInCtus() <= m_tileParameters[col].getRightEdgePosInCtus())
       {
         columnIdx = col;
@@ -317,5 +322,5 @@
     for(Int row=0; row < numRows; row++)
     {
-      if(i / getFrameWidthInCU() <= m_tileParameters[row*numCols].getBottomEdgePosInCU())
+      if(i / getFrameWidthInCtus() <= m_tileParameters[row*numCols].getBottomEdgePosInCtus())
       {
         rowIdx = row;
@@ -325,44 +330,41 @@
     m_puiTileIdxMap[i] = rowIdx * numCols + columnIdx;
   }
-
-}
-
-UInt TComPicSym::xCalculateNxtCUAddr( UInt uiCurrCUAddr )
-{
-  UInt  uiNxtCUAddr;
-  UInt  uiTileIdx;
-  
-  //get the tile index for the current LCU
-  uiTileIdx = this->getTileIdxMap(uiCurrCUAddr);
-
-  //get the raster scan address for the next LCU
-  if( uiCurrCUAddr % m_uiWidthInCU == this->getTComTile(uiTileIdx)->getRightEdgePosInCU() && uiCurrCUAddr / m_uiWidthInCU == this->getTComTile(uiTileIdx)->getBottomEdgePosInCU() )
-  //the current LCU is the last LCU of the tile
-  {
-    if(uiTileIdx == (m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1)-1)
-    {
-      uiNxtCUAddr = m_uiNumCUsInFrame;
+}
+UInt TComPicSym::xCalculateNextCtuRSAddr( UInt currCtuRsAddr )
+{
+  UInt  nextCtuRsAddr;
+
+  //get the tile index for the current CTU
+  const UInt uiTileIdx = getTileIdxMap(currCtuRsAddr);
+
+  //get the raster scan address for the next CTU
+  if( currCtuRsAddr % m_frameWidthInCtus == getTComTile(uiTileIdx)->getRightEdgePosInCtus() && currCtuRsAddr / m_frameWidthInCtus == getTComTile(uiTileIdx)->getBottomEdgePosInCtus() )
+  //the current CTU is the last CTU of the tile
+  {
+    if(uiTileIdx+1 == getNumTiles())
+    {
+      nextCtuRsAddr = m_numCtusInFrame;
     }
     else
     {
-      uiNxtCUAddr = this->getTComTile(uiTileIdx+1)->getFirstCUAddr();
-    }
-  } 
-  else //the current LCU is not the last LCU of the tile
-  {
-    if( uiCurrCUAddr % m_uiWidthInCU == this->getTComTile(uiTileIdx)->getRightEdgePosInCU() )  //the current LCU is on the rightmost edge of the tile
-    {
-      uiNxtCUAddr = uiCurrCUAddr + m_uiWidthInCU - this->getTComTile(uiTileIdx)->getTileWidth() + 1;
+      nextCtuRsAddr = getTComTile(uiTileIdx+1)->getFirstCtuRsAddr();
+    }
+  }
+  else //the current CTU is not the last CTU of the tile
+  {
+    if( currCtuRsAddr % m_frameWidthInCtus == getTComTile(uiTileIdx)->getRightEdgePosInCtus() )  //the current CTU is on the rightmost edge of the tile
+    {
+      nextCtuRsAddr = currCtuRsAddr + m_frameWidthInCtus - getTComTile(uiTileIdx)->getTileWidthInCtus() + 1;
     }
     else
     {
-      uiNxtCUAddr = uiCurrCUAddr + 1;
-    }
-  }
-
-  return uiNxtCUAddr;
-}
-
-Void TComPicSym::deriveLoopFilterBoundaryAvailibility(Int ctu,
+      nextCtuRsAddr = currCtuRsAddr + 1;
+    }
+  }
+
+  return nextCtuRsAddr;
+}
+
+Void TComPicSym::deriveLoopFilterBoundaryAvailibility(Int ctuRsAddr,
                                                       Bool& isLeftAvail,
                                                       Bool& isRightAvail,
@@ -376,8 +378,8 @@
 {
 
-  isLeftAvail      = (ctu % m_uiWidthInCU != 0);
-  isRightAvail     = (ctu % m_uiWidthInCU != m_uiWidthInCU-1);
-  isAboveAvail     = (ctu >= m_uiWidthInCU );
-  isBelowAvail     = (ctu <  m_uiNumCUsInFrame - m_uiWidthInCU);
+  isLeftAvail      = (ctuRsAddr % m_frameWidthInCtus != 0);
+  isRightAvail     = (ctuRsAddr % m_frameWidthInCtus != m_frameWidthInCtus-1);
+  isAboveAvail     = (ctuRsAddr >= m_frameWidthInCtus );
+  isBelowAvail     = (ctuRsAddr <  m_numCtusInFrame - m_frameWidthInCtus);
   isAboveLeftAvail = (isAboveAvail && isLeftAvail);
   isAboveRightAvail= (isAboveAvail && isRightAvail);
@@ -385,16 +387,16 @@
   isBelowRightAvail= (isBelowAvail && isRightAvail);
 
-  Bool isLoopFiltAcrossTilePPS = getCU(ctu)->getSlice()->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
-
-  {
-    TComDataCU* ctuCurr  = getCU(ctu);
-    TComDataCU* ctuLeft  = isLeftAvail ?getCU(ctu-1):NULL;
-    TComDataCU* ctuRight = isRightAvail?getCU(ctu+1):NULL;
-    TComDataCU* ctuAbove = isAboveAvail?getCU(ctu-m_uiWidthInCU):NULL;
-    TComDataCU* ctuBelow = isBelowAvail?getCU(ctu+m_uiWidthInCU):NULL;
-    TComDataCU* ctuAboveLeft  = isAboveLeftAvail ? getCU(ctu-m_uiWidthInCU-1):NULL;
-    TComDataCU* ctuAboveRigtht= isAboveRightAvail? getCU(ctu-m_uiWidthInCU+1):NULL;
-    TComDataCU* ctuBelowLeft  = isBelowLeftAvail ? getCU(ctu+m_uiWidthInCU-1):NULL;
-    TComDataCU* ctuBelowRight = isBelowRightAvail? getCU(ctu+m_uiWidthInCU+1):NULL;
+  Bool isLoopFiltAcrossTilePPS = getCtu(ctuRsAddr)->getSlice()->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+
+  {
+    TComDataCU* ctuCurr  = getCtu(ctuRsAddr);
+    TComDataCU* ctuLeft  = isLeftAvail ?getCtu(ctuRsAddr-1):NULL;
+    TComDataCU* ctuRight = isRightAvail?getCtu(ctuRsAddr+1):NULL;
+    TComDataCU* ctuAbove = isAboveAvail?getCtu(ctuRsAddr-m_frameWidthInCtus):NULL;
+    TComDataCU* ctuBelow = isBelowAvail?getCtu(ctuRsAddr+m_frameWidthInCtus):NULL;
+    TComDataCU* ctuAboveLeft  = isAboveLeftAvail ? getCtu(ctuRsAddr-m_frameWidthInCtus-1):NULL;
+    TComDataCU* ctuAboveRight = isAboveRightAvail? getCtu(ctuRsAddr-m_frameWidthInCtus+1):NULL;
+    TComDataCU* ctuBelowLeft  = isBelowLeftAvail ? getCtu(ctuRsAddr+m_frameWidthInCtus-1):NULL;
+    TComDataCU* ctuBelowRight = isBelowRightAvail? getCtu(ctuRsAddr+m_frameWidthInCtus+1):NULL;
 
     {
@@ -402,81 +404,80 @@
       if(ctuLeft != NULL)
       {
-        isLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuLeft->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+        isLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuLeft->getSlice()->getSliceCurStartCtuTsAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
       }
       //above
       if(ctuAbove != NULL)
       {
-        isAboveAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuAbove->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+        isAboveAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuAbove->getSlice()->getSliceCurStartCtuTsAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
       }
       //right
       if(ctuRight != NULL)
       {
-        isRightAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuRight->getSlice()->getSliceCurStartCUAddr())?ctuRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+        isRightAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuRight->getSlice()->getSliceCurStartCtuTsAddr())?ctuRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
       }
       //below
       if(ctuBelow != NULL)
       {
-        isBelowAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuBelow->getSlice()->getSliceCurStartCUAddr())?ctuBelow->getSlice()->getLFCrossSliceBoundaryFlag():true;
+        isBelowAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuBelow->getSlice()->getSliceCurStartCtuTsAddr())?ctuBelow->getSlice()->getLFCrossSliceBoundaryFlag():true;
       }
       //above-left
       if(ctuAboveLeft != NULL)
       {
-        isAboveLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuAboveLeft->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+        isAboveLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuAboveLeft->getSlice()->getSliceCurStartCtuTsAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
       }
       //below-right
       if(ctuBelowRight != NULL)
-{
-        isBelowRightAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuBelowRight->getSlice()->getSliceCurStartCUAddr())?ctuBelowRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
-      }
-
+      {
+        isBelowRightAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuBelowRight->getSlice()->getSliceCurStartCtuTsAddr())?ctuBelowRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
 
       //above-right
-      if(ctuAboveRigtht != NULL)
-      {
-        Int curSliceStartEncOrder  = ctuCurr->getSlice()->getSliceCurStartCUAddr();
-        Int aboveRigthtSliceStartEncOrder = ctuAboveRigtht->getSlice()->getSliceCurStartCUAddr();
-
-        isAboveRightAvail = (curSliceStartEncOrder == aboveRigthtSliceStartEncOrder)?(true):
+      if(ctuAboveRight != NULL)
+      {
+        Int curSliceStartTsAddr  = ctuCurr->getSlice()->getSliceCurStartCtuTsAddr();
+        Int aboveRightSliceStartTsAddr = ctuAboveRight->getSlice()->getSliceCurStartCtuTsAddr();
+
+        isAboveRightAvail = (curSliceStartTsAddr == aboveRightSliceStartTsAddr)?(true):
           (
-          (curSliceStartEncOrder > aboveRigthtSliceStartEncOrder)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
-          :(ctuAboveRigtht->getSlice()->getLFCrossSliceBoundaryFlag())
-          );          
+          (curSliceStartTsAddr > aboveRightSliceStartTsAddr)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuAboveRight->getSlice()->getLFCrossSliceBoundaryFlag())
+          );
       }
       //below-left
       if(ctuBelowLeft != NULL)
       {
-        Int curSliceStartEncOrder  = ctuCurr->getSlice()->getSliceCurStartCUAddr();
-        Int belowLeftSliceStartEncOrder = ctuBelowLeft->getSlice()->getSliceCurStartCUAddr();
-
-        isBelowLeftAvail = (curSliceStartEncOrder == belowLeftSliceStartEncOrder)?(true):
+        Int curSliceStartTsAddr       = ctuCurr->getSlice()->getSliceCurStartCtuTsAddr();
+        Int belowLeftSliceStartTsAddr = ctuBelowLeft->getSlice()->getSliceCurStartCtuTsAddr();
+
+        isBelowLeftAvail = (curSliceStartTsAddr == belowLeftSliceStartTsAddr)?(true):
           (
-          (curSliceStartEncOrder > belowLeftSliceStartEncOrder)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          (curSliceStartTsAddr > belowLeftSliceStartTsAddr)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
           :(ctuBelowLeft->getSlice()->getLFCrossSliceBoundaryFlag())
           );
-      }        
+      }
     }
 
     if(!isLoopFiltAcrossTilePPS)
-    {      
-      isLeftAvail      = (!isLeftAvail      ) ?false:(getTileIdxMap( ctuLeft->getAddr()         ) == getTileIdxMap( ctu ));
-      isAboveAvail     = (!isAboveAvail     ) ?false:(getTileIdxMap( ctuAbove->getAddr()        ) == getTileIdxMap( ctu ));
-      isRightAvail     = (!isRightAvail     ) ?false:(getTileIdxMap( ctuRight->getAddr()        ) == getTileIdxMap( ctu ));
-      isBelowAvail     = (!isBelowAvail     ) ?false:(getTileIdxMap( ctuBelow->getAddr()        ) == getTileIdxMap( ctu ));
-      isAboveLeftAvail = (!isAboveLeftAvail ) ?false:(getTileIdxMap( ctuAboveLeft->getAddr()    ) == getTileIdxMap( ctu ));
-      isAboveRightAvail= (!isAboveRightAvail) ?false:(getTileIdxMap( ctuAboveRigtht->getAddr()  ) == getTileIdxMap( ctu ));
-      isBelowLeftAvail = (!isBelowLeftAvail ) ?false:(getTileIdxMap( ctuBelowLeft->getAddr()    ) == getTileIdxMap( ctu ));
-      isBelowRightAvail= (!isBelowRightAvail) ?false:(getTileIdxMap( ctuBelowRight->getAddr()   ) == getTileIdxMap( ctu ));
-    }
-  }
-
-}
+    {
+      isLeftAvail      = (!isLeftAvail      ) ?false:(getTileIdxMap( ctuLeft->getCtuRsAddr()         ) == getTileIdxMap( ctuRsAddr ));
+      isAboveAvail     = (!isAboveAvail     ) ?false:(getTileIdxMap( ctuAbove->getCtuRsAddr()        ) == getTileIdxMap( ctuRsAddr ));
+      isRightAvail     = (!isRightAvail     ) ?false:(getTileIdxMap( ctuRight->getCtuRsAddr()        ) == getTileIdxMap( ctuRsAddr ));
+      isBelowAvail     = (!isBelowAvail     ) ?false:(getTileIdxMap( ctuBelow->getCtuRsAddr()        ) == getTileIdxMap( ctuRsAddr ));
+      isAboveLeftAvail = (!isAboveLeftAvail ) ?false:(getTileIdxMap( ctuAboveLeft->getCtuRsAddr()    ) == getTileIdxMap( ctuRsAddr ));
+      isAboveRightAvail= (!isAboveRightAvail) ?false:(getTileIdxMap( ctuAboveRight->getCtuRsAddr()   ) == getTileIdxMap( ctuRsAddr ));
+      isBelowLeftAvail = (!isBelowLeftAvail ) ?false:(getTileIdxMap( ctuBelowLeft->getCtuRsAddr()    ) == getTileIdxMap( ctuRsAddr ));
+      isBelowRightAvail= (!isBelowRightAvail) ?false:(getTileIdxMap( ctuBelowRight->getCtuRsAddr()   ) == getTileIdxMap( ctuRsAddr ));
+    }
+  }
+
+}
+
 
 TComTile::TComTile()
-: m_uiTileWidth         (0)
-, m_uiTileHeight        (0)
-, m_uiRightEdgePosInCU  (0)
-, m_uiBottomEdgePosInCU (0)
-, m_uiFirstCUAddr       (0)
-
+: m_tileWidthInCtus     (0)
+, m_tileHeightInCtus    (0)
+, m_rightEdgePosInCtus  (0)
+, m_bottomEdgePosInCtus (0)
+, m_firstCtuRsAddr      (0)
 {
 }
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicSym.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicSym.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -41,4 +41,5 @@
 
 // Include files
+#include <deque>
 #include "CommonDef.h"
 #include "TComSlice.h"
@@ -57,24 +58,24 @@
 {
 private:
-  UInt      m_uiTileWidth;
-  UInt      m_uiTileHeight;
-  UInt      m_uiRightEdgePosInCU;
-  UInt      m_uiBottomEdgePosInCU;
-  UInt      m_uiFirstCUAddr;
+  UInt      m_tileWidthInCtus;
+  UInt      m_tileHeightInCtus;
+  UInt      m_rightEdgePosInCtus;
+  UInt      m_bottomEdgePosInCtus;
+  UInt      m_firstCtuRsAddr;
 
-public:  
+public:
   TComTile();
   virtual ~TComTile();
 
-  Void      setTileWidth         ( UInt i )            { m_uiTileWidth = i; }
-  UInt      getTileWidth         ()                    { return m_uiTileWidth; }
-  Void      setTileHeight        ( UInt i )            { m_uiTileHeight = i; }
-  UInt      getTileHeight        ()                    { return m_uiTileHeight; }
-  Void      setRightEdgePosInCU  ( UInt i )            { m_uiRightEdgePosInCU = i; }
-  UInt      getRightEdgePosInCU  ()                    { return m_uiRightEdgePosInCU; }
-  Void      setBottomEdgePosInCU ( UInt i )            { m_uiBottomEdgePosInCU = i; }
-  UInt      getBottomEdgePosInCU ()                    { return m_uiBottomEdgePosInCU; }
-  Void      setFirstCUAddr       ( UInt i )            { m_uiFirstCUAddr = i; }
-  UInt      getFirstCUAddr       ()                    { return m_uiFirstCUAddr; }
+  Void      setTileWidthInCtus     ( UInt i )            { m_tileWidthInCtus = i; }
+  UInt      getTileWidthInCtus     () const              { return m_tileWidthInCtus; }
+  Void      setTileHeightInCtus    ( UInt i )            { m_tileHeightInCtus = i; }
+  UInt      getTileHeightInCtus    () const              { return m_tileHeightInCtus; }
+  Void      setRightEdgePosInCtus  ( UInt i )            { m_rightEdgePosInCtus = i; }
+  UInt      getRightEdgePosInCtus  () const              { return m_rightEdgePosInCtus; }
+  Void      setBottomEdgePosInCtus ( UInt i )            { m_bottomEdgePosInCtus = i; }
+  UInt      getBottomEdgePosInCtus () const              { return m_bottomEdgePosInCtus; }
+  Void      setFirstCtuRsAddr      ( UInt i )            { m_firstCtuRsAddr = i; }
+  UInt      getFirstCtuRsAddr      () const              { return m_firstCtuRsAddr; }
 };
 
@@ -83,68 +84,79 @@
 {
 private:
-  UInt          m_uiWidthInCU;
-  UInt          m_uiHeightInCU;
-  
-  UInt          m_uiMaxCUWidth;
-  UInt          m_uiMaxCUHeight;
+  UInt          m_frameWidthInCtus;
+  UInt          m_frameHeightInCtus;
+
   UInt          m_uiMinCUWidth;
   UInt          m_uiMinCUHeight;
-  
+
   UChar         m_uhTotalDepth;       ///< max. depth
-  UInt          m_uiNumPartitions;
-  UInt          m_uiNumPartInWidth;
-  UInt          m_uiNumPartInHeight;
-  UInt          m_uiNumCUsInFrame;
-  
-  TComSlice**   m_apcTComSlice;
-  UInt          m_uiNumAllocatedSlice;
-  TComDataCU**  m_apcTComDataCU;        ///< array of CU data
-    
-  Int           m_iNumColumnsMinus1; 
-  Int           m_iNumRowsMinus1;
+  UInt          m_numPartitionsInCtu;
+  UInt          m_numPartInCtuWidth;
+  UInt          m_numPartInCtuHeight;
+  UInt          m_numCtusInFrame;
+
+  std::deque<TComSlice*> m_apSlices;
+  TComDataCU**  m_pictureCtuArray;        ///< array of CU data.
+
+  Int           m_numTileColumnsMinus1;
+  Int           m_numTileRowsMinus1;
   std::vector<TComTile> m_tileParameters;
-  UInt*         m_puiCUOrderMap;       //the map of LCU raster scan address relative to LCU encoding order 
-  UInt*         m_puiTileIdxMap;       //the map of the tile index relative to LCU raster scan address 
-  UInt*         m_puiInverseCUOrderMap;
+  UInt*         m_ctuTsToRsAddrMap;    ///< for a given TS (Tile-Scan; coding order) address, returns the RS (Raster-Scan) address. cf CtbAddrTsToRs in specification.
+  UInt*         m_puiTileIdxMap;       ///< the map of the tile index relative to CTU raster scan address
+  UInt*         m_ctuRsToTsAddrMap;    ///< for a given RS (Raster-Scan) address, returns the TS (Tile-Scan; coding order) address. cf CtbAddrRsToTs in specification.
 
-  SAOBlkParam *m_saoBlkParams;
+  SAOBlkParam  *m_saoBlkParams;
+#if ADAPTIVE_QP_SELECTION
+  TCoeff*       m_pParentARLBuffer;
+#endif
+  TComSPS       m_sps;
+  TComPPS       m_pps;
+
+  Void               xInitTiles( );
+  Void               xInitCtuTsRsAddrMaps();
+  Void               setNumTileColumnsMinus1( Int i )                      { m_numTileColumnsMinus1 = i;    }
+  Void               setNumTileRowsMinus1( Int i )                         { m_numTileRowsMinus1 = i;       }
+  Void               setCtuTsToRsAddrMap( Int ctuTsAddr, Int ctuRsAddr )   { *(m_ctuTsToRsAddrMap + ctuTsAddr) = ctuRsAddr; }
+  Void               setCtuRsToTsAddrMap( Int ctuRsAddr, Int ctuTsOrder )  { *(m_ctuRsToTsAddrMap + ctuRsAddr) = ctuTsOrder; }
+
 public:
-  Void        create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
-  Void        destroy ();
+  Void               create  ( const TComSPS &sps, const TComPPS &pps, UInt uiMaxDepth );
+  Void               destroy ();
 
   TComPicSym  ();
-  TComSlice*  getSlice(UInt i)          { return  m_apcTComSlice[i];            }
-  UInt        getFrameWidthInCU()       { return m_uiWidthInCU;                 }
-  UInt        getFrameHeightInCU()      { return m_uiHeightInCU;                }
-  UInt        getMinCUWidth()           { return m_uiMinCUWidth;                }
-  UInt        getMinCUHeight()          { return m_uiMinCUHeight;               }
-  UInt        getNumberOfCUsInFrame()   { return m_uiNumCUsInFrame;  }
-  TComDataCU*&  getCU( UInt uiCUAddr )  { return m_apcTComDataCU[uiCUAddr];     }
-  
-  Void        setSlice(TComSlice* p, UInt i) { m_apcTComSlice[i] = p;           }
-  UInt        getNumAllocatedSlice()    { return m_uiNumAllocatedSlice;         }
-  Void        allocateNewSlice();
-  Void        clearSliceBuffer();
-  UInt        getNumPartition()         { return m_uiNumPartitions;             }
-  UInt        getNumPartInWidth()       { return m_uiNumPartInWidth;            }
-  UInt        getNumPartInHeight()      { return m_uiNumPartInHeight;           }
-  Void         setNumColumnsMinus1( Int i )                          { m_iNumColumnsMinus1 = i; }
-  Int          getNumColumnsMinus1()                                 { return m_iNumColumnsMinus1; }  
-  Void         setNumRowsMinus1( Int i )                             { m_iNumRowsMinus1 = i; }
-  Int          getNumRowsMinus1()                                    { return m_iNumRowsMinus1; }
-  Int          getNumTiles()                                         { return (m_iNumRowsMinus1+1)*(m_iNumColumnsMinus1+1); }
-  TComTile*    getTComTile  ( UInt tileIdx )                         { return &(m_tileParameters[tileIdx]); }
-  Void         setCUOrderMap( Int encCUOrder, Int cuAddr )           { *(m_puiCUOrderMap + encCUOrder) = cuAddr; }
-  UInt         getCUOrderMap( Int encCUOrder )                       { return *(m_puiCUOrderMap + (encCUOrder>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : encCUOrder)); }
-  UInt         getTileIdxMap( Int i )                                { return *(m_puiTileIdxMap + i); }
-  Void         setInverseCUOrderMap( Int cuAddr, Int encCUOrder )    { *(m_puiInverseCUOrderMap + cuAddr) = encCUOrder; }
-  UInt         getInverseCUOrderMap( Int cuAddr )                    { return *(m_puiInverseCUOrderMap + (cuAddr>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : cuAddr)); }
-  UInt         getPicSCUEncOrder( UInt SCUAddr );
-  UInt         getPicSCUAddr( UInt SCUEncOrder );
-  Void         initTiles(TComPPS *pps);
-  UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
-  SAOBlkParam* getSAOBlkParam() { return m_saoBlkParams;}
-  Void deriveLoopFilterBoundaryAvailibility(Int ctu, Bool& isLeftAvail,Bool& isRightAvail,Bool& isAboveAvail,Bool& isBelowAvail,Bool& isAboveLeftAvail,Bool& isAboveRightAvail,Bool& isBelowLeftAvail,Bool& isBelowRightAvail);
+  TComSlice*         getSlice(UInt i)                                      { return m_apSlices[i];             }
+  const TComSlice*   getSlice(UInt i) const                                { return m_apSlices[i];             }
+  UInt               getFrameWidthInCtus() const                           { return m_frameWidthInCtus;            }
+  UInt               getFrameHeightInCtus() const                          { return m_frameHeightInCtus;           }
+  UInt               getMinCUWidth() const                                 { return m_uiMinCUWidth;                }
+  UInt               getMinCUHeight() const                                { return m_uiMinCUHeight;               }
+  UInt               getNumberOfCtusInFrame() const                        { return m_numCtusInFrame;              }
+  TComDataCU*        getCtu( UInt ctuRsAddr )                              { return m_pictureCtuArray[ctuRsAddr];  }
+  const TComDataCU*  getCtu( UInt ctuRsAddr ) const                        { return m_pictureCtuArray[ctuRsAddr];  }
+  const TComSPS&     getSPS()                 const                        { return m_sps; }
+  const TComPPS&     getPPS()                 const                        { return m_pps; }
 
+  TComSlice *        swapSliceObject(TComSlice* p, UInt i)                 { p->setSPS(&m_sps); p->setPPS(&m_pps); TComSlice *pTmp=m_apSlices[i];m_apSlices[i] = p; pTmp->setSPS(0); pTmp->setPPS(0); return pTmp; }
+  UInt               getNumAllocatedSlice() const                          { return UInt(m_apSlices.size());       }
+  Void               allocateNewSlice();
+  Void               clearSliceBuffer();
+  UInt               getNumPartitionsInCtu() const                         { return m_numPartitionsInCtu;   }
+  UInt               getNumPartInCtuWidth() const                          { return m_numPartInCtuWidth;    }
+  UInt               getNumPartInCtuHeight() const                         { return m_numPartInCtuHeight;   }
+  Int                getNumTileColumnsMinus1() const                       { return m_numTileColumnsMinus1; }
+  Int                getNumTileRowsMinus1() const                          { return m_numTileRowsMinus1;    }
+  Int                getNumTiles() const                                   { return (m_numTileRowsMinus1+1)*(m_numTileColumnsMinus1+1); }
+  TComTile*          getTComTile  ( UInt tileIdx )                         { return &(m_tileParameters[tileIdx]); }
+  const TComTile*    getTComTile  ( UInt tileIdx ) const                   { return &(m_tileParameters[tileIdx]); }
+  UInt               getCtuTsToRsAddrMap( Int ctuTsAddr ) const            { return *(m_ctuTsToRsAddrMap + (ctuTsAddr>=m_numCtusInFrame ? m_numCtusInFrame : ctuTsAddr)); }
+  UInt               getTileIdxMap( Int ctuRsAddr ) const                  { return *(m_puiTileIdxMap + ctuRsAddr); }
+  UInt               getCtuRsToTsAddrMap( Int ctuRsAddr ) const            { return *(m_ctuRsToTsAddrMap + (ctuRsAddr>=m_numCtusInFrame ? m_numCtusInFrame : ctuRsAddr)); }
+  SAOBlkParam*       getSAOBlkParam()                                      { return m_saoBlkParams;}
+  const SAOBlkParam* getSAOBlkParam() const                                { return m_saoBlkParams;}
+  Void               deriveLoopFilterBoundaryAvailibility(Int ctuRsAddr,
+                                                          Bool& isLeftAvail, Bool& isRightAvail, Bool& isAboveAvail, Bool& isBelowAvail,
+                                                          Bool& isAboveLeftAvail, Bool& isAboveRightAvail, Bool& isBelowLeftAvail, Bool& isBelowRightAvail);
+protected:
+  UInt               xCalculateNextCtuRSAddr( UInt uiCurrCtuRSAddr );
 
 };// END CLASS DEFINITION TComPicSym
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -47,4 +47,5 @@
 
 #include "TComPicYuv.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
 
 //! \ingroup TLibCommon
@@ -53,27 +54,40 @@
 TComPicYuv::TComPicYuv()
 {
-  m_apiPicBufY      = NULL;   // Buffer (including margin)
-  m_apiPicBufU      = NULL;
-  m_apiPicBufV      = NULL;
-  
-  m_piPicOrgY       = NULL;    // m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
-  m_piPicOrgU       = NULL;
-  m_piPicOrgV       = NULL;
-  
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    m_apiPicBuf[i]    = NULL;   // Buffer (including margin)
+    m_piPicOrg[i]     = NULL;    // m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
+  }
+
+  for(UInt i=0; i<MAX_NUM_CHANNEL_TYPE; i++)
+  {
+    m_ctuOffsetInBuffer[i]=0;
+    m_subCuOffsetInBuffer[i]=0;
+  }
+
   m_bIsBorderExtended = false;
 }
 
+
+
+
 TComPicYuv::~TComPicYuv()
 {
 }
 
-Void TComPicYuv::create( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth )
-{
-  m_iPicWidth       = iPicWidth;
-  m_iPicHeight      = iPicHeight;
-  
-  // --> After config finished!
-  m_iCuWidth        = uiMaxCUWidth;
-  m_iCuHeight       = uiMaxCUHeight;
+
+
+
+Void TComPicYuv::create ( const Int iPicWidth,                ///< picture width
+                          const Int iPicHeight,               ///< picture height
+                          const ChromaFormat chromaFormatIDC, ///< chroma format
+                          const UInt uiMaxCUWidth,            ///< used for generating offsets to CUs. Can use iPicWidth if no offsets are required
+                          const UInt uiMaxCUHeight,           ///< used for generating offsets to CUs. Can use iPicHeight if no offsets are required
+                          const UInt uiMaxCUDepth,            ///< used for generating offsets to CUs. Can use 0 if no offsets are required
+                          const Bool bUseMargin)              ///< if true, then a margin of uiMaxCUWidth+16 and uiMaxCUHeight+16 is created around the image.
+
+{
+  m_iPicWidth         = iPicWidth;
+  m_iPicHeight        = iPicHeight;
 
 #if H_3D_IV_MERGE
@@ -84,42 +98,58 @@
   m_iBaseUnitHeight = uiMaxCUHeight >> uiMaxCUDepth;
 #endif
-  Int numCuInWidth  = m_iPicWidth  / m_iCuWidth  + (m_iPicWidth  % m_iCuWidth  != 0);
-  Int numCuInHeight = m_iPicHeight / m_iCuHeight + (m_iPicHeight % m_iCuHeight != 0);
-  
-  m_iLumaMarginX    = g_uiMaxCUWidth  + 16; // for 16-byte alignment
-  m_iLumaMarginY    = g_uiMaxCUHeight + 16;  // margin for 8-tap filter and infinite padding
-  
-  m_iChromaMarginX  = m_iLumaMarginX>>1;
-  m_iChromaMarginY  = m_iLumaMarginY>>1;
-  
-  m_apiPicBufY      = (Pel*)xMalloc( Pel, ( m_iPicWidth       + (m_iLumaMarginX  <<1)) * ( m_iPicHeight       + (m_iLumaMarginY  <<1)));
-  m_apiPicBufU      = (Pel*)xMalloc( Pel, ((m_iPicWidth >> 1) + (m_iChromaMarginX<<1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY<<1)));
-  m_apiPicBufV      = (Pel*)xMalloc( Pel, ((m_iPicWidth >> 1) + (m_iChromaMarginX<<1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY<<1)));
-  
-  m_piPicOrgY       = m_apiPicBufY + m_iLumaMarginY   * getStride()  + m_iLumaMarginX;
-  m_piPicOrgU       = m_apiPicBufU + m_iChromaMarginY * getCStride() + m_iChromaMarginX;
-  m_piPicOrgV       = m_apiPicBufV + m_iChromaMarginY * getCStride() + m_iChromaMarginX;
-  
+
+  m_chromaFormatIDC   = chromaFormatIDC;
+  m_iMarginX          = (bUseMargin?uiMaxCUWidth:0) + 16;   // for 16-byte alignment
+  m_iMarginY          = (bUseMargin?uiMaxCUHeight:0) + 16;  // margin for 8-tap filter and infinite padding
   m_bIsBorderExtended = false;
-  
-  m_cuOffsetY = new Int[numCuInWidth * numCuInHeight];
-  m_cuOffsetC = new Int[numCuInWidth * numCuInHeight];
-  for (Int cuRow = 0; cuRow < numCuInHeight; cuRow++)
-  {
-    for (Int cuCol = 0; cuCol < numCuInWidth; cuCol++)
-    {
-      m_cuOffsetY[cuRow * numCuInWidth + cuCol] = getStride() * cuRow * m_iCuHeight + cuCol * m_iCuWidth;
-      m_cuOffsetC[cuRow * numCuInWidth + cuCol] = getCStride() * cuRow * (m_iCuHeight / 2) + cuCol * (m_iCuWidth / 2);
-    }
-  }
-  
-  m_buOffsetY = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
-  m_buOffsetC = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
-  for (Int buRow = 0; buRow < (1 << uiMaxCUDepth); buRow++)
-  {
-    for (Int buCol = 0; buCol < (1 << uiMaxCUDepth); buCol++)
-    {
-      m_buOffsetY[(buRow << uiMaxCUDepth) + buCol] = getStride() * buRow * (uiMaxCUHeight >> uiMaxCUDepth) + buCol * (uiMaxCUWidth  >> uiMaxCUDepth);
-      m_buOffsetC[(buRow << uiMaxCUDepth) + buCol] = getCStride() * buRow * (uiMaxCUHeight / 2 >> uiMaxCUDepth) + buCol * (uiMaxCUWidth / 2 >> uiMaxCUDepth);
+
+  // assign the picture arrays and set up the ptr to the top left of the original picture
+  {
+    Int chan=0;
+    for(; chan<getNumberValidComponents(); chan++)
+    {
+      const ComponentID ch=ComponentID(chan);
+      m_apiPicBuf[chan] = (Pel*)xMalloc( Pel, getStride(ch)       * getTotalHeight(ch));
+      m_piPicOrg[chan]  = m_apiPicBuf[chan] + (m_iMarginY >> getComponentScaleY(ch))   * getStride(ch)       + (m_iMarginX >> getComponentScaleX(ch));
+    }
+    for(;chan<MAX_NUM_COMPONENT; chan++)
+    {
+      m_apiPicBuf[chan] = NULL;
+      m_piPicOrg[chan]  = NULL;
+    }
+  }
+
+
+  const Int numCuInWidth  = m_iPicWidth  / uiMaxCUWidth  + (m_iPicWidth  % uiMaxCUWidth  != 0);
+  const Int numCuInHeight = m_iPicHeight / uiMaxCUHeight + (m_iPicHeight % uiMaxCUHeight != 0);
+  for(Int chan=0; chan<2; chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    const Int ctuHeight=uiMaxCUHeight>>getComponentScaleY(ch);
+    const Int ctuWidth=uiMaxCUWidth>>getComponentScaleX(ch);
+    const Int stride = getStride(ch);
+
+    m_ctuOffsetInBuffer[chan] = new Int[numCuInWidth * numCuInHeight];
+
+    for (Int cuRow = 0; cuRow < numCuInHeight; cuRow++)
+    {
+      for (Int cuCol = 0; cuCol < numCuInWidth; cuCol++)
+      {
+        m_ctuOffsetInBuffer[chan][cuRow * numCuInWidth + cuCol] = stride * cuRow * ctuHeight + cuCol * ctuWidth;
+      }
+    }
+
+    m_subCuOffsetInBuffer[chan] = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
+
+    const Int numSubBlockPartitions=(1<<uiMaxCUDepth);
+    const Int minSubBlockHeight    =(ctuHeight >> uiMaxCUDepth);
+    const Int minSubBlockWidth     =(ctuWidth  >> uiMaxCUDepth);
+
+    for (Int buRow = 0; buRow < numSubBlockPartitions; buRow++)
+    {
+      for (Int buCol = 0; buCol < numSubBlockPartitions; buCol++)
+      {
+        m_subCuOffsetInBuffer[chan][(buRow << uiMaxCUDepth) + buCol] = stride  * buRow * minSubBlockHeight + buCol * minSubBlockWidth;
+      }
     }
   }
@@ -127,150 +157,104 @@
 }
 
+
+
 Void TComPicYuv::destroy()
 {
-  m_piPicOrgY       = NULL;
-  m_piPicOrgU       = NULL;
-  m_piPicOrgV       = NULL;
-  
-  if( m_apiPicBufY ){ xFree( m_apiPicBufY );    m_apiPicBufY = NULL; }
-  if( m_apiPicBufU ){ xFree( m_apiPicBufU );    m_apiPicBufU = NULL; }
-  if( m_apiPicBufV ){ xFree( m_apiPicBufV );    m_apiPicBufV = NULL; }
-
-  delete[] m_cuOffsetY;
-  delete[] m_cuOffsetC;
-  delete[] m_buOffsetY;
-  delete[] m_buOffsetC;
-}
-
-Void TComPicYuv::createLuma( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth )
-{
-  m_iPicWidth       = iPicWidth;
-  m_iPicHeight      = iPicHeight;
-  
-  // --> After config finished!
-  m_iCuWidth        = uiMaxCUWidth;
-  m_iCuHeight       = uiMaxCUHeight;
-  
-  Int numCuInWidth  = m_iPicWidth  / m_iCuWidth  + (m_iPicWidth  % m_iCuWidth  != 0);
-  Int numCuInHeight = m_iPicHeight / m_iCuHeight + (m_iPicHeight % m_iCuHeight != 0);
-  
-  m_iLumaMarginX    = g_uiMaxCUWidth  + 16; // for 16-byte alignment
-  m_iLumaMarginY    = g_uiMaxCUHeight + 16;  // margin for 8-tap filter and infinite padding
-  
-  m_apiPicBufY      = (Pel*)xMalloc( Pel, ( m_iPicWidth       + (m_iLumaMarginX  <<1)) * ( m_iPicHeight       + (m_iLumaMarginY  <<1)));
-  m_piPicOrgY       = m_apiPicBufY + m_iLumaMarginY   * getStride()  + m_iLumaMarginX;
-  
-  m_cuOffsetY = new Int[numCuInWidth * numCuInHeight];
-  m_cuOffsetC = NULL;
-  for (Int cuRow = 0; cuRow < numCuInHeight; cuRow++)
-  {
-    for (Int cuCol = 0; cuCol < numCuInWidth; cuCol++)
-    {
-      m_cuOffsetY[cuRow * numCuInWidth + cuCol] = getStride() * cuRow * m_iCuHeight + cuCol * m_iCuWidth;
-    }
-  }
-  
-  m_buOffsetY = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
-  m_buOffsetC = NULL;
-  for (Int buRow = 0; buRow < (1 << uiMaxCUDepth); buRow++)
-  {
-    for (Int buCol = 0; buCol < (1 << uiMaxCUDepth); buCol++)
-    {
-      m_buOffsetY[(buRow << uiMaxCUDepth) + buCol] = getStride() * buRow * (uiMaxCUHeight >> uiMaxCUDepth) + buCol * (uiMaxCUWidth  >> uiMaxCUDepth);
-    }
+  for(Int chan=0; chan<MAX_NUM_COMPONENT; chan++)
+  {
+    m_piPicOrg[chan] = NULL;
+
+    if( m_apiPicBuf[chan] )
+    {
+      xFree( m_apiPicBuf[chan] );
+      m_apiPicBuf[chan] = NULL;
+    }
+  }
+
+  for(UInt chan=0; chan<MAX_NUM_CHANNEL_TYPE; chan++)
+  {
+    if (m_ctuOffsetInBuffer[chan])
+    {
+      delete[] m_ctuOffsetInBuffer[chan];
+      m_ctuOffsetInBuffer[chan] = NULL;
+    }
+    if (m_subCuOffsetInBuffer[chan])
+    {
+      delete[] m_subCuOffsetInBuffer[chan];
+      m_subCuOffsetInBuffer[chan] = NULL;
+    }
+  }
+}
+
+
+
+Void  TComPicYuv::copyToPic (TComPicYuv*  pcPicYuvDst) const
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth(COMPONENT_Y)  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight(COMPONENT_Y) );
+  assert( m_chromaFormatIDC == pcPicYuvDst->getChromaFormat() );
+
+  for(Int chan=0; chan<getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    ::memcpy ( pcPicYuvDst->getBuf(ch), m_apiPicBuf[ch], sizeof (Pel) * getStride(ch) * getTotalHeight(ch));
   }
   return;
 }
 
-Void TComPicYuv::destroyLuma()
-{
-  m_piPicOrgY       = NULL;
-  
-  if( m_apiPicBufY ){ xFree( m_apiPicBufY );    m_apiPicBufY = NULL; }
-  
-  delete[] m_cuOffsetY;
-  delete[] m_buOffsetY;
-}
-
-Void  TComPicYuv::copyToPic (TComPicYuv*  pcPicYuvDst)
-{
-  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
-  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
-  
-  ::memcpy ( pcPicYuvDst->getBufY(), m_apiPicBufY, sizeof (Pel) * ( m_iPicWidth       + (m_iLumaMarginX   << 1)) * ( m_iPicHeight       + (m_iLumaMarginY   << 1)) );
-  ::memcpy ( pcPicYuvDst->getBufU(), m_apiPicBufU, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
-  ::memcpy ( pcPicYuvDst->getBufV(), m_apiPicBufV, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
-  return;
-}
-
-Void  TComPicYuv::copyToPicLuma (TComPicYuv*  pcPicYuvDst)
-{
-  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
-  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
-  
-  ::memcpy ( pcPicYuvDst->getBufY(), m_apiPicBufY, sizeof (Pel) * ( m_iPicWidth       + (m_iLumaMarginX   << 1)) * ( m_iPicHeight       + (m_iLumaMarginY   << 1)) );
-  return;
-}
-
-Void  TComPicYuv::copyToPicCb (TComPicYuv*  pcPicYuvDst)
-{
-  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
-  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
-  
-  ::memcpy ( pcPicYuvDst->getBufU(), m_apiPicBufU, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
-  return;
-}
-
-Void  TComPicYuv::copyToPicCr (TComPicYuv*  pcPicYuvDst)
-{
-  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
-  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
-  
-  ::memcpy ( pcPicYuvDst->getBufV(), m_apiPicBufV, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
-  return;
-}
 
 Void TComPicYuv::extendPicBorder ()
 {
-  if ( m_bIsBorderExtended ) return;
-  
-  xExtendPicCompBorder( getLumaAddr(), getStride(),  getWidth(),      getHeight(),      m_iLumaMarginX,   m_iLumaMarginY   );
-  xExtendPicCompBorder( getCbAddr()  , getCStride(), getWidth() >> 1, getHeight() >> 1, m_iChromaMarginX, m_iChromaMarginY );
-  xExtendPicCompBorder( getCrAddr()  , getCStride(), getWidth() >> 1, getHeight() >> 1, m_iChromaMarginX, m_iChromaMarginY );
-  
+  if ( m_bIsBorderExtended )
+  {
+    return;
+  }
+
+  for(Int chan=0; chan<getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    Pel *piTxt=getAddr(ch); // piTxt = point to (0,0) of image within bigger picture.
+    const Int iStride=getStride(ch);
+    const Int iWidth=getWidth(ch);
+    const Int iHeight=getHeight(ch);
+    const Int iMarginX=getMarginX(ch);
+    const Int iMarginY=getMarginY(ch);
+
+    Pel*  pi = piTxt;
+    // do left and right margins
+    for (Int y = 0; y < iHeight; y++)
+    {
+      for (Int x = 0; x < iMarginX; x++ )
+      {
+        pi[ -iMarginX + x ] = pi[0];
+        pi[    iWidth + x ] = pi[iWidth-1];
+      }
+      pi += iStride;
+    }
+
+    // pi is now the (0,height) (bottom left of image within bigger picture
+    pi -= (iStride + iMarginX);
+    // pi is now the (-marginX, height-1)
+    for (Int y = 0; y < iMarginY; y++ )
+    {
+      ::memcpy( pi + (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+    }
+
+    // pi is still (-marginX, height-1)
+    pi -= ((iHeight-1) * iStride);
+    // pi is now (-marginX, 0)
+    for (Int y = 0; y < iMarginY; y++ )
+    {
+      ::memcpy( pi - (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+    }
+  }
+
   m_bIsBorderExtended = true;
 }
 
-Void TComPicYuv::xExtendPicCompBorder  (Pel* piTxt, Int iStride, Int iWidth, Int iHeight, Int iMarginX, Int iMarginY)
-{
-  Int   x, y;
-  Pel*  pi;
-  
-  pi = piTxt;
-  for ( y = 0; y < iHeight; y++)
-  {
-    for ( x = 0; x < iMarginX; x++ )
-    {
-      pi[ -iMarginX + x ] = pi[0];
-      pi[    iWidth + x ] = pi[iWidth-1];
-    }
-    pi += iStride;
-  }
-  
-  pi -= (iStride + iMarginX);
-  for ( y = 0; y < iMarginY; y++ )
-  {
-    ::memcpy( pi + (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
-  }
-  
-  pi -= ((iHeight-1) * iStride);
-  for ( y = 0; y < iMarginY; y++ )
-  {
-    ::memcpy( pi - (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
-  }
-}
-
-
-Void TComPicYuv::dump (Char* pFileName, Bool bAdd)
+
+
+// NOTE: This function is never called, but may be useful for developers.
+Void TComPicYuv::dump (const Char* pFileName, const BitDepths &bitDepths, Bool bAdd) const
 {
   FILE* pFile;
@@ -283,52 +267,29 @@
     pFile = fopen (pFileName, "ab");
   }
-  
-  Int     shift = g_bitDepthY-8;
-  Int     offset = (shift>0)?(1<<(shift-1)):0;
-  
-  Int   x, y;
-  UChar uc;
-  
-  Pel*  piY   = getLumaAddr();
-  Pel*  piCb  = getCbAddr();
-  Pel*  piCr  = getCrAddr();
-  
-  for ( y = 0; y < m_iPicHeight; y++ )
-  {
-    for ( x = 0; x < m_iPicWidth; x++ )
-    {
-      uc = (UChar)Clip3<Pel>(0, 255, (piY[x]+offset)>>shift);
-      
-      fwrite( &uc, sizeof(UChar), 1, pFile );
-    }
-    piY += getStride();
-  }
-  
-  shift = g_bitDepthC-8;
-  offset = (shift>0)?(1<<(shift-1)):0;
-
-  for ( y = 0; y < m_iPicHeight >> 1; y++ )
-  {
-    for ( x = 0; x < m_iPicWidth >> 1; x++ )
-    {
-      uc = (UChar)Clip3<Pel>(0, 255, (piCb[x]+offset)>>shift);
-      fwrite( &uc, sizeof(UChar), 1, pFile );
-    }
-    piCb += getCStride();
-  }
-  
-  for ( y = 0; y < m_iPicHeight >> 1; y++ )
-  {
-    for ( x = 0; x < m_iPicWidth >> 1; x++ )
-    {
-      uc = (UChar)Clip3<Pel>(0, 255, (piCr[x]+offset)>>shift);
-      fwrite( &uc, sizeof(UChar), 1, pFile );
-    }
-    piCr += getCStride();
-  }
-  
+
+
+  for(Int chan = 0; chan < getNumberValidComponents(); chan++)
+  {
+    const ComponentID  ch     = ComponentID(chan);
+    const Int          shift  = bitDepths.recon[toChannelType(ch)] - 8;
+    const Int          offset = (shift>0)?(1<<(shift-1)):0;
+    const Pel         *pi     = getAddr(ch);
+    const Int          stride = getStride(ch);
+    const Int          height = getHeight(ch);
+    const Int          width  = getWidth(ch);
+
+    for (Int y = 0; y < height; y++ )
+    {
+      for (Int x = 0; x < width; x++ )
+      {
+        UChar uc = (UChar)Clip3<Pel>(0, 255, (pi[x]+offset)>>shift);
+        fwrite( &uc, sizeof(UChar), 1, pFile );
+      }
+      pi += stride;
+    }
+  }
+
   fclose(pFile);
 }
-
 #if H_3D
 #if H_3D_IV_MERGE
@@ -363,9 +324,10 @@
   xSetPels( getLumaAddr(), getStride(), getWidth(), getHeight(), pVal );
 }
-
+#endif
+#if NH_3D_VSO
 Void TComPicYuv::setChromaTo( Pel pVal )
 {
-  xSetPels( getCbAddr(), getCStride(), getWidth() >> 1, getHeight() >> 1, pVal ); 
-  xSetPels( getCrAddr(), getCStride(), getWidth() >> 1, getHeight() >> 1, pVal );
+  xSetPels( getAddr( COMPONENT_Cb ), getStride( COMPONENT_Cb ), getWidth( COMPONENT_Cb), getHeight( COMPONENT_Cb ), pVal ); 
+  xSetPels( getAddr( COMPONENT_Cr ), getStride( COMPONENT_Cr ), getWidth( COMPONENT_Cr), getHeight( COMPONENT_Cr ), pVal );
 }
 
@@ -382,4 +344,3 @@
 }
 #endif
-
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuv.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuv.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -42,4 +42,6 @@
 #include "CommonDef.h"
 #include "TComRom.h"
+#include "TComChromaFormat.h"
+#include "SEI.h"
 
 //! \ingroup TLibCommon
@@ -54,38 +56,28 @@
 {
 private:
-  
+
   // ------------------------------------------------------------------------------------------------
   //  YUV buffer
   // ------------------------------------------------------------------------------------------------
-  
-  Pel*  m_apiPicBufY;           ///< Buffer (including margin)
-  Pel*  m_apiPicBufU;
-  Pel*  m_apiPicBufV;
-  
-  Pel*  m_piPicOrgY;            ///< m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
-  Pel*  m_piPicOrgU;
-  Pel*  m_piPicOrgV;
-  
+
+  Pel*  m_apiPicBuf[MAX_NUM_COMPONENT];             ///< Buffer (including margin)
+
+  Pel*  m_piPicOrg[MAX_NUM_COMPONENT];              ///< m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
+
   // ------------------------------------------------------------------------------------------------
   //  Parameter for general YUV buffer usage
   // ------------------------------------------------------------------------------------------------
-  
-  Int   m_iPicWidth;            ///< Width of picture
-  Int   m_iPicHeight;           ///< Height of picture
-  
-  Int   m_iCuWidth;             ///< Width of Coding Unit (CU)
-  Int   m_iCuHeight;            ///< Height of Coding Unit (CU)
-  Int*  m_cuOffsetY;
-  Int*  m_cuOffsetC;
-  Int*  m_buOffsetY;
-  Int*  m_buOffsetC;
-  
-  Int   m_iLumaMarginX;
-  Int   m_iLumaMarginY;
-  Int   m_iChromaMarginX;
-  Int   m_iChromaMarginY;
-  
+
+  Int   m_iPicWidth;                                ///< Width of picture in pixels
+  Int   m_iPicHeight;                               ///< Height of picture in pixels
+  ChromaFormat m_chromaFormatIDC;                   ///< Chroma Format
+
+  Int*  m_ctuOffsetInBuffer[MAX_NUM_CHANNEL_TYPE];  ///< Gives an offset in the buffer for a given CTU (and channel)
+  Int*  m_subCuOffsetInBuffer[MAX_NUM_CHANNEL_TYPE];///< Gives an offset in the buffer for a given sub-CU (and channel), relative to start of CTU
+
+  Int   m_iMarginX;                                 ///< margin of Luma channel (chroma's may be smaller, depending on ratio)
+  Int   m_iMarginY;                                 ///< margin of Luma channel (chroma's may be smaller, depending on ratio)
+
   Bool  m_bIsBorderExtended;
-  
 #if H_3D_IV_MERGE
   Int   m_iBaseUnitWidth;       ///< Width of Base Unit (with maximum depth or minimum size, m_iCuWidth >> Max. Depth)
@@ -93,78 +85,84 @@
   Int   m_iNumCuInWidth;
 #endif
-protected:
-  Void  xExtendPicCompBorder (Pel* piTxt, Int iStride, Int iWidth, Int iHeight, Int iMarginX, Int iMarginY);
-#if H_3D
+
+#if NH_3D_VSO
   Void  xSetPels( Pel* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal );
 #endif
-  
+
 public:
-  TComPicYuv         ();
-  virtual ~TComPicYuv();
-  
+               TComPicYuv         ();
+  virtual     ~TComPicYuv         ();
+
   // ------------------------------------------------------------------------------------------------
   //  Memory management
   // ------------------------------------------------------------------------------------------------
-  
-  Void  create      ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
-  Void  destroy     ();
-  
-  Void  createLuma  ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uhMaxCUDepth );
-  Void  destroyLuma ();
-  
+
+  Void          create            (const Int iPicWidth,
+                                   const Int iPicHeight,
+                                   const ChromaFormat chromaFormatIDC,
+                                   const UInt uiMaxCUWidth,  ///< used for generating offsets to CUs. Can use iPicWidth if no offsets are required
+                                   const UInt uiMaxCUHeight, ///< used for generating offsets to CUs. Can use iPicHeight if no offsets are required
+                                   const UInt uiMaxCUDepth,  ///< used for generating offsets to CUs. Can use 0 if no offsets are required
+                                   const Bool bUseMargin);   ///< if true, then a margin of uiMaxCUWidth+16 and uiMaxCUHeight+16 is created around the image.
+
+  Void          destroy           ();
+
+  // The following have been removed - Use CHROMA_400 in the above function call.
+  //Void  createLuma  ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uhMaxCUDepth );
+  //Void  destroyLuma ();
+
   // ------------------------------------------------------------------------------------------------
   //  Get information of picture
   // ------------------------------------------------------------------------------------------------
-  
-  Int   getWidth    ()     { return  m_iPicWidth;    }
-  Int   getHeight   ()     { return  m_iPicHeight;   }
-  
-  Int   getStride   ()     { return (m_iPicWidth     ) + (m_iLumaMarginX  <<1); }
-  Int   getCStride  ()     { return (m_iPicWidth >> 1) + (m_iChromaMarginX<<1); }
-  
-  Int   getLumaMargin   () { return m_iLumaMarginX;  }
-  Int   getChromaMargin () { return m_iChromaMarginX;}
-  
+
+  Int           getWidth          (const ComponentID id) const { return  m_iPicWidth >> getComponentScaleX(id);   }
+  Int           getHeight         (const ComponentID id) const { return  m_iPicHeight >> getComponentScaleY(id);  }
+  ChromaFormat  getChromaFormat   ()                     const { return m_chromaFormatIDC; }
+  UInt          getNumberValidComponents() const { return ::getNumberValidComponents(m_chromaFormatIDC); }
+
+  Int           getStride         (const ComponentID id) const { return ((m_iPicWidth     ) + (m_iMarginX  <<1)) >> getComponentScaleX(id); }
+  Int           getTotalHeight    (const ComponentID id) const { return ((m_iPicHeight    ) + (m_iMarginY  <<1)) >> getComponentScaleY(id); }
+
+  Int           getMarginX        (const ComponentID id) const { return m_iMarginX >> getComponentScaleX(id);  }
+  Int           getMarginY        (const ComponentID id) const { return m_iMarginY >> getComponentScaleY(id);  }
+
   // ------------------------------------------------------------------------------------------------
   //  Access function for picture buffer
   // ------------------------------------------------------------------------------------------------
-  
+
   //  Access starting position of picture buffer with margin
-  Pel*  getBufY     ()     { return  m_apiPicBufY;   }
-  Pel*  getBufU     ()     { return  m_apiPicBufU;   }
-  Pel*  getBufV     ()     { return  m_apiPicBufV;   }
-  
+  Pel*          getBuf            (const ComponentID ch)       { return  m_apiPicBuf[ch];   }
+
   //  Access starting position of original picture
-  Pel*  getLumaAddr ()     { return  m_piPicOrgY;    }
-  Pel*  getCbAddr   ()     { return  m_piPicOrgU;    }
-  Pel*  getCrAddr   ()     { return  m_piPicOrgV;    }
-  
+  Pel*          getAddr           (const ComponentID ch)       { return  m_piPicOrg[ch];   }
+  const Pel*    getAddr           (const ComponentID ch) const { return  m_piPicOrg[ch];   }
+
   //  Access starting position of original picture for specific coding unit (CU) or partition unit (PU)
-  Pel*  getLumaAddr ( Int iCuAddr ) { return m_piPicOrgY + m_cuOffsetY[ iCuAddr ]; }
-  Pel*  getCbAddr   ( Int iCuAddr ) { return m_piPicOrgU + m_cuOffsetC[ iCuAddr ]; }
-  Pel*  getCrAddr   ( Int iCuAddr ) { return m_piPicOrgV + m_cuOffsetC[ iCuAddr ]; }
-  Pel*  getLumaAddr ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgY + m_cuOffsetY[iCuAddr] + m_buOffsetY[g_auiZscanToRaster[uiAbsZorderIdx]]; }
-  Pel*  getCbAddr   ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgU + m_cuOffsetC[iCuAddr] + m_buOffsetC[g_auiZscanToRaster[uiAbsZorderIdx]]; }
-  Pel*  getCrAddr   ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgV + m_cuOffsetC[iCuAddr] + m_buOffsetC[g_auiZscanToRaster[uiAbsZorderIdx]]; }
-  
+  Pel*          getAddr           (const ComponentID ch, const Int ctuRSAddr )       { return m_piPicOrg[ch] + m_ctuOffsetInBuffer[ch==0?0:1][ ctuRSAddr ]; }
+  const Pel*    getAddr           (const ComponentID ch, const Int ctuRSAddr ) const { return m_piPicOrg[ch] + m_ctuOffsetInBuffer[ch==0?0:1][ ctuRSAddr ]; }
+  Pel*          getAddr           (const ComponentID ch, const Int ctuRSAddr, const Int uiAbsZorderIdx )
+                                     { return m_piPicOrg[ch] + m_ctuOffsetInBuffer[ch==0?0:1][ctuRSAddr] + m_subCuOffsetInBuffer[ch==0?0:1][g_auiZscanToRaster[uiAbsZorderIdx]]; }
+  const Pel*    getAddr           (const ComponentID ch, const Int ctuRSAddr, const Int uiAbsZorderIdx ) const
+                                     { return m_piPicOrg[ch] + m_ctuOffsetInBuffer[ch==0?0:1][ctuRSAddr] + m_subCuOffsetInBuffer[ch==0?0:1][g_auiZscanToRaster[uiAbsZorderIdx]]; }
+
+  UInt          getComponentScaleX(const ComponentID id) const { return ::getComponentScaleX(id, m_chromaFormatIDC); }
+  UInt          getComponentScaleY(const ComponentID id) const { return ::getComponentScaleY(id, m_chromaFormatIDC); }
+
   // ------------------------------------------------------------------------------------------------
   //  Miscellaneous
   // ------------------------------------------------------------------------------------------------
-  
+
   //  Copy function to picture
-  Void  copyToPic       ( TComPicYuv*  pcPicYuvDst );
-  Void  copyToPicLuma   ( TComPicYuv*  pcPicYuvDst );
-  Void  copyToPicCb     ( TComPicYuv*  pcPicYuvDst );
-  Void  copyToPicCr     ( TComPicYuv*  pcPicYuvDst );
-  
+  Void          copyToPic         ( TComPicYuv*  pcPicYuvDst ) const ;
+
   //  Extend function of picture buffer
-  Void  extendPicBorder      ();
-  
+  Void          extendPicBorder   ();
+
   //  Dump picture
-  Void  dump (Char* pFileName, Bool bAdd = false);
-  
+  Void          dump              (const Char* pFileName, const BitDepths &bitDepths, Bool bAdd = false) const ;
+
   // Set border extension flag
-  Void  setBorderExtension(Bool b) { m_bIsBorderExtended = b; }
-#if H_3D
+  Void          setBorderExtension(Bool b) { m_bIsBorderExtended = b; }
+#if NH_3D
   // Set Function 
   Void  setLumaTo    ( Pel pVal );  
@@ -176,9 +174,13 @@
 #endif
 #endif
+
 };// END CLASS DEFINITION TComPicYuv
 
-void calcChecksum(TComPicYuv& pic, UChar digest[3][16]);
-void calcCRC(TComPicYuv& pic, UChar digest[3][16]);
-void calcMD5(TComPicYuv& pic, UChar digest[3][16]);
+
+// These functions now return the length of the digest strings.
+UInt calcChecksum(const TComPicYuv& pic, TComPictureHash &digest, const BitDepths &bitDepths);
+UInt calcCRC     (const TComPicYuv& pic, TComPictureHash &digest, const BitDepths &bitDepths);
+UInt calcMD5     (const TComPicYuv& pic, TComPictureHash &digest, const BitDepths &bitDepths);
+std::string hashToString(const TComPictureHash &digest, Int numChar);
 //! \}
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -43,5 +43,5 @@
  */
 template<UInt OUTPUT_BITDEPTH_DIV8>
-static void md5_block(MD5& md5, const Pel* plane, UInt n)
+static Void md5_block(MD5& md5, const Pel* plane, UInt n)
 {
   /* create a 64 byte buffer for packing Pel's into */
@@ -64,5 +64,5 @@
  */
 template<UInt OUTPUT_BITDEPTH_DIV8>
-static void md5_plane(MD5& md5, const Pel* plane, UInt width, UInt height, UInt stride)
+static Void md5_plane(MD5& md5, const Pel* plane, UInt width, UInt height, UInt stride)
 {
   /* N is the number of samples to process per md5 update.
@@ -74,8 +74,10 @@
   for (UInt y = 0; y < height; y++)
   {
-    /* convert pel's into UInt chars in little endian byte order.
+    /* convert pels into unsigned chars in little endian byte order.
      * NB, for 8bit data, data is truncated to 8bits. */
     for (UInt x = 0; x < width_less_modN; x += N)
+    {
       md5_block<OUTPUT_BITDEPTH_DIV8>(md5, &plane[y*stride + x], N);
+    }
 
     /* mop up any of the remaining line */
@@ -84,5 +86,6 @@
 }
 
-static void compCRC(Int bitdepth, const Pel* plane, UInt width, UInt height, UInt stride, UChar digest[16])
+
+UInt compCRC(Int bitdepth, const Pel* plane, UInt width, UInt height, UInt stride, TComPictureHash &digest)
 {
   UInt crcMsb;
@@ -119,25 +122,22 @@
   }
 
-  digest[0] = (crcVal>>8)  & 0xff;
-  digest[1] =  crcVal      & 0xff;
-}
-
-void calcCRC(TComPicYuv& pic, UChar digest[3][16])
-{
-  UInt width = pic.getWidth();
-  UInt height = pic.getHeight();
-  UInt stride = pic.getStride();
-
-  compCRC(g_bitDepthY, pic.getLumaAddr(), width, height, stride, digest[0]);
-
-  width >>= 1;
-  height >>= 1;
-  stride >>= 1;
-
-  compCRC(g_bitDepthC, pic.getCbAddr(), width, height, stride, digest[1]);
-  compCRC(g_bitDepthC, pic.getCrAddr(), width, height, stride, digest[2]);
-}
-
-static void compChecksum(Int bitdepth, const Pel* plane, UInt width, UInt height, UInt stride, UChar digest[16])
+  digest.hash.push_back((crcVal>>8)  & 0xff);
+  digest.hash.push_back( crcVal      & 0xff);
+  return 2;
+}
+
+UInt calcCRC(const TComPicYuv& pic, TComPictureHash &digest, const BitDepths &bitDepths)
+{
+  UInt digestLen=0;
+  digest.hash.clear();
+  for(Int chan=0; chan<pic.getNumberValidComponents(); chan++)
+  {
+    const ComponentID compID=ComponentID(chan);
+    digestLen=compCRC(bitDepths.recon[toChannelType(compID)], pic.getAddr(compID), pic.getWidth(compID), pic.getHeight(compID), pic.getStride(compID), digest);
+  }
+  return digestLen;
+}
+
+UInt compChecksum(Int bitdepth, const Pel* plane, UInt width, UInt height, UInt stride, TComPictureHash &digest, const BitDepths &/*bitDepths*/)
 {
   UInt checksum = 0;
@@ -158,24 +158,21 @@
   }
 
-  digest[0] = (checksum>>24) & 0xff;
-  digest[1] = (checksum>>16) & 0xff;
-  digest[2] = (checksum>>8)  & 0xff;
-  digest[3] =  checksum      & 0xff;
-}
-
-void calcChecksum(TComPicYuv& pic, UChar digest[3][16])
-{
-  UInt width = pic.getWidth();
-  UInt height = pic.getHeight();
-  UInt stride = pic.getStride();
-
-  compChecksum(g_bitDepthY, pic.getLumaAddr(), width, height, stride, digest[0]);
-
-  width >>= 1;
-  height >>= 1;
-  stride >>= 1;
-
-  compChecksum(g_bitDepthC, pic.getCbAddr(), width, height, stride, digest[1]);
-  compChecksum(g_bitDepthC, pic.getCrAddr(), width, height, stride, digest[2]);
+  digest.hash.push_back((checksum>>24) & 0xff);
+  digest.hash.push_back((checksum>>16) & 0xff);
+  digest.hash.push_back((checksum>>8)  & 0xff);
+  digest.hash.push_back( checksum      & 0xff);
+  return 4;
+}
+
+UInt calcChecksum(const TComPicYuv& pic, TComPictureHash &digest, const BitDepths &bitDepths)
+{
+  UInt digestLen=0;
+  digest.hash.clear();
+  for(Int chan=0; chan<pic.getNumberValidComponents(); chan++)
+  {
+    const ComponentID compID=ComponentID(chan);
+    digestLen=compChecksum(bitDepths.recon[toChannelType(compID)], pic.getAddr(compID), pic.getWidth(compID), pic.getHeight(compID), pic.getStride(compID), digest, bitDepths);
+  }
+  return digestLen;
 }
 /**
@@ -186,29 +183,45 @@
  * uses little-endian two byte words; 8bit data uses single byte words.
  */
-void calcMD5(TComPicYuv& pic, UChar digest[3][16])
+UInt calcMD5(const TComPicYuv& pic, TComPictureHash &digest, const BitDepths &bitDepths)
 {
   /* choose an md5_plane packing function based on the system bitdepth */
-  typedef void (*MD5PlaneFunc)(MD5&, const Pel*, UInt, UInt, UInt);
+  typedef Void (*MD5PlaneFunc)(MD5&, const Pel*, UInt, UInt, UInt);
   MD5PlaneFunc md5_plane_func;
-  md5_plane_func = g_bitDepthY <= 8 ? (MD5PlaneFunc)md5_plane<1> : (MD5PlaneFunc)md5_plane<2>;
-
-  MD5 md5Y, md5U, md5V;
-  UInt width = pic.getWidth();
-  UInt height = pic.getHeight();
-  UInt stride = pic.getStride();
-
-  md5_plane_func(md5Y, pic.getLumaAddr(), width, height, stride);
-  md5Y.finalize(digest[0]);
-
-  md5_plane_func = g_bitDepthC <= 8 ? (MD5PlaneFunc)md5_plane<1> : (MD5PlaneFunc)md5_plane<2>;
-  width >>= 1;
-  height >>= 1;
-  stride >>= 1;
-
-  md5_plane_func(md5U, pic.getCbAddr(), width, height, stride);
-  md5U.finalize(digest[1]);
-
-  md5_plane_func(md5V, pic.getCrAddr(), width, height, stride);
-  md5V.finalize(digest[2]);
-}
+
+  MD5 md5[MAX_NUM_COMPONENT];
+
+  digest.hash.clear();
+  for(Int chan=0; chan<pic.getNumberValidComponents(); chan++)
+  {
+    const ComponentID compID=ComponentID(chan);
+    md5_plane_func = bitDepths.recon[toChannelType(compID)] <= 8 ? (MD5PlaneFunc)md5_plane<1> : (MD5PlaneFunc)md5_plane<2>;
+    UChar tmp_digest[MD5_DIGEST_STRING_LENGTH];
+    md5_plane_func(md5[compID], pic.getAddr(compID), pic.getWidth(compID), pic.getHeight(compID), pic.getStride(compID));
+    md5[compID].finalize(tmp_digest);
+    for(UInt i=0; i<MD5_DIGEST_STRING_LENGTH; i++)
+    {
+      digest.hash.push_back(tmp_digest[i]);
+    }
+  }
+  return 16;
+}
+
+std::string hashToString(const TComPictureHash &digest, Int numChar)
+{
+  static const Char* hex = "0123456789abcdef";
+  std::string result;
+
+  for(Int pos=0; pos<Int(digest.hash.size()); pos++)
+  {
+    if ((pos % numChar) == 0 && pos!=0 )
+    {
+      result += ',';
+    }
+    result += hex[digest.hash[pos] >> 4];
+    result += hex[digest.hash[pos] & 0xf];
+  }
+
+  return result;
+}
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,7 +38,32 @@
 #include <memory.h>
 #include "TComPrediction.h"
+#include "TComPic.h"
+#include "TComTU.h"
 
 //! \ingroup TLibCommon
 //! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar TComPrediction::m_aucIntraFilter[MAX_NUM_CHANNEL_TYPE][MAX_INTRA_FILTER_DEPTHS] =
+{
+  { // Luma
+    10, //4x4
+    7, //8x8
+    1, //16x16
+    0, //32x32
+    10, //64x64
+  },
+  { // Chroma
+    10, //4xn
+    7, //8xn
+    1, //16xn
+    0, //32xn
+    10, //64xn
+  }
+
+};
 
 // ====================================================================================================================
@@ -50,5 +75,11 @@
 , m_iLumaRecStride(0)
 {
-  m_piYuvExt = NULL;
+  for(UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    for(UInt buf=0; buf<2; buf++)
+    {
+      m_piYuvExt[ch][buf] = NULL;
+    }
+  }
 #if H_3D_VSP
   m_pDepthBlock = (Int*) malloc(MAX_NUM_SPU_W*MAX_NUM_SPU_W*sizeof(Int));
@@ -58,4 +89,5 @@
   }
 #endif
+
 }
 
@@ -70,8 +102,22 @@
 #endif
 
-  delete[] m_piYuvExt;
-
-  m_acYuvPred[0].destroy();
-  m_acYuvPred[1].destroy();
+  destroy();
+}
+
+Void TComPrediction::destroy()
+{
+  for(UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    for(UInt buf=0; buf<NUM_PRED_BUF; buf++)
+    {
+      delete [] m_piYuvExt[ch][buf];
+      m_piYuvExt[ch][buf] = NULL;
+    }
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acYuvPred[i].destroy();
+  }
 
   m_cYuvPredTemp.destroy();
@@ -84,10 +130,11 @@
   {
     delete [] m_pLumaRecBuffer;
-  }
-  
-  Int i, j;
-  for (i = 0; i < 4; i++)
-  {
-    for (j = 0; j < 4; j++)
+    m_pLumaRecBuffer = 0;
+  }
+  m_iLumaRecStride = 0;
+
+  for (UInt i = 0; i < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS; i++)
+  {
+    for (UInt j = 0; j < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS; j++)
     {
       m_filteredBlock[i][j].destroy();
@@ -97,28 +144,42 @@
 }
 
-Void TComPrediction::initTempBuff()
-{
-  if( m_piYuvExt == NULL )
-  {
-    Int extWidth  = MAX_CU_SIZE + 16; 
+Void TComPrediction::initTempBuff(ChromaFormat chromaFormatIDC)
+{
+  // if it has been initialised before, but the chroma format has changed, release the memory and start again.
+  if( m_piYuvExt[COMPONENT_Y][PRED_BUF_UNFILTERED] != NULL && m_cYuvPredTemp.getChromaFormat()!=chromaFormatIDC)
+  {
+    destroy();
+  }
+
+  if( m_piYuvExt[COMPONENT_Y][PRED_BUF_UNFILTERED] == NULL ) // check if first is null (in which case, nothing initialised yet)
+  {
+    Int extWidth  = MAX_CU_SIZE + 16;
     Int extHeight = MAX_CU_SIZE + 1;
-    Int i, j;
-    for (i = 0; i < 4; i++)
-    {
-      m_filteredBlockTmp[i].create(extWidth, extHeight + 7);
-      for (j = 0; j < 4; j++)
-      {
-        m_filteredBlock[i][j].create(extWidth, extHeight);
-      }
-    }
-    m_iYuvExtHeight  = ((MAX_CU_SIZE + 2) << 4);
-    m_iYuvExtStride = ((MAX_CU_SIZE  + 8) << 4);
-    m_piYuvExt = new Int[ m_iYuvExtStride * m_iYuvExtHeight ];
+
+    for (UInt i = 0; i < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS; i++)
+    {
+      m_filteredBlockTmp[i].create(extWidth, extHeight + 7, chromaFormatIDC);
+      for (UInt j = 0; j < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS; j++)
+      {
+        m_filteredBlock[i][j].create(extWidth, extHeight, chromaFormatIDC);
+      }
+    }
+
+    m_iYuvExtSize = (MAX_CU_SIZE*2+1) * (MAX_CU_SIZE*2+1);
+    for(UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+    {
+      for(UInt buf=0; buf<NUM_PRED_BUF; buf++)
+      {
+        m_piYuvExt[ch][buf] = new Pel[ m_iYuvExtSize ];
+      }
+    }
 
     // new structure
-    m_acYuvPred[0] .create( MAX_CU_SIZE, MAX_CU_SIZE );
-    m_acYuvPred[1] .create( MAX_CU_SIZE, MAX_CU_SIZE );
-
-    m_cYuvPredTemp.create( MAX_CU_SIZE, MAX_CU_SIZE );
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acYuvPred[i] .create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
+    }
+
+    m_cYuvPredTemp.create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
 #if H_3D_ARP
     m_acYuvPredBase[0] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
@@ -128,5 +189,7 @@
     m_cYuvDepthOnVsp.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
 #endif
-  }
+
+  }
+
 
   if (m_iLumaRecStride != (MAX_CU_SIZE>>1) + 1)
@@ -152,5 +215,6 @@
 
 // Function for calculating DC value of the reference samples used in Intra prediction
-Pel TComPrediction::predIntraGetPredValDC( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft )
+//NOTE: Bit-Limit - 25-bit source
+Pel TComPrediction::predIntraGetPredValDC( const Pel* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft )
 {
   assert(iWidth > 0 && iHeight > 0);
@@ -189,5 +253,5 @@
     pDcVal = pSrc[-1]; // Default DC value already calculated and placed in the prediction array if no neighbors are available
   }
-  
+
   return pDcVal;
 }
@@ -196,13 +260,17 @@
 
 /** Function for deriving the simplified angular intra predictions.
- * \param pSrc pointer to reconstructed sample array
- * \param srcStride the stride of the reconstructed sample array
- * \param rpDst reference to pointer for the prediction sample array
- * \param dstStride the stride of the prediction sample array
- * \param width the width of the block
- * \param height the height of the block
- * \param dirMode the intra prediction mode index
- * \param blkAboveAvailable boolean indication if the block above is available
- * \param blkLeftAvailable boolean indication if the block to the left is available
+ * \param bitDepth           bit depth
+ * \param pSrc               pointer to reconstructed sample array
+ * \param srcStride          the stride of the reconstructed sample array
+ * \param pTrueDst           reference to pointer for the prediction sample array
+ * \param dstStrideTrue      the stride of the prediction sample array
+ * \param uiWidth            the width of the block
+ * \param uiHeight           the height of the block
+ * \param channelType        type of pel array (luma/chroma)
+ * \param format             chroma format
+ * \param dirMode            the intra prediction mode index
+ * \param blkAboveAvailable  boolean indication if the block above is available
+ * \param blkLeftAvailable   boolean indication if the block to the left is available
+ * \param bEnableEdgeFilters indication whether to enable edge filters
  *
  * This function derives the prediction samples for the angular mode based on the prediction direction indicated by
@@ -214,45 +282,51 @@
  * from the extended main reference.
  */
-Void TComPrediction::xPredIntraAng(Int bitDepth, Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, Bool bFilter )
-{
-  Int k,l;
-  Int blkSize        = width;
-  Pel* pDst          = rpDst;
+//NOTE: Bit-Limit - 25-bit source
+Void TComPrediction::xPredIntraAng(       Int bitDepth,
+                                    const Pel* pSrc,     Int srcStride,
+                                          Pel* pTrueDst, Int dstStrideTrue,
+                                          UInt uiWidth, UInt uiHeight, ChannelType channelType,
+                                          UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable
+                                  , const Bool bEnableEdgeFilters
+                                  )
+{
+  Int width=Int(uiWidth);
+  Int height=Int(uiHeight);
 
   // Map the mode index to main prediction direction and angle
-  assert( dirMode > 0 ); //no planar
-  Bool modeDC        = dirMode < 2;
-  Bool modeHor       = !modeDC && (dirMode < 18);
-  Bool modeVer       = !modeDC && !modeHor;
-  Int intraPredAngle = modeVer ? (Int)dirMode - VER_IDX : modeHor ? -((Int)dirMode - HOR_IDX) : 0;
-  Int absAng         = abs(intraPredAngle);
-  Int signAng        = intraPredAngle < 0 ? -1 : 1;
-
-  // Set bitshifts and scale the angle parameter to block size
-  Int angTable[9]    = {0,    2,    5,   9,  13,  17,  21,  26,  32};
-  Int invAngTable[9] = {0, 4096, 1638, 910, 630, 482, 390, 315, 256}; // (256 * 32) / Angle
-  Int invAngle       = invAngTable[absAng];
-  absAng             = angTable[absAng];
-  intraPredAngle     = signAng * absAng;
+  assert( dirMode != PLANAR_IDX ); //no planar
+  const Bool modeDC        = dirMode==DC_IDX;
 
   // Do the DC prediction
   if (modeDC)
   {
-    Pel dcval = predIntraGetPredValDC(pSrc, srcStride, width, height, blkAboveAvailable, blkLeftAvailable);
-
-    for (k=0;k<blkSize;k++)
-    {
-      for (l=0;l<blkSize;l++)
-      {
-        pDst[k*dstStride+l] = dcval;
-      }
-    }
-  }
-
-  // Do angular predictions
-  else
-  {
+    const Pel dcval = predIntraGetPredValDC(pSrc, srcStride, width, height, blkAboveAvailable, blkLeftAvailable);
+
+    for (Int y=height;y>0;y--, pTrueDst+=dstStrideTrue)
+    {
+      for (Int x=0; x<width;) // width is always a multiple of 4.
+      {
+        pTrueDst[x++] = dcval;
+      }
+    }
+  }
+  else // Do angular predictions
+  {
+    const Bool       bIsModeVer         = (dirMode >= 18);
+    const Int        intraPredAngleMode = (bIsModeVer) ? (Int)dirMode - VER_IDX :  -((Int)dirMode - HOR_IDX);
+    const Int        absAngMode         = abs(intraPredAngleMode);
+    const Int        signAng            = intraPredAngleMode < 0 ? -1 : 1;
+    const Bool       edgeFilter         = bEnableEdgeFilters && isLuma(channelType) && (width <= MAXIMUM_INTRA_FILTERED_WIDTH) && (height <= MAXIMUM_INTRA_FILTERED_HEIGHT);
+
+    // Set bitshifts and scale the angle parameter to block size
+    static const Int angTable[9]    = {0,    2,    5,   9,  13,  17,  21,  26,  32};
+    static const Int invAngTable[9] = {0, 4096, 1638, 910, 630, 482, 390, 315, 256}; // (256 * 32) / Angle
+    Int invAngle                    = invAngTable[absAngMode];
+    Int absAng                      = angTable[absAngMode];
+    Int intraPredAngle              = signAng * absAng;
+
     Pel* refMain;
     Pel* refSide;
+
     Pel  refAbove[2*MAX_CU_SIZE+1];
     Pel  refLeft[2*MAX_CU_SIZE+1];
@@ -261,18 +335,20 @@
     if (intraPredAngle < 0)
     {
-      for (k=0;k<blkSize+1;k++)
-      {
-        refAbove[k+blkSize-1] = pSrc[k-srcStride-1];
-      }
-      for (k=0;k<blkSize+1;k++)
-      {
-        refLeft[k+blkSize-1] = pSrc[(k-1)*srcStride-1];
-      }
-      refMain = (modeVer ? refAbove : refLeft) + (blkSize-1);
-      refSide = (modeVer ? refLeft : refAbove) + (blkSize-1);
+      const Int refMainOffsetPreScale = (bIsModeVer ? height : width ) - 1;
+      const Int refMainOffset         = height - 1;
+      for (Int x=0;x<width+1;x++)
+      {
+        refAbove[x+refMainOffset] = pSrc[x-srcStride-1];
+      }
+      for (Int y=0;y<height+1;y++)
+      {
+        refLeft[y+refMainOffset] = pSrc[(y-1)*srcStride-1];
+      }
+      refMain = (bIsModeVer ? refAbove : refLeft)  + refMainOffset;
+      refSide = (bIsModeVer ? refLeft  : refAbove) + refMainOffset;
 
       // Extend the Main reference to the left.
       Int invAngleSum    = 128;       // rounding for (shift by 8)
-      for (k=-1; k>blkSize*intraPredAngle>>5; k--)
+      for (Int k=-1; k>(refMainOffsetPreScale+1)*intraPredAngle>>5; k--)
       {
         invAngleSum += invAngle;
@@ -282,31 +358,40 @@
     else
     {
-      for (k=0;k<2*blkSize+1;k++)
-      {
-        refAbove[k] = pSrc[k-srcStride-1];
-      }
-      for (k=0;k<2*blkSize+1;k++)
-      {
-        refLeft[k] = pSrc[(k-1)*srcStride-1];
-      }
-      refMain = modeVer ? refAbove : refLeft;
-      refSide = modeVer ? refLeft  : refAbove;
-    }
-
-    if (intraPredAngle == 0)
-    {
-      for (k=0;k<blkSize;k++)
-      {
-        for (l=0;l<blkSize;l++)
+      for (Int x=0;x<2*width+1;x++)
+      {
+        refAbove[x] = pSrc[x-srcStride-1];
+      }
+      for (Int y=0;y<2*height+1;y++)
+      {
+        refLeft[y] = pSrc[(y-1)*srcStride-1];
+      }
+      refMain = bIsModeVer ? refAbove : refLeft ;
+      refSide = bIsModeVer ? refLeft  : refAbove;
+    }
+
+    // swap width/height if we are doing a horizontal mode:
+    Pel tempArray[MAX_CU_SIZE*MAX_CU_SIZE];
+    const Int dstStride = bIsModeVer ? dstStrideTrue : MAX_CU_SIZE;
+    Pel *pDst = bIsModeVer ? pTrueDst : tempArray;
+    if (!bIsModeVer)
+    {
+      std::swap(width, height);
+    }
+
+    if (intraPredAngle == 0)  // pure vertical or pure horizontal
+    {
+      for (Int y=0;y<height;y++)
+      {
+        for (Int x=0;x<width;x++)
         {
-          pDst[k*dstStride+l] = refMain[l+1];
+          pDst[y*dstStride+x] = refMain[x+1];
         }
       }
 
-      if ( bFilter )
-      {
-        for (k=0;k<blkSize;k++)
+      if (edgeFilter)
+      {
+        for (Int y=0;y<height;y++)
         {
-          pDst[k*dstStride] = Clip3(0, (1<<bitDepth)-1, pDst[k*dstStride] + (( refSide[k+1] - refSide[0] ) >> 1) );
+          pDst[y*dstStride] = Clip3 (0, ((1 << bitDepth) - 1), pDst[y*dstStride] + (( refSide[y+1] - refSide[0] ) >> 1) );
         }
       }
@@ -314,22 +399,21 @@
     else
     {
-      Int deltaPos=0;
-      Int deltaInt;
-      Int deltaFract;
-      Int refMainIndex;
-
-      for (k=0;k<blkSize;k++)
-      {
-        deltaPos += intraPredAngle;
-        deltaInt   = deltaPos >> 5;
-        deltaFract = deltaPos & (32 - 1);
+      Pel *pDsty=pDst;
+
+      for (Int y=0, deltaPos=intraPredAngle; y<height; y++, deltaPos+=intraPredAngle, pDsty+=dstStride)
+      {
+        const Int deltaInt   = deltaPos >> 5;
+        const Int deltaFract = deltaPos & (32 - 1);
 
         if (deltaFract)
         {
           // Do linear filtering
-          for (l=0;l<blkSize;l++)
+          const Pel *pRM=refMain+deltaInt+1;
+          Int lastRefMainPel=*pRM++;
+          for (Int x=0;x<width;pRM++,x++)
           {
-            refMainIndex        = l+deltaInt+1;
-            pDst[k*dstStride+l] = (Pel) ( ((32-deltaFract)*refMain[refMainIndex]+deltaFract*refMain[refMainIndex+1]+16) >> 5 );
+            Int thisRefMainPel=*pRM;
+            pDsty[x+0] = (Pel) ( ((32-deltaFract)*lastRefMainPel + deltaFract*thisRefMainPel +16) >> 5 );
+            lastRefMainPel=thisRefMainPel;
           }
         }
@@ -337,7 +421,7 @@
         {
           // Just copy the integer samples
-          for (l=0;l<blkSize;l++)
+          for (Int x=0;x<width; x++)
           {
-            pDst[k*dstStride+l] = refMain[l+deltaInt+1];
+            pDsty[x] = refMain[x+deltaInt+1];
           }
         }
@@ -346,75 +430,102 @@
 
     // Flip the block if this is the horizontal mode
-    if (modeHor)
-    {
-      Pel  tmp;
-      for (k=0;k<blkSize-1;k++)
-      {
-        for (l=k+1;l<blkSize;l++)
+    if (!bIsModeVer)
+    {
+      for (Int y=0; y<height; y++)
+      {
+        for (Int x=0; x<width; x++)
         {
-          tmp                 = pDst[k*dstStride+l];
-          pDst[k*dstStride+l] = pDst[l*dstStride+k];
-          pDst[l*dstStride+k] = tmp;
+          pTrueDst[x*dstStrideTrue] = pDst[x];
         }
-      }
-    }
-  }
-}
-
-Void TComPrediction::predIntraLumaAng(TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft )
-{
-  Pel *pDst = piPred;
-  Int *ptrSrc;
+        pTrueDst++;
+        pDst+=dstStride;
+      }
+    }
+  }
+}
+
+Void TComPrediction::predIntraAng( const ComponentID compID, UInt uiDirMode, Pel* piOrg /* Will be null for decoding */, UInt uiOrgStride, Pel* piPred, UInt uiStride, TComTU &rTu, Bool bAbove, Bool bLeft, const Bool bUseFilteredPredSamples, const Bool bUseLosslessDPCM )
+{
+  const ChannelType    channelType = toChannelType(compID);
+  const TComRectangle &rect        = rTu.getRect(isLuma(compID) ? COMPONENT_Y : COMPONENT_Cb);
+  const Int            iWidth      = rect.width;
+  const Int            iHeight     = rect.height;
 
   assert( g_aucConvertToBit[ iWidth ] >= 0 ); //   4x  4
   assert( g_aucConvertToBit[ iWidth ] <= 5 ); // 128x128
-  assert( iWidth == iHeight  );
-
-  ptrSrc = pcTComPattern->getPredictorPtr( uiDirMode, g_aucConvertToBit[ iWidth ] + 2, m_piYuvExt );
+  //assert( iWidth == iHeight  );
+
+        Pel *pDst = piPred;
 
   // get starting pixel in block
-  Int sw = 2 * iWidth + 1;
-
-  // Create the prediction
-  if ( uiDirMode == PLANAR_IDX )
-  {
-    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
+  const Int sw = (2 * iWidth + 1);
+
+  if ( bUseLosslessDPCM )
+  {
+    const Pel *ptrSrc = getPredictorPtr( compID, false );
+    // Sample Adaptive intra-Prediction (SAP)
+    if (uiDirMode==HOR_IDX)
+    {
+      // left column filled with reference samples
+      // remaining columns filled with piOrg data (if available).
+      for(Int y=0; y<iHeight; y++)
+      {
+        piPred[y*uiStride+0] = ptrSrc[(y+1)*sw];
+      }
+      if (piOrg!=0)
+      {
+        piPred+=1; // miss off first column
+        for(Int y=0; y<iHeight; y++, piPred+=uiStride, piOrg+=uiOrgStride)
+        {
+          memcpy(piPred, piOrg, (iWidth-1)*sizeof(Pel));
+        }
+      }
+    }
+    else // VER_IDX
+    {
+      // top row filled with reference samples
+      // remaining rows filled with piOrd data (if available)
+      for(Int x=0; x<iWidth; x++)
+      {
+        piPred[x] = ptrSrc[x+1];
+      }
+      if (piOrg!=0)
+      {
+        piPred+=uiStride; // miss off the first row
+        for(Int y=1; y<iHeight; y++, piPred+=uiStride, piOrg+=uiOrgStride)
+        {
+          memcpy(piPred, piOrg, iWidth*sizeof(Pel));
+        }
+      }
+    }
   }
   else
   {
-    if ( (iWidth > 16) || (iHeight > 16) )
-    {
-      xPredIntraAng(g_bitDepthY, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, false );
+    const Pel *ptrSrc = getPredictorPtr( compID, bUseFilteredPredSamples );
+
+    if ( uiDirMode == PLANAR_IDX )
+    {
+      xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
     }
     else
     {
-      xPredIntraAng(g_bitDepthY, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, true );
-
-      if( (uiDirMode == DC_IDX ) && bAbove && bLeft )
-      {
-        xDCPredFiltering( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight);
-      }
-    }
-  }
-}
-
-// Angular chroma
-Void TComPrediction::predIntraChromaAng( Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft )
-{
-  Pel *pDst = piPred;
-  Int *ptrSrc = piSrc;
-
-  // get starting pixel in block
-  Int sw = 2 * iWidth + 1;
-
-  if ( uiDirMode == PLANAR_IDX )
-  {
-    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
-  }
-  else
-  {
-    // Create the prediction
-    xPredIntraAng(g_bitDepthC, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, false );
-  }
+      // Create the prediction
+            TComDataCU *const pcCU              = rTu.getCU();
+      const UInt              uiAbsPartIdx      = rTu.GetAbsPartIdxTU();
+      const Bool              enableEdgeFilters = !(pcCU->isRDPCMEnabled(uiAbsPartIdx) && pcCU->getCUTransquantBypass(uiAbsPartIdx));
+#if O0043_BEST_EFFORT_DECODING
+      const Int channelsBitDepthForPrediction = rTu.getCU()->getSlice()->getSPS()->getStreamBitDepth(channelType);
+#else
+      const Int channelsBitDepthForPrediction = rTu.getCU()->getSlice()->getSPS()->getBitDepth(channelType);
+#endif
+      xPredIntraAng( channelsBitDepthForPrediction, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, channelType, uiDirMode, bAbove, bLeft, enableEdgeFilters );
+
+      if(( uiDirMode == DC_IDX ) && bAbove && bLeft )
+      {
+        xDCPredFiltering( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, channelType );
+      }
+    }
+  }
+
 }
 
@@ -526,7 +637,6 @@
 #endif
 
-/** Function for checking identical motion.
- * \param TComDataCU* pcCU
- * \param UInt PartAddr
+/** Check for identical motion in both motion vector direction of a bi-directional predicted CU
+  * \returns true, if motion vectors and reference pictures match
  */
 Bool TComPrediction::xCheckIdenticalMotion ( TComDataCU* pcCU, UInt PartAddr )
@@ -1099,21 +1209,21 @@
     {
 #endif
-      if ( eRefPicList != REF_PIC_LIST_X )
-      {
-        if( pcCU->getSlice()->getPPS()->getUseWP())
-        {
-          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
-        }
-        else
-        {
-          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
-        }
-        if ( pcCU->getSlice()->getPPS()->getUseWP() )
-        {
-          xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
-        }
+    if ( eRefPicList != REF_PIC_LIST_X )
+    {
+      if( pcCU->getSlice()->getPPS()->getUseWP())
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
       }
       else
       {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+      }
+      if ( pcCU->getSlice()->getPPS()->getUseWP() )
+      {
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+      }
+    }
+    else
+    {
 #if H_3D_SPIVMP
         if ( pcCU->getSPIVMPFlag(uiPartAddr)!=0)  
@@ -1148,16 +1258,16 @@
         {
 #endif
-          if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
-          {
-            xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
-          }
-          else
-          {
-            xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
-          }
+      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+      }
+      else
+      {
+        xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
+      }
 #if H_3D_SPIVMP
         }
 #endif
-      }
+    }
 #if H_3D_VSP
     }
@@ -1185,21 +1295,21 @@
     {
 #endif
-      if ( eRefPicList != REF_PIC_LIST_X )
-      {
-        if( pcCU->getSlice()->getPPS()->getUseWP())
-        {
-          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
-        }
-        else
-        {
-          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
-        }
-        if ( pcCU->getSlice()->getPPS()->getUseWP() )
-        {
-          xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
-        }
+    if ( eRefPicList != REF_PIC_LIST_X )
+    {
+      if( pcCU->getSlice()->getPPS()->getUseWP())
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
       }
       else
       {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+      }
+      if ( pcCU->getSlice()->getPPS()->getUseWP() )
+      {
+        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+      }
+    }
+    else
+    {
 #if H_3D_SPIVMP
        if (pcCU->getSPIVMPFlag(uiPartAddr)!=0)  
@@ -1233,16 +1343,16 @@
       {
 #endif
-        if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
-        {
-          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
-        }
-        else
-        {
-          xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
-        }
+      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+      {
+        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+      }
+      else
+      {
+        xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
+      }
 #if H_3D_SPIVMP
        }
 #endif
-      }
+    }
 #if H_3D_VSP
     }
@@ -1263,10 +1373,10 @@
 }
 
-Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi )
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv* pcYuvPred, Bool bi )
 {
   Int         iRefIdx     = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           assert (iRefIdx >= 0);
   TComMv      cMv         = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
   pcCU->clipMv(cMv);
-#if H_MV
+#if NH_MV
   pcCU->checkMvVertRest(cMv, eRefPicList, iRefIdx );
 #endif
@@ -1302,6 +1412,10 @@
         , bICFlag );
 #else
-      xPredInterLumaBlk  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
-      xPredInterChromaBlk( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
+
+  for (UInt comp=COMPONENT_Y; comp<pcYuvPred->getNumberValidComponents(); comp++)
+  {
+    const ComponentID compID=ComponentID(comp);
+    xPredInterBlk  (compID,  pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, pcYuvPred, bi, pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID)) );
+  }
 #endif
 #if H_3D_ARP
@@ -1690,22 +1804,22 @@
 #endif
 
-Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvPred )
+Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv* pcYuvPred )
 {
   TComYuv* pcMbYuv;
-  Int      iRefIdx[2] = {-1, -1};
-
-  for ( Int iRefList = 0; iRefList < 2; iRefList++ )
-  {
-    RefPicList eRefPicList = (iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
-    iRefIdx[iRefList] = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
-
-    if ( iRefIdx[iRefList] < 0 )
+  Int      iRefIdx[NUM_REF_PIC_LIST_01] = {-1, -1};
+
+  for ( UInt refList = 0; refList < NUM_REF_PIC_LIST_01; refList++ )
+  {
+    RefPicList eRefPicList = (refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
+    iRefIdx[refList] = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+
+    if ( iRefIdx[refList] < 0 )
     {
       continue;
     }
 
-    assert( iRefIdx[iRefList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );
-
-    pcMbYuv = &m_acYuvPred[iRefList];
+    assert( iRefIdx[refList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );
+
+    pcMbYuv = &m_acYuvPred[refList];
     if( pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiPartAddr ) >= 0 && pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiPartAddr ) >= 0 )
     {
@@ -1714,6 +1828,6 @@
     else
     {
-      if ( ( pcCU->getSlice()->getPPS()->getUseWP()       && pcCU->getSlice()->getSliceType() == P_SLICE ) || 
-           ( pcCU->getSlice()->getPPS()->getWPBiPred() && pcCU->getSlice()->getSliceType() == B_SLICE ) )
+      if ( ( pcCU->getSlice()->getPPS()->getUseWP()       && pcCU->getSlice()->getSliceType() == P_SLICE ) ||
+           ( pcCU->getSlice()->getPPS()->getWPBiPred()    && pcCU->getSlice()->getSliceType() == B_SLICE ) )
       {
         xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, true );
@@ -1726,15 +1840,15 @@
   }
 
-  if ( pcCU->getSlice()->getPPS()->getWPBiPred() && pcCU->getSlice()->getSliceType() == B_SLICE  )
-  {
-    xWeightedPredictionBi( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
-  }  
+  if ( pcCU->getSlice()->getPPS()->getWPBiPred()    && pcCU->getSlice()->getSliceType() == B_SLICE  )
+  {
+    xWeightedPredictionBi( pcCU, &m_acYuvPred[REF_PIC_LIST_0], &m_acYuvPred[REF_PIC_LIST_1], iRefIdx[REF_PIC_LIST_0], iRefIdx[REF_PIC_LIST_1], uiPartAddr, iWidth, iHeight, pcYuvPred );
+  }
   else if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType() == P_SLICE )
   {
-    xWeightedPredictionUni( pcCU, &m_acYuvPred[0], uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, rpcYuvPred ); 
+    xWeightedPredictionUni( pcCU, &m_acYuvPred[REF_PIC_LIST_0], uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
   }
   else
   {
-    xWeightedAverage( &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+    xWeightedAverage( &m_acYuvPred[REF_PIC_LIST_0], &m_acYuvPred[REF_PIC_LIST_1], iRefIdx[REF_PIC_LIST_0], iRefIdx[REF_PIC_LIST_1], uiPartAddr, iWidth, iHeight, pcYuvPred, pcCU->getSlice()->getSPS()->getBitDepths() );
   }
 }
@@ -1769,16 +1883,20 @@
 
 /**
- * \brief Generate motion-compensated luma block
+ * \brief Generate motion-compensated block
  *
- * \param cu       Pointer to current CU
- * \param refPic   Pointer to reference picture
- * \param partAddr Address of block within CU
- * \param mv       Motion vector
- * \param width    Width of block
- * \param height   Height of block
- * \param dstPic   Pointer to destination picture
- * \param bi       Flag indicating whether bipred is used
+ * \param compID     Colour component ID
+ * \param cu         Pointer to current CU
+ * \param refPic     Pointer to reference picture
+ * \param partAddr   Address of block within CU
+ * \param mv         Motion vector
+ * \param width      Width of block
+ * \param height     Height of block
+ * \param dstPic     Pointer to destination picture
+ * \param bi         Flag indicating whether bipred is used
+ * \param  bitDepth  Bit depth
  */
-Void TComPrediction::xPredInterLumaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi 
+
+
+Void TComPrediction::xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth 
 #if H_3D_ARP
     , Bool filterType
@@ -1787,15 +1905,19 @@
     , Bool bICFlag
 #endif
-  )
-{
-  Int refStride = refPic->getStride();  
-  Int refOffset = ( mv->getHor() >> 2 ) + ( mv->getVer() >> 2 ) * refStride;
-  Pel *ref      = refPic->getLumaAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
-  
-  Int dstStride = dstPic->getStride();
-  Pel *dst      = dstPic->getLumaAddr( partAddr );
-  
-  Int xFrac = mv->getHor() & 0x3;
-  Int yFrac = mv->getVer() & 0x3;
+)
+{
+  Int     refStride  = refPic->getStride(compID);
+  Int     dstStride  = dstPic->getStride(compID);
+  Int shiftHor=(2+refPic->getComponentScaleX(compID));
+  Int shiftVer=(2+refPic->getComponentScaleY(compID));
+
+  Int     refOffset  = (mv->getHor() >> shiftHor) + (mv->getVer() >> shiftVer) * refStride;
+
+  Pel*    ref     = refPic->getAddr(compID, cu->getCtuRsAddr(), cu->getZorderIdxInCtu() + partAddr ) + refOffset;
+
+  Pel*    dst = dstPic->getAddr( compID, partAddr );
+
+  Int     xFrac  = mv->getHor() & ((1<<shiftHor)-1);
+  Int     yFrac  = mv->getVer() & ((1<<shiftVer)-1);
 
 #if H_3D_IC
@@ -1808,4 +1930,10 @@
   }
 #endif
+
+  UInt    cxWidth  = width  >> refPic->getComponentScaleX(compID);
+  UInt    cxHeight = height >> refPic->getComponentScaleY(compID);
+
+  const ChromaFormat chFmt = cu->getPic()->getChromaFormat();
+
   if ( yFrac == 0 )
   {
@@ -1813,10 +1941,10 @@
     m_if.filterHorLuma( ref, refStride, dst, dstStride, width, height, xFrac,       !bi || bICFlag
 #else
-    m_if.filterHorLuma( ref, refStride, dst, dstStride, width, height, xFrac,       !bi 
-#endif
-#if H_3D_ARP
+    m_if.filterHor(compID, ref, refStride, dst,  dstStride, cxWidth, cxHeight, xFrac, !bi, chFmt, bitDepth
+#endif
+#if H_3D_ARP 
     , filterType
-#endif
-      );
+#endif 
+);
   }
   else if ( xFrac == 0 )
@@ -1825,33 +1953,32 @@
     m_if.filterVerLuma( ref, refStride, dst, dstStride, width, height, yFrac, true, !bi || bICFlag
 #else
-    m_if.filterVerLuma( ref, refStride, dst, dstStride, width, height, yFrac, true, !bi 
+    m_if.filterVer(compID, ref, refStride, dst, dstStride, cxWidth, cxHeight, yFrac, true, !bi, chFmt, bitDepth
 #endif
 #if H_3D_ARP
     , filterType
 #endif
-      );
+);
   }
   else
   {
-    Int tmpStride = m_filteredBlockTmp[0].getStride();
-    Short *tmp    = m_filteredBlockTmp[0].getLumaAddr();
-
-    Int filterSize = NTAPS_LUMA;
-    Int halfFilterSize = ( filterSize >> 1 );
-
-    m_if.filterHorLuma(ref - (halfFilterSize-1)*refStride, refStride, tmp, tmpStride, width, height+filterSize-1, xFrac, false     
+    Int   tmpStride = m_filteredBlockTmp[0].getStride(compID);
+    Pel*  tmp       = m_filteredBlockTmp[0].getAddr(compID);
+
+    const Int vFilterSize = isLuma(compID) ? NTAPS_LUMA : NTAPS_CHROMA;
+
+    m_if.filterHor(compID, ref - ((vFilterSize>>1) -1)*refStride, refStride, tmp, tmpStride, cxWidth, cxHeight+vFilterSize-1, xFrac, false,      chFmt, bitDepth
 #if H_3D_ARP 
     , filterType
 #endif 
-      );
+);
 #if H_3D_IC
     m_if.filterVerLuma(tmp + (halfFilterSize-1)*tmpStride, tmpStride, dst, dstStride, width, height,              yFrac, false, !bi || bICFlag
 #else
-    m_if.filterVerLuma(tmp + (halfFilterSize-1)*tmpStride, tmpStride, dst, dstStride, width, height,              yFrac, false, !bi
+    m_if.filterVer(compID, tmp + ((vFilterSize>>1) -1)*tmpStride, tmpStride, dst, dstStride, cxWidth, cxHeight,               yFrac, false, !bi, chFmt, bitDepth
 #endif
 #if H_3D_ARP
     , filterType
 #endif 
-      );    
+);
   }
 
@@ -1890,19 +2017,8 @@
   }
 #endif
-}
-
-/**
- * \brief Generate motion-compensated chroma block
- *
- * \param cu       Pointer to current CU
- * \param refPic   Pointer to reference picture
- * \param partAddr Address of block within CU
- * \param mv       Motion vector
- * \param width    Width of block
- * \param height   Height of block
- * \param dstPic   Pointer to destination picture
- * \param bi       Flag indicating whether bipred is used
- */
-Void TComPrediction::xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi 
+
+}
+
+
 #if H_3D_ARP
     , Bool filterType
@@ -1911,104 +2027,52 @@
     , Bool bICFlag
 #endif
-  )
-{
-  Int     refStride  = refPic->getCStride();
-  Int     dstStride  = dstPic->getCStride();
-  
-  Int     refOffset  = (mv->getHor() >> 3) + (mv->getVer() >> 3) * refStride;
-  
-  Pel*    refCb     = refPic->getCbAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
-  Pel*    refCr     = refPic->getCrAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
-  
-  Pel* dstCb = dstPic->getCbAddr( partAddr );
-  Pel* dstCr = dstPic->getCrAddr( partAddr );
-  
-  Int     xFrac  = mv->getHor() & 0x7;
-  Int     yFrac  = mv->getVer() & 0x7;
-  UInt    cxWidth  = width  >> 1;
-  UInt    cxHeight = height >> 1;
-  
-  Int     extStride = m_filteredBlockTmp[0].getStride();
-  Short*  extY      = m_filteredBlockTmp[0].getLumaAddr();
-  
-  Int filterSize = NTAPS_CHROMA;
-  
-  Int halfFilterSize = (filterSize>>1);
-  
-  if ( yFrac == 0 )
-  {
 #if H_3D_IC
     m_if.filterHorChroma(refCb, refStride, dstCb,  dstStride, cxWidth, cxHeight, xFrac, !bi || bICFlag
 #else
-    m_if.filterHorChroma(refCb, refStride, dstCb,  dstStride, cxWidth, cxHeight, xFrac, !bi
 #endif
 #if H_3D_ARP
     , filterType
 #endif
-    );    
 #if H_3D_IC
     m_if.filterHorChroma(refCr, refStride, dstCr,  dstStride, cxWidth, cxHeight, xFrac, !bi || bICFlag
 #else
-    m_if.filterHorChroma(refCr, refStride, dstCr,  dstStride, cxWidth, cxHeight, xFrac, !bi
 #endif
 #if H_3D_ARP
     , filterType
 #endif
-    );
-  }
-  else if ( xFrac == 0 )
-  {
 #if H_3D_IC
     m_if.filterVerChroma(refCb, refStride, dstCb, dstStride, cxWidth, cxHeight, yFrac, true, !bi || bICFlag
 #else
-    m_if.filterVerChroma(refCb, refStride, dstCb, dstStride, cxWidth, cxHeight, yFrac, true, !bi
 #endif
 #if H_3D_ARP
     , filterType
 #endif
-    );
 #if H_3D_IC
     m_if.filterVerChroma(refCr, refStride, dstCr, dstStride, cxWidth, cxHeight, yFrac, true, !bi || bICFlag
 #else
-    m_if.filterVerChroma(refCr, refStride, dstCr, dstStride, cxWidth, cxHeight, yFrac, true, !bi
 #endif
 #if H_3D_ARP
     , filterType
 #endif
-    );
-  }
-  else
-  {
-    m_if.filterHorChroma(refCb - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false
 #if H_3D_ARP
     , filterType
 #endif  
-      );
 #if H_3D_IC
     m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCb, dstStride, cxWidth, cxHeight  , yFrac, false, !bi || bICFlag
 #else
-    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCb, dstStride, cxWidth, cxHeight  , yFrac, false, !bi
 #endif
 #if H_3D_ARP
     , filterType
 #endif 
-      );
-    
-    m_if.filterHorChroma(refCr - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false
 #if H_3D_ARP
     , filterType
 #endif 
-      );
 #if H_3D_IC
     m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCr, dstStride, cxWidth, cxHeight  , yFrac, false, !bi || bICFlag
 #else
-    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCr, dstStride, cxWidth, cxHeight  , yFrac, false, !bi
 #endif
 #if H_3D_ARP
     , filterType
 #endif 
-      );    
-  }
-
 #if H_3D_IC
   if( bICFlag )
@@ -2057,19 +2121,18 @@
   }
 #endif
-}
-
-Void TComPrediction::xWeightedAverage( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst )
+Void TComPrediction::xWeightedAverage( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* pcYuvDst, const BitDepths &clipBitDepths
+ )
 {
   if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
   {
-    rpcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight );
+    pcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight, clipBitDepths );
   }
   else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
   {
-    pcYuvSrc0->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+    pcYuvSrc0->copyPartToPartYuv( pcYuvDst, uiPartIdx, iWidth, iHeight );
   }
   else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
   {
-    pcYuvSrc1->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+    pcYuvSrc1->copyPartToPartYuv( pcYuvDst, uiPartIdx, iWidth, iHeight );
   }
 }
@@ -2079,4 +2142,5 @@
 {
   AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+
   if( pcAMVPInfo->iN <= 1 )
   {
@@ -2094,52 +2158,64 @@
 
 /** Function for deriving planar intra prediction.
- * \param pSrc pointer to reconstructed sample array
- * \param srcStride the stride of the reconstructed sample array
- * \param rpDst reference to pointer for the prediction sample array
- * \param dstStride the stride of the prediction sample array
- * \param width the width of the block
- * \param height the height of the block
+ * \param pSrc        pointer to reconstructed sample array
+ * \param srcStride   the stride of the reconstructed sample array
+ * \param rpDst       reference to pointer for the prediction sample array
+ * \param dstStride   the stride of the prediction sample array
+ * \param width       the width of the block
+ * \param height      the height of the block
+ * \param channelType type of pel array (luma, chroma)
+ * \param format      chroma format
  *
  * This function derives the prediction samples for planar mode (intra coding).
  */
-Void TComPrediction::xPredIntraPlanar( Int* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height )
-{
-  assert(width == height);
-
-  Int k, l, bottomLeft, topRight;
-  Int horPred;
+//NOTE: Bit-Limit - 24-bit source
+Void TComPrediction::xPredIntraPlanar( const Pel* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height )
+{
+  assert(width <= height);
+
   Int leftColumn[MAX_CU_SIZE+1], topRow[MAX_CU_SIZE+1], bottomRow[MAX_CU_SIZE], rightColumn[MAX_CU_SIZE];
-  UInt blkSize = width;
-  UInt offset2D = width;
-  UInt shift1D = g_aucConvertToBit[ width ] + 2;
-  UInt shift2D = shift1D + 1;
+  UInt shift1Dhor = g_aucConvertToBit[ width ] + 2;
+  UInt shift1Dver = g_aucConvertToBit[ height ] + 2;
 
   // Get left and above reference column and row
-  for(k=0;k<blkSize+1;k++)
+  for(Int k=0;k<width+1;k++)
   {
     topRow[k] = pSrc[k-srcStride];
+  }
+
+  for (Int k=0; k < height+1; k++)
+  {
     leftColumn[k] = pSrc[k*srcStride-1];
   }
 
   // Prepare intermediate variables used in interpolation
-  bottomLeft = leftColumn[blkSize];
-  topRight   = topRow[blkSize];
-  for (k=0;k<blkSize;k++)
-  {
-    bottomRow[k]   = bottomLeft - topRow[k];
-    rightColumn[k] = topRight   - leftColumn[k];
-    topRow[k]      <<= shift1D;
-    leftColumn[k]  <<= shift1D;
-  }
+  Int bottomLeft = leftColumn[height];
+  Int topRight   = topRow[width];
+
+  for(Int k=0;k<width;k++)
+  {
+    bottomRow[k]  = bottomLeft - topRow[k];
+    topRow[k]     <<= shift1Dver;
+  }
+
+  for(Int k=0;k<height;k++)
+  {
+    rightColumn[k]  = topRight - leftColumn[k];
+    leftColumn[k]   <<= shift1Dhor;
+  }
+
+  const UInt topRowShift = 0;
 
   // Generate prediction signal
-  for (k=0;k<blkSize;k++)
-  {
-    horPred = leftColumn[k] + offset2D;
-    for (l=0;l<blkSize;l++)
-    {
-      horPred += rightColumn[k];
-      topRow[l] += bottomRow[l];
-      rpDst[k*dstStride+l] = ( (horPred + topRow[l]) >> shift2D );
+  for (Int y=0;y<height;y++)
+  {
+    Int horPred = leftColumn[y] + width;
+    for (Int x=0;x<width;x++)
+    {
+      horPred += rightColumn[y];
+      topRow[x] += bottomRow[x];
+
+      Int vertPred = ((topRow[x] + topRowShift)>>topRowShift);
+      rpDst[y*dstStride+x] = ( horPred + vertPred ) >> (shift1Dhor+1);
     }
   }
@@ -2149,30 +2225,43 @@
  * \param pSrc pointer to reconstructed sample array
  * \param iSrcStride the stride of the reconstructed sample array
- * \param rpDst reference to pointer for the prediction sample array
+ * \param pDst reference to pointer for the prediction sample array
  * \param iDstStride the stride of the prediction sample array
  * \param iWidth the width of the block
  * \param iHeight the height of the block
+ * \param channelType type of pel array (luma, chroma)
  *
  * This function performs filtering left and top edges of the prediction samples for DC mode (intra coding).
  */
-Void TComPrediction::xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight )
-{
-  Pel* pDst = rpDst;
+Void TComPrediction::xDCPredFiltering( const Pel* pSrc, Int iSrcStride, Pel* pDst, Int iDstStride, Int iWidth, Int iHeight, ChannelType channelType )
+{
   Int x, y, iDstStride2, iSrcStride2;
 
-  // boundary pixels processing
-  pDst[0] = (Pel)((pSrc[-iSrcStride] + pSrc[-1] + 2 * pDst[0] + 2) >> 2);
-
-  for ( x = 1; x < iWidth; x++ )
-  {
-    pDst[x] = (Pel)((pSrc[x - iSrcStride] +  3 * pDst[x] + 2) >> 2);
-  }
-
-  for ( y = 1, iDstStride2 = iDstStride, iSrcStride2 = iSrcStride-1; y < iHeight; y++, iDstStride2+=iDstStride, iSrcStride2+=iSrcStride )
-  {
-    pDst[iDstStride2] = (Pel)((pSrc[iSrcStride2] + 3 * pDst[iDstStride2] + 2) >> 2);
+  if (isLuma(channelType) && (iWidth <= MAXIMUM_INTRA_FILTERED_WIDTH) && (iHeight <= MAXIMUM_INTRA_FILTERED_HEIGHT))
+  {
+    //top-left
+    pDst[0] = (Pel)((pSrc[-iSrcStride] + pSrc[-1] + 2 * pDst[0] + 2) >> 2);
+
+    //top row (vertical filter)
+    for ( x = 1; x < iWidth; x++ )
+    {
+      pDst[x] = (Pel)((pSrc[x - iSrcStride] +  3 * pDst[x] + 2) >> 2);
+    }
+
+    //left column (horizontal filter)
+    for ( y = 1, iDstStride2 = iDstStride, iSrcStride2 = iSrcStride-1; y < iHeight; y++, iDstStride2+=iDstStride, iSrcStride2+=iSrcStride )
+    {
+      pDst[iDstStride2] = (Pel)((pSrc[iSrcStride2] + 3 * pDst[iDstStride2] + 2) >> 2);
+    }
   }
 
   return;
+}
+
+/* Static member function */
+Bool TComPrediction::UseDPCMForFirstPassIntraEstimation(TComTU &rTu, const UInt uiDirMode)
+{
+  return (rTu.getCU()->isRDPCMEnabled(rTu.GetAbsPartIdxTU()) ) &&
+          rTu.getCU()->getCUTransquantBypass(rTu.GetAbsPartIdxTU()) &&
+          (uiDirMode==HOR_IDX || uiDirMode==VER_IDX);
 }
 #if H_3D_IC
@@ -2544,3 +2633,4 @@
 #endif // H_3D_DIM_SDC
 #endif
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPrediction.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComPrediction.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -41,10 +41,11 @@
 
 // Include files
-#include "TComPic.h"
-#include "TComMotionInfo.h"
-#include "TComPattern.h"
-#include "TComTrQuant.h"
+#include "TComYuv.h"
 #include "TComInterpolationFilter.h"
 #include "TComWeightPrediction.h"
+
+// forward declaration
+class TComMv;
+class TComTU; 
 
 //! \ingroup TLibCommon
@@ -56,22 +57,33 @@
 
 /// prediction class
+typedef enum PRED_BUF_E
+{
+  PRED_BUF_UNFILTERED=0,
+  PRED_BUF_FILTERED=1,
+  NUM_PRED_BUF=2
+} PRED_BUF;
+
+static const UInt MAX_INTRA_FILTER_DEPTHS=5;
+
 class TComPrediction : public TComWeightPrediction
 {
+private:
+  static const UChar m_aucIntraFilter[MAX_NUM_CHANNEL_TYPE][MAX_INTRA_FILTER_DEPTHS];
+
 protected:
-  Int*      m_piYuvExt;
-  Int       m_iYuvExtStride;
-  Int       m_iYuvExtHeight;
-  
-  TComYuv   m_acYuvPred[2];
+  Pel*      m_piYuvExt[MAX_NUM_COMPONENT][NUM_PRED_BUF];
+  Int       m_iYuvExtSize;
+
+  TComYuv   m_acYuvPred[NUM_REF_PIC_LIST_01];
   TComYuv   m_cYuvPredTemp;
 #if H_3D_ARP
   TComYuv   m_acYuvPredBase[2];
 #endif
-  TComYuv m_filteredBlock[4][4];
-  TComYuv m_filteredBlockTmp[4];
-  
+  TComYuv m_filteredBlock[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS];
+  TComYuv m_filteredBlockTmp[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS];
+
   TComInterpolationFilter m_if;
-  
-  Pel*   m_pLumaRecBuffer;       ///< array for downsampled reconstructed luma sample 
+
+  Pel*   m_pLumaRecBuffer;       ///< array for downsampled reconstructed luma sample
   Int    m_iLumaRecStride;       ///< stride of #m_pLumaRecBuffer array
 #if H_3D_IC
@@ -84,7 +96,7 @@
 #endif
 
-  Void xPredIntraAng            (Int bitDepth, Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, Bool bFilter );
-  Void xPredIntraPlanar         ( Int* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height );
-  
+  Void xPredIntraAng            ( Int bitDepth, const Pel* pSrc, Int srcStride, Pel* pDst, Int dstStride, UInt width, UInt height, ChannelType channelType, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, const Bool bEnableEdgeFilters );
+  Void xPredIntraPlanar         ( const Pel* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height );
+
   // motion compensation functions
 #if H_3D_ARP
@@ -93,6 +105,7 @@
   Void xPredInterUniARPviewRef( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi, TComMvField * pNewMvFiled = NULL );
 #endif
-  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi=false          );
-  Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight,                         TComYuv*& rpcYuvPred );
+
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv* pcYuvPred, Bool bi=false          );
+  Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight,                         TComYuv* pcYuvPred          );
 #if H_3D_VSP
   Void xPredInterUniVSP         ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi=false          );
@@ -100,5 +113,5 @@
 #endif
 
-  Void xPredInterLumaBlk  ( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi
+  Void xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth
 #if H_3D_ARP
     , Bool filterType = false
@@ -107,6 +120,5 @@
     , Bool bICFlag    = false
 #endif
-    );
-  Void xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi
+ );
 
 #if H_3D_ARP
@@ -116,15 +128,15 @@
     , Bool bICFlag    = false
 #endif
-    );
-
 #if H_3D_VSP
   Void xPredInterUniSubPU        ( TComDataCU *cu, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi, Int widthSubPU=4, Int heightSubPU=4 );
 #endif
-  Void xWeightedAverage         ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst );  
-  Void xGetLLSPrediction ( TComPattern* pcPattern, Int* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0 );
+
+  Void xWeightedAverage         ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv* pcYuvDst, const BitDepths &clipBitDepths  );
+
+  Void xGetLLSPrediction ( const Pel* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0, const ChromaFormat chFmt  DEBUG_STRING_FN_DECLARE(sDebug) );
 #if H_3D_IC
   Void xGetLLSICPrediction( TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, TextType eType );
 #endif
-  Void xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight );
+  Void xDCPredFiltering( const Pel* pSrc, Int iSrcStride, Pel* pDst, Int iDstStride, Int iWidth, Int iHeight, ChannelType channelType );
   Bool xCheckIdenticalMotion    ( TComDataCU* pcCU, UInt PartAddr);
 #if H_3D_SPIVMP
@@ -143,20 +155,23 @@
 #endif
 
+  Void destroy();
+
 public:
   TComPrediction();
   virtual ~TComPrediction();
-  
-  Void    initTempBuff();
-  
+
+  Void    initTempBuff(ChromaFormat chromaFormatIDC);
+
+  ChromaFormat getChromaFormat() const { return m_cYuvPredTemp.getChromaFormat(); }
+
   // inter
   Void motionCompensation         ( TComDataCU*  pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList = REF_PIC_LIST_X, Int iPartIdx = -1 );
-  
+
   // motion vector prediction
   Void getMvPredAMVP              ( TComDataCU* pcCU, UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, TComMv& rcMvPred );
-  
+
   // Angular Intra
-  Void predIntraLumaAng           ( TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft );
-  Void predIntraChromaAng         ( Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft );
-  
+  Void predIntraAng               ( const ComponentID compID, UInt uiDirMode, Pel *piOrg /* Will be null for decoding */, UInt uiOrgStride, Pel* piPred, UInt uiStride, TComTU &rTu, Bool bAbove, Bool bLeft, const Bool bUseFilteredPredSamples, const Bool bUseLosslessDPCM = false );
+
 #if H_3D_DIM
   // Depth intra
@@ -178,10 +193,23 @@
 #endif
 
-  Pel  predIntraGetPredValDC      ( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft );
-  
-  Int* getPredicBuf()             { return m_piYuvExt;      }
-  Int  getPredicBufWidth()        { return m_iYuvExtStride; }
-  Int  getPredicBufHeight()       { return m_iYuvExtHeight; }
-
+  Pel  predIntraGetPredValDC      ( const Pel* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft );
+
+  Pel*  getPredictorPtr           ( const ComponentID compID, const Bool bUseFilteredPredictions )
+  {
+    return m_piYuvExt[compID][bUseFilteredPredictions?PRED_BUF_FILTERED:PRED_BUF_UNFILTERED];
+  }
+
+  // This function is actually still in TComPattern.cpp
+  /// set parameters from CU data for accessing intra data
+  Void initIntraPatternChType ( TComTU &rTu,
+                              Bool&       bAbove,
+                              Bool&       bLeft,
+                              const ComponentID compID, const Bool bFilterRefSamples
+                              DEBUG_STRING_FN_DECLARE(sDebug)
+                              );
+
+  static Bool filteringIntraReferenceSamples(const ComponentID compID, UInt uiDirMode, UInt uiTuChWidth, UInt uiTuChHeight, const ChromaFormat chFmt, const Bool intraReferenceSmoothingDisabled);
+
+  static Bool UseDPCMForFirstPassIntraEstimation(TComTU &rTu, const UInt uiDirMode);
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,8 +38,10 @@
 #include <math.h>
 #include <assert.h>
+#include <limits>
 #include "TComRom.h"
 #include "TComRdCost.h"
-#if H_3D
+#if NH_3D
 #include "TComDataCU.h"
+#include "TComRectangle.h"
 #endif
 
@@ -47,5 +49,5 @@
 //! \{
 
-#if H_3D_VSO
+#if NH_3D_VSO
 // SAIT_VSO_EST_A0033
 Double TComRdCost::m_dDisparityCoeff = 1.0;
@@ -58,19 +60,16 @@
 TComRdCost::~TComRdCost()
 {
-#if !FIX203
-  xUninit();
-#endif
 }
 
 // Calculate RD functions
-#if H_3D_VSO
+#if NH_3D_VSO
 Double TComRdCost::calcRdCost( UInt uiBits, Dist uiDistortion, Bool bFlag, DFunc eDFunc )
 #else
-Double TComRdCost::calcRdCost( UInt uiBits, UInt uiDistortion, Bool bFlag, DFunc eDFunc )
+Double TComRdCost::calcRdCost( UInt uiBits, Distortion uiDistortion, Bool bFlag, DFunc eDFunc )
 #endif
 {
   Double dRdCost = 0.0;
   Double dLambda = 0.0;
-  
+
   switch ( eDFunc )
   {
@@ -79,5 +78,9 @@
       break;
     case DF_SAD:
-      dLambda = (Double)m_uiLambdaMotionSAD;
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+      dLambda = m_dLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
+#else
+      dLambda = (Double)m_uiLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
+#endif
       break;
     case DF_DEFAULT:
@@ -91,13 +94,16 @@
       break;
   }
-  
-  if (bFlag)
+
+  if (bFlag) //NOTE: this "bFlag" is never true
   {
     // Intra8x8, Intra4x4 Block only...
-#if SEQUENCE_LEVEL_LOSSLESS
-    dRdCost = (Double)(uiBits);
-#else
-    dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
-#endif
+    if (m_costMode != COST_STANDARD_LOSSY)
+    {
+      dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+    }
+    else
+    {
+      dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
+    }
   }
   else
@@ -105,22 +111,30 @@
     if (eDFunc == DF_SAD)
     {
-      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)>>16));
-      dRdCost = (Double)(UInt)floor(dRdCost);
+      if (m_costMode != COST_STANDARD_LOSSY)
+      {
+        dRdCost = ((Double(uiDistortion) * 65536) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      }
+      else
+      {
+        dRdCost = floor(Double(uiDistortion) + (floor((Double(uiBits) * dLambda) + 0.5) / 65536.0));
+      }
     }
     else
     {
-#if SEQUENCE_LEVEL_LOSSLESS
-      dRdCost = (Double)(uiBits);
-#else
-      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)));
-      dRdCost = (Double)(UInt)floor(dRdCost);
-#endif
-    }
-  }
-  
+      if (m_costMode != COST_STANDARD_LOSSY)
+      {
+        dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      }
+      else
+      {
+        dRdCost = floor(Double(uiDistortion) + (Double(uiBits) * dLambda) + 0.5);
+      }
+    }
+  }
+
   return dRdCost;
 }
 
-#if H_3D_VSO
+#if NH_3D_VSO
 Double TComRdCost::calcRdCost64( UInt64 uiBits, Dist64 uiDistortion, Bool bFlag, DFunc eDFunc )
 #else
@@ -130,5 +144,5 @@
   Double dRdCost = 0.0;
   Double dLambda = 0.0;
-  
+
   switch ( eDFunc )
   {
@@ -137,5 +151,9 @@
       break;
     case DF_SAD:
-      dLambda = (Double)m_uiLambdaMotionSAD;
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+      dLambda = m_dLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
+#else
+      dLambda = (Double)m_uiLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
+#endif
       break;
     case DF_DEFAULT:
@@ -149,13 +167,16 @@
       break;
   }
-  
-  if (bFlag)
+
+  if (bFlag) //NOTE: this "bFlag" is never true
   {
     // Intra8x8, Intra4x4 Block only...
-#if SEQUENCE_LEVEL_LOSSLESS
-    dRdCost = (Double)(uiBits);
-#else
-    dRdCost = (((Double)(Int64)uiDistortion) + ((Double)(Int64)uiBits * dLambda));
-#endif
+    if (m_costMode != COST_STANDARD_LOSSY)
+    {
+      dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+    }
+    else
+    {
+      dRdCost = (((Double)(Int64)uiDistortion) + ((Double)(Int64)uiBits * dLambda));
+    }
   }
   else
@@ -163,27 +184,54 @@
     if (eDFunc == DF_SAD)
     {
-      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)>>16));
-      dRdCost = (Double)(UInt)floor(dRdCost);
+      if (m_costMode != COST_STANDARD_LOSSY)
+      {
+        dRdCost = ((Double(uiDistortion) * 65536) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      }
+      else
+      {
+        dRdCost = floor(Double(uiDistortion) + (floor((Double(uiBits) * dLambda) + 0.5) / 65536.0));
+      }
     }
     else
     {
-#if SEQUENCE_LEVEL_LOSSLESS
-      dRdCost = (Double)(uiBits);
-#else
-      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)));
-      dRdCost = (Double)(UInt)floor(dRdCost);
-#endif
-    }
-  }
-  
+      if (m_costMode != COST_STANDARD_LOSSY)
+      {
+        dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      }
+      else
+      {
+        dRdCost = floor(Double(uiDistortion) + (Double(uiBits) * dLambda) + 0.5);
+      }
+    }
+  }
+
   return dRdCost;
 }
 
-Void TComRdCost::setLambda( Double dLambda )
+Void TComRdCost::setLambda( Double dLambda, const BitDepths &bitDepths )
 {
   m_dLambda           = dLambda;
   m_sqrtLambda        = sqrt(m_dLambda);
-  m_uiLambdaMotionSAD = (UInt)floor(65536.0 * m_sqrtLambda);
-  m_uiLambdaMotionSSE = (UInt)floor(65536.0 * m_dLambda   );
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  m_dLambdaMotionSAD[0] = 65536.0 * m_sqrtLambda;
+  m_dLambdaMotionSSE[0] = 65536.0 * m_dLambda;
+#if FULL_NBIT
+  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12) / 3.0));
+#else
+  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12 - 6 * (bitDepths.recon[CHANNEL_TYPE_LUMA] - 8)) / 3.0));
+#endif
+  m_dLambdaMotionSAD[1] = 65536.0 * sqrt(dLambda);
+  m_dLambdaMotionSSE[1] = 65536.0 * dLambda;
+#else
+  m_uiLambdaMotionSAD[0] = (UInt)floor(65536.0 * m_sqrtLambda);
+  m_uiLambdaMotionSSE[0] = (UInt)floor(65536.0 * m_dLambda   );
+#if FULL_NBIT
+  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12) / 3.0));
+#else
+  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12 - 6 * (bitDepths.recon[CHANNEL_TYPE_LUMA] - 8)) / 3.0));
+#endif
+  m_uiLambdaMotionSAD[1] = (UInt)floor(65536.0 * sqrt(dLambda));
+  m_uiLambdaMotionSSE[1] = (UInt)floor(65536.0 * dLambda   );
+#endif
 }
 
@@ -192,48 +240,47 @@
 Void TComRdCost::init()
 {
-  m_afpDistortFunc[0]  = NULL;                  // for DF_DEFAULT
-  
-  m_afpDistortFunc[1]  = TComRdCost::xGetSSE;
-  m_afpDistortFunc[2]  = TComRdCost::xGetSSE4;
-  m_afpDistortFunc[3]  = TComRdCost::xGetSSE8;
-  m_afpDistortFunc[4]  = TComRdCost::xGetSSE16;
-  m_afpDistortFunc[5]  = TComRdCost::xGetSSE32;
-  m_afpDistortFunc[6]  = TComRdCost::xGetSSE64;
-  m_afpDistortFunc[7]  = TComRdCost::xGetSSE16N;
-  
-  m_afpDistortFunc[8]  = TComRdCost::xGetSAD;
-  m_afpDistortFunc[9]  = TComRdCost::xGetSAD4;
-  m_afpDistortFunc[10] = TComRdCost::xGetSAD8;
-  m_afpDistortFunc[11] = TComRdCost::xGetSAD16;
-  m_afpDistortFunc[12] = TComRdCost::xGetSAD32;
-  m_afpDistortFunc[13] = TComRdCost::xGetSAD64;
-  m_afpDistortFunc[14] = TComRdCost::xGetSAD16N;
-  
-  m_afpDistortFunc[15] = TComRdCost::xGetSAD;
-  m_afpDistortFunc[16] = TComRdCost::xGetSAD4;
-  m_afpDistortFunc[17] = TComRdCost::xGetSAD8;
-  m_afpDistortFunc[18] = TComRdCost::xGetSAD16;
-  m_afpDistortFunc[19] = TComRdCost::xGetSAD32;
-  m_afpDistortFunc[20] = TComRdCost::xGetSAD64;
-  m_afpDistortFunc[21] = TComRdCost::xGetSAD16N;
-  
-#if AMP_SAD
-  m_afpDistortFunc[43] = TComRdCost::xGetSAD12;
-  m_afpDistortFunc[44] = TComRdCost::xGetSAD24;
-  m_afpDistortFunc[45] = TComRdCost::xGetSAD48;
-
-  m_afpDistortFunc[46] = TComRdCost::xGetSAD12;
-  m_afpDistortFunc[47] = TComRdCost::xGetSAD24;
-  m_afpDistortFunc[48] = TComRdCost::xGetSAD48;
-#endif
-  m_afpDistortFunc[22] = TComRdCost::xGetHADs;
-  m_afpDistortFunc[23] = TComRdCost::xGetHADs;
-  m_afpDistortFunc[24] = TComRdCost::xGetHADs;
-  m_afpDistortFunc[25] = TComRdCost::xGetHADs;
-  m_afpDistortFunc[26] = TComRdCost::xGetHADs;
-  m_afpDistortFunc[27] = TComRdCost::xGetHADs;
-  m_afpDistortFunc[28] = TComRdCost::xGetHADs;
-
-#if H_3D_VSO
+  m_afpDistortFunc[DF_DEFAULT] = NULL;                  // for DF_DEFAULT
+
+  m_afpDistortFunc[DF_SSE    ] = TComRdCost::xGetSSE;
+  m_afpDistortFunc[DF_SSE4   ] = TComRdCost::xGetSSE4;
+  m_afpDistortFunc[DF_SSE8   ] = TComRdCost::xGetSSE8;
+  m_afpDistortFunc[DF_SSE16  ] = TComRdCost::xGetSSE16;
+  m_afpDistortFunc[DF_SSE32  ] = TComRdCost::xGetSSE32;
+  m_afpDistortFunc[DF_SSE64  ] = TComRdCost::xGetSSE64;
+  m_afpDistortFunc[DF_SSE16N ] = TComRdCost::xGetSSE16N;
+
+  m_afpDistortFunc[DF_SAD    ] = TComRdCost::xGetSAD;
+  m_afpDistortFunc[DF_SAD4   ] = TComRdCost::xGetSAD4;
+  m_afpDistortFunc[DF_SAD8   ] = TComRdCost::xGetSAD8;
+  m_afpDistortFunc[DF_SAD16  ] = TComRdCost::xGetSAD16;
+  m_afpDistortFunc[DF_SAD32  ] = TComRdCost::xGetSAD32;
+  m_afpDistortFunc[DF_SAD64  ] = TComRdCost::xGetSAD64;
+  m_afpDistortFunc[DF_SAD16N ] = TComRdCost::xGetSAD16N;
+
+  m_afpDistortFunc[DF_SADS   ] = TComRdCost::xGetSAD;
+  m_afpDistortFunc[DF_SADS4  ] = TComRdCost::xGetSAD4;
+  m_afpDistortFunc[DF_SADS8  ] = TComRdCost::xGetSAD8;
+  m_afpDistortFunc[DF_SADS16 ] = TComRdCost::xGetSAD16;
+  m_afpDistortFunc[DF_SADS32 ] = TComRdCost::xGetSAD32;
+  m_afpDistortFunc[DF_SADS64 ] = TComRdCost::xGetSAD64;
+  m_afpDistortFunc[DF_SADS16N] = TComRdCost::xGetSAD16N;
+
+  m_afpDistortFunc[DF_SAD12  ] = TComRdCost::xGetSAD12;
+  m_afpDistortFunc[DF_SAD24  ] = TComRdCost::xGetSAD24;
+  m_afpDistortFunc[DF_SAD48  ] = TComRdCost::xGetSAD48;
+
+  m_afpDistortFunc[DF_SADS12 ] = TComRdCost::xGetSAD12;
+  m_afpDistortFunc[DF_SADS24 ] = TComRdCost::xGetSAD24;
+  m_afpDistortFunc[DF_SADS48 ] = TComRdCost::xGetSAD48;
+
+  m_afpDistortFunc[DF_HADS   ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS4  ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS8  ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS16 ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS32 ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS64 ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS16N] = TComRdCost::xGetHADs;
+
+#if NH_3D_VSO
   // SAIT_VSO_EST_A0033
   m_afpDistortFunc[29]  = TComRdCost::xGetVSD;
@@ -245,16 +292,15 @@
   m_afpDistortFunc[35]  = TComRdCost::xGetVSD16N;
 #endif
-#if !FIX203
-  m_puiComponentCostOriginP = NULL;
-  m_puiComponentCost        = NULL;
-  m_puiVerCost              = NULL;
-  m_puiHorCost              = NULL;
-#endif
-  m_uiCost                  = 0;
-  m_iCostScale              = 0;
-#if !FIX203
-  m_iSearchLimit            = 0xdeaddead;
-#endif
-#if H_3D_VSO
+
+  m_costMode                   = COST_STANDARD_LOSSY;
+
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  m_dCost                      = 0;
+#else
+  m_uiCost                     = 0;
+#endif
+  m_iCostScale                 = 0;
+
+#if NH_3D_VSO
   m_bUseVSO                 = false;
   m_uiVSOMode               = 0; 
@@ -268,48 +314,14 @@
   m_bUseMask                = false;
 #endif
-}
-
-#if !FIX203
-Void TComRdCost::initRateDistortionModel( Int iSubPelSearchLimit )
-{
-  // make it larger
-  iSubPelSearchLimit += 4;
-  iSubPelSearchLimit *= 8;
-  
-  if( m_iSearchLimit != iSubPelSearchLimit )
-  {
-    xUninit();
-    
-    m_iSearchLimit = iSubPelSearchLimit;
-    
-    m_puiComponentCostOriginP = new UInt[ 4 * iSubPelSearchLimit ];
-    iSubPelSearchLimit *= 2;
-    
-    m_puiComponentCost = m_puiComponentCostOriginP + iSubPelSearchLimit;
-    
-    for( Int n = -iSubPelSearchLimit; n < iSubPelSearchLimit; n++)
-    {
-      m_puiComponentCost[n] = xGetComponentBits( n );
-    }
-  }
-}
-
-Void TComRdCost::xUninit()
-{
-  if( NULL != m_puiComponentCostOriginP )
-  {
-    delete [] m_puiComponentCostOriginP;
-    m_puiComponentCostOriginP = NULL;
-  }
-}
-#endif
-
-UInt TComRdCost::xGetComponentBits( Int iVal )
-{
+
+}
+
+// Static member function
+UInt TComRdCost::xGetExpGolombNumberOfBits( Int iVal )
+{
+  assert(iVal != std::numeric_limits<Int>::min());
   UInt uiLength = 1;
-  UInt uiTemp   = ( iVal <= 0) ? (-iVal<<1)+1: (iVal<<1);
-  
-  assert ( uiTemp );
-  
+  UInt uiTemp   = ( iVal <= 0) ? (UInt(-iVal)<<1)+1: UInt(iVal<<1);
+
   while ( 1 != uiTemp )
   {
@@ -317,5 +329,5 @@
     uiLength += 2;
   }
-  
+
   return uiLength;
 }
@@ -327,5 +339,5 @@
   rcDistParam.iRows    = uiBlkHeight;
   rcDistParam.DistFunc = m_afpDistortFunc[eDFunc + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
-  
+
 #if H_3D_DBBP
   if( m_bUseMask )
@@ -363,28 +375,26 @@
   rcDistParam.pOrg = pcPatternKey->getROIY();
   rcDistParam.pCur = piRefY;
-  
+
   rcDistParam.iStrideOrg = pcPatternKey->getPatternLStride();
   rcDistParam.iStrideCur = iRefStride;
-  
+
   // set Block Width / Height
   rcDistParam.iCols    = pcPatternKey->getROIYWidth();
   rcDistParam.iRows    = pcPatternKey->getROIYHeight();
   rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
-  
-#if AMP_SAD
+
   if (rcDistParam.iCols == 12)
   {
-    rcDistParam.DistFunc = m_afpDistortFunc[43 ];
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD12];
   }
   else if (rcDistParam.iCols == 24)
   {
-    rcDistParam.DistFunc = m_afpDistortFunc[44 ];
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD24];
   }
   else if (rcDistParam.iCols == 48)
   {
-    rcDistParam.DistFunc = m_afpDistortFunc[45 ];
-  }
-#endif
-  
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD48];
+  }
+
 #if H_3D_DBBP
   if( m_bUseMask )
@@ -403,33 +413,31 @@
   rcDistParam.pOrg = pcPatternKey->getROIY();
   rcDistParam.pCur = piRefY;
-  
+
   rcDistParam.iStrideOrg = pcPatternKey->getPatternLStride();
   rcDistParam.iStrideCur = iRefStride * iStep;
-  
+
   // set Step for interpolated buffer
   rcDistParam.iStep = iStep;
-  
+
   // set Block Width / Height
   rcDistParam.iCols    = pcPatternKey->getROIYWidth();
   rcDistParam.iRows    = pcPatternKey->getROIYHeight();
-  
+
   // set distortion function
   if ( !bHADME )
   {
     rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
-#if AMP_SAD
     if (rcDistParam.iCols == 12)
     {
-      rcDistParam.DistFunc = m_afpDistortFunc[46 ];
+      rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS12];
     }
     else if (rcDistParam.iCols == 24)
     {
-      rcDistParam.DistFunc = m_afpDistortFunc[47 ];
+      rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS24];
     }
     else if (rcDistParam.iCols == 48)
     {
-      rcDistParam.DistFunc = m_afpDistortFunc[48 ];
-    }
-#endif
+      rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS48];
+    }
   }
   else
@@ -437,5 +445,5 @@
     rcDistParam.DistFunc = m_afpDistortFunc[DF_HADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
   }
-  
+
 #if H_3D_DBBP
   if( m_bUseMask )
@@ -448,6 +456,5 @@
 }
 
-Void
-TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
+Void TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
 {
   rcDP.pOrg       = p1;
@@ -469,9 +476,9 @@
 }
 
-UInt TComRdCost::calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight )
-{
-  UInt uiSum = 0;
+Distortion TComRdCost::calcHAD( Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight )
+{
+  Distortion uiSum = 0;
   Int x, y;
-  
+
   if ( ( (iWidth % 8) == 0 ) && ( (iHeight % 8) == 0 ) )
   {
@@ -488,6 +495,6 @@
   else
   {
-    assert(iWidth % 4 == 0 && iHeight % 4 == 0);
-    
+    assert ( ( (iWidth % 4) == 0 ) && ( (iHeight % 4) == 0 ) );
+
     for ( y=0; y<iHeight; y+= 4 )
     {
@@ -500,7 +507,6 @@
     }
   }
-  
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
-
+
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8) );
 }
 
@@ -542,5 +548,5 @@
 
 
-UInt TComRdCost::getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText, DFunc eDFunc)
+Distortion TComRdCost::getDistPart( Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, const ComponentID compID, DFunc eDFunc )
 {
   DistParam cDtParam;
@@ -553,6 +559,6 @@
 
   cDtParam.bApplyWeight = false;
-  cDtParam.uiComp       = 255;    // just for assert: to be sure it was set before use, since only values 0,1 or 2 are allowed.
-  cDtParam.bitDepth = bitDepth;
+  cDtParam.compIdx      = MAX_NUM_COMPONENT; // just for assert: to be sure it was set before use
+  cDtParam.bitDepth     = bitDepth;
 
 #if H_3D_IC
@@ -562,11 +568,8 @@
   cDtParam.bUseSDCMRSAD = false;
 #endif
-  if (eText == TEXT_CHROMA_U)
-  {
-   return ((Int) (m_cbDistortionWeight * cDtParam.DistFunc( &cDtParam )));
-  }
-  else if (eText == TEXT_CHROMA_V)
-  {
-   return ((Int) (m_crDistortionWeight * cDtParam.DistFunc( &cDtParam )));
+
+  if (isChroma(compID))
+  {
+    return ((Distortion) (m_distortionWeight[compID] * cDtParam.DistFunc( &cDtParam )));
   }
   else
@@ -575,13 +578,13 @@
   }
 }
-#if H_3D_VSO
+#if NH_3D_VSO
 // SAIT_VSO_EST_A0033
-UInt TComRdCost::getDistPartVSD( TComDataCU* pcCU, UInt uiPartOffset, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight,  Bool bHAD, DFunc eDFunc )
+UInt TComRdCost::getDistPartVSD( TComDataCU* pcCU, UInt uiPartOffset, Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight,  Bool bHAD, DFunc eDFunc )
 {
   AOT( ( m_dDisparityCoeff <= 0 ) || ( m_dDisparityCoeff > 10 ) );
 
-  Pel* piVirRec  = m_pcVideoRecPicYuv->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiPartOffset); 
-  Pel* piVirOrg  = m_pcDepthPicYuv   ->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiPartOffset); 
-  Int iVirStride = m_pcVideoRecPicYuv->getStride();   
+  Pel* piVirRec  = m_pcVideoRecPicYuv->getAddr( COMPONENT_Y, pcCU->getCtuRsAddr( ), pcCU->getZorderIdxInCtu()+uiPartOffset ); 
+  Pel* piVirOrg  = m_pcDepthPicYuv   ->getAddr( COMPONENT_Y, pcCU->getCtuRsAddr( ), pcCU->getZorderIdxInCtu()+uiPartOffset ); 
+  Int iVirStride = m_pcVideoRecPicYuv->getStride( COMPONENT_Y );   
 
   DistParam cDtParam;
@@ -596,8 +599,7 @@
   cDtParam.iStep      = 1;
 
-  cDtParam.bApplyWeight = false;
-  cDtParam.uiComp       = 255;    // just for assert: to be sure it was set before use, since only values 0,1 or 2 are allowed.
-
-  cDtParam.bitDepth   = g_bitDepthY;
+  cDtParam.bApplyWeight = false;  
+
+  cDtParam.bitDepth   = bitDepth;
 
   Dist dist = cDtParam.DistFunc( &cDtParam );
@@ -611,9 +613,9 @@
     if ( !bHAD )
     {
-      distDepth = (Dist) getDistPart( g_bitDepthY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
+      distDepth = (Dist) getDistPart( bitDepth, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight, COMPONENT_Y);
     }
     else
     {
-      distDepth = (Dist) calcHAD( g_bitDepthY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
+      distDepth = (Dist) calcHAD( bitDepth, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
     }
 
@@ -756,9 +758,9 @@
 // --------------------------------------------------------------------------------------------------------------------
 
-UInt TComRdCost::xGetSAD( DistParam* pcDtParam )
+Distortion TComRdCost::xGetSAD( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSADw( pcDtParam );
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
 #if H_3D_IC
@@ -774,13 +776,14 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
   Int  iStrideCur = pcDtParam->iStrideCur;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-- )
   {
@@ -792,14 +795,15 @@
     piCur += iStrideCur;
   }
-  
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-UInt TComRdCost::xGetSAD4( DistParam* pcDtParam )
-{
-  if ( pcDtParam->bApplyWeight ) 
-  {
-    return xGetSADw( pcDtParam );
-  }
+
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+
 #if H_3D_IC
   if( pcDtParam->bUseIC )
@@ -814,6 +818,7 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -821,7 +826,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -830,19 +835,20 @@
     uiSum += abs( piOrg[2] - piCur[2] );
     uiSum += abs( piOrg[3] - piCur[3] );
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-UInt TComRdCost::xGetSAD8( DistParam* pcDtParam )
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD8( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSADw( pcDtParam );
-  }
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+
 #if H_3D_IC
   if( pcDtParam->bUseIC )
@@ -857,6 +863,7 @@
   }
 #endif
-  Pel* piOrg      = pcDtParam->pOrg;
-  Pel* piCur      = pcDtParam->pCur;
+
+  const Pel* piOrg      = pcDtParam->pOrg;
+  const Pel* piCur      = pcDtParam->pCur;
   Int  iRows      = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -864,7 +871,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -877,19 +884,20 @@
     uiSum += abs( piOrg[6] - piCur[6] );
     uiSum += abs( piOrg[7] - piCur[7] );
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-UInt TComRdCost::xGetSAD16( DistParam* pcDtParam )
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD16( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSADw( pcDtParam );
-  }
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+
 #if H_3D_IC
   if( pcDtParam->bUseIC )
@@ -904,6 +912,7 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -911,7 +920,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -932,19 +941,18 @@
     uiSum += abs( piOrg[14] - piCur[14] );
     uiSum += abs( piOrg[15] - piCur[15] );
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-#if AMP_SAD
-UInt TComRdCost::xGetSAD12( DistParam* pcDtParam )
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD12( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSADw( pcDtParam );
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
 #if H_3D_IC
@@ -960,6 +968,7 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -967,7 +976,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -984,15 +993,14 @@
     uiSum += abs( piOrg[10] - piCur[10] );
     uiSum += abs( piOrg[11] - piCur[11] );
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-#endif
-
-UInt TComRdCost::xGetSAD16N( DistParam* pcDtParam )
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD16N( DistParam* pcDtParam )
 {
 #if H_3D_IC
@@ -1008,6 +1016,7 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
@@ -1016,7 +1025,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1043,15 +1052,16 @@
     piCur += iStrideCur;
   }
-  
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-UInt TComRdCost::xGetSAD32( DistParam* pcDtParam )
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD32( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSADw( pcDtParam );
-  }
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+
 #if H_3D_IC
   if( pcDtParam->bUseIC )
@@ -1066,6 +1076,7 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1073,7 +1084,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1110,20 +1121,20 @@
     uiSum += abs( piOrg[30] - piCur[30] );
     uiSum += abs( piOrg[31] - piCur[31] );
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-#if AMP_SAD
-UInt TComRdCost::xGetSAD24( DistParam* pcDtParam )
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD24( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSADw( pcDtParam );
-  }
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+
 #if H_3D_IC
   if( pcDtParam->bUseIC )
@@ -1138,6 +1149,7 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1145,7 +1157,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1174,21 +1186,20 @@
     uiSum += abs( piOrg[22] - piCur[22] );
     uiSum += abs( piOrg[23] - piCur[23] );
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-#endif
-
-UInt TComRdCost::xGetSAD64( DistParam* pcDtParam )
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD64( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSADw( pcDtParam );
-  }
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+
 #if H_3D_IC
   if( pcDtParam->bUseIC )
@@ -1203,6 +1214,7 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1210,7 +1222,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1279,19 +1291,18 @@
     uiSum += abs( piOrg[62] - piCur[62] );
     uiSum += abs( piOrg[63] - piCur[63] );
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-#if AMP_SAD
-UInt TComRdCost::xGetSAD48( DistParam* pcDtParam )
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+Distortion TComRdCost::xGetSAD48( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSADw( pcDtParam );
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
 #if H_3D_IC
@@ -1307,6 +1318,7 @@
   }
 #endif
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iSubShift  = pcDtParam->iSubShift;
@@ -1314,7 +1326,7 @@
   Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
   Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1367,13 +1379,13 @@
     uiSum += abs( piOrg[46] - piCur[46] );
     uiSum += abs( piOrg[47] - piCur[47] );
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   uiSum <<= iSubShift;
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-#endif
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
 
 #if H_3D_IC || H_3D_INTER_SDC
@@ -1645,5 +1657,4 @@
 }
 
-#if AMP_SAD
 UInt TComRdCost::xGetSAD12ic( DistParam* pcDtParam )
 {
@@ -1726,5 +1737,5 @@
   return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
 }
-#endif
+
 
 UInt TComRdCost::xGetSAD16Nic( DistParam* pcDtParam )
@@ -1962,5 +1973,5 @@
 }
 
-#if AMP_SAD
+
 UInt TComRdCost::xGetSAD24ic( DistParam* pcDtParam )
 {
@@ -2079,5 +2090,4 @@
   return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
 }
-#endif
 
 UInt TComRdCost::xGetSAD64ic( DistParam* pcDtParam )
@@ -2318,5 +2328,5 @@
 }
 
-#if AMP_SAD
+
 UInt TComRdCost::xGetSAD48ic( DistParam* pcDtParam )
 {
@@ -2509,28 +2519,26 @@
 }
 #endif
-
-#endif
 // --------------------------------------------------------------------------------------------------------------------
 // SSE
 // --------------------------------------------------------------------------------------------------------------------
 
-UInt TComRdCost::xGetSSE( DistParam* pcDtParam )
+Distortion TComRdCost::xGetSSE( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSSEw( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
   Int  iStrideCur = pcDtParam->iStrideCur;
-  
-  UInt uiSum = 0;
-  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
-  
-  Int iTemp;
-  
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int iTemp;
+
   for( ; iRows != 0; iRows-- )
   {
@@ -2538,331 +2546,337 @@
     {
       iTemp = piOrg[n  ] - piCur[n  ];
-      uiSum += ( iTemp * iTemp ) >> uiShift;
-    }
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+      uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   return ( uiSum );
 }
 
-UInt TComRdCost::xGetSSE4( DistParam* pcDtParam )
+Distortion TComRdCost::xGetSSE4( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
     assert( pcDtParam->iCols == 4 );
-    return xGetSSEw( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
   Int  iStrideCur = pcDtParam->iStrideCur;
-  
-  UInt uiSum = 0;
-  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
-  
-  Int  iTemp;
-  
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
   for( ; iRows != 0; iRows-- )
   {
-    
-    iTemp = piOrg[0] - piCur[0]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[1] - piCur[1]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[2] - piCur[2]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[3] - piCur[3]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    iTemp = piOrg[0] - piCur[0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[1] - piCur[1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[2] - piCur[2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[3] - piCur[3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   return ( uiSum );
 }
 
-UInt TComRdCost::xGetSSE8( DistParam* pcDtParam )
+Distortion TComRdCost::xGetSSE8( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
     assert( pcDtParam->iCols == 8 );
-    return xGetSSEw( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
   Int  iStrideCur = pcDtParam->iStrideCur;
-  
-  UInt uiSum = 0;
-  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
-  
-  Int  iTemp;
-  
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
   for( ; iRows != 0; iRows-- )
   {
-    iTemp = piOrg[0] - piCur[0]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[1] - piCur[1]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[2] - piCur[2]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[3] - piCur[3]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[4] - piCur[4]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[5] - piCur[5]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[6] - piCur[6]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[7] - piCur[7]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+    iTemp = piOrg[0] - piCur[0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[1] - piCur[1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[2] - piCur[2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[3] - piCur[3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[4] - piCur[4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[5] - piCur[5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[6] - piCur[6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[7] - piCur[7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   return ( uiSum );
 }
 
-UInt TComRdCost::xGetSSE16( DistParam* pcDtParam )
+Distortion TComRdCost::xGetSSE16( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
     assert( pcDtParam->iCols == 16 );
-    return xGetSSEw( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
   Int  iStrideCur = pcDtParam->iStrideCur;
-  
-  UInt uiSum = 0;
-  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
-  
-  Int  iTemp;
-  
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
   for( ; iRows != 0; iRows-- )
   {
-    
-    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[10] - piCur[10]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[11] - piCur[11]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[12] - piCur[12]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[13] - piCur[13]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[14] - piCur[14]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[15] - piCur[15]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   return ( uiSum );
 }
 
-UInt TComRdCost::xGetSSE16N( DistParam* pcDtParam )
+Distortion TComRdCost::xGetSSE16N( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetSSEw( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iCols   = pcDtParam->iCols;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
   Int  iStrideCur = pcDtParam->iStrideCur;
-  
-  UInt uiSum = 0;
-  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
-  Int  iTemp;
-  
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
   for( ; iRows != 0; iRows-- )
   {
     for (Int n = 0; n < iCols; n+=16 )
     {
-      
-      iTemp = piOrg[n+ 0] - piCur[n+ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 1] - piCur[n+ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 2] - piCur[n+ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 3] - piCur[n+ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 4] - piCur[n+ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 5] - piCur[n+ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 6] - piCur[n+ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 7] - piCur[n+ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 8] - piCur[n+ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+ 9] - piCur[n+ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+10] - piCur[n+10]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+11] - piCur[n+11]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+12] - piCur[n+12]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+13] - piCur[n+13]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+14] - piCur[n+14]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      iTemp = piOrg[n+15] - piCur[n+15]; uiSum += ( iTemp * iTemp ) >> uiShift;
-      
-    }
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+      iTemp = piOrg[n+ 0] - piCur[n+ 0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 1] - piCur[n+ 1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 2] - piCur[n+ 2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 3] - piCur[n+ 3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 4] - piCur[n+ 4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 5] - piCur[n+ 5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 6] - piCur[n+ 6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 7] - piCur[n+ 7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 8] - piCur[n+ 8]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 9] - piCur[n+ 9]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+10] - piCur[n+10]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+11] - piCur[n+11]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+12] - piCur[n+12]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+13] - piCur[n+13]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+14] - piCur[n+14]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+15] - piCur[n+15]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   return ( uiSum );
 }
 
-UInt TComRdCost::xGetSSE32( DistParam* pcDtParam )
+Distortion TComRdCost::xGetSSE32( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
     assert( pcDtParam->iCols == 32 );
-    return xGetSSEw( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
   Int  iStrideCur = pcDtParam->iStrideCur;
-  
-  UInt uiSum = 0;
-  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
-  Int  iTemp;
-  
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
   for( ; iRows != 0; iRows-- )
   {
-    
-    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[16] - piCur[16]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[17] - piCur[17]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[18] - piCur[18]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[19] - piCur[19]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[20] - piCur[20]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[21] - piCur[21]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[22] - piCur[22]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[23] - piCur[23]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[24] - piCur[24]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[25] - piCur[25]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[26] - piCur[26]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[27] - piCur[27]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[28] - piCur[28]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[29] - piCur[29]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[30] - piCur[30]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[31] - piCur[31]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[10] - piCur[10]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[11] - piCur[11]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[12] - piCur[12]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[13] - piCur[13]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[14] - piCur[14]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[15] - piCur[15]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[16] - piCur[16]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[17] - piCur[17]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[18] - piCur[18]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[19] - piCur[19]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[20] - piCur[20]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[21] - piCur[21]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[22] - piCur[22]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[23] - piCur[23]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[24] - piCur[24]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[25] - piCur[25]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[26] - piCur[26]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[27] - piCur[27]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[28] - piCur[28]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[29] - piCur[29]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[30] - piCur[30]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[31] - piCur[31]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   return ( uiSum );
 }
 
-UInt TComRdCost::xGetSSE64( DistParam* pcDtParam )
+Distortion TComRdCost::xGetSSE64( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
     assert( pcDtParam->iCols == 64 );
-    return xGetSSEw( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
   Int  iRows   = pcDtParam->iRows;
   Int  iStrideOrg = pcDtParam->iStrideOrg;
   Int  iStrideCur = pcDtParam->iStrideCur;
-  
-  UInt uiSum = 0;
-  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
-  Int  iTemp;
-  
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
   for( ; iRows != 0; iRows-- )
   {
-    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[16] - piCur[16]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[17] - piCur[17]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[18] - piCur[18]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[19] - piCur[19]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[20] - piCur[20]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[21] - piCur[21]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[22] - piCur[22]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[23] - piCur[23]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[24] - piCur[24]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[25] - piCur[25]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[26] - piCur[26]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[27] - piCur[27]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[28] - piCur[28]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[29] - piCur[29]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[30] - piCur[30]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[31] - piCur[31]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[32] - piCur[32]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[33] - piCur[33]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[34] - piCur[34]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[35] - piCur[35]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[36] - piCur[36]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[37] - piCur[37]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[38] - piCur[38]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[39] - piCur[39]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[40] - piCur[40]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[41] - piCur[41]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[42] - piCur[42]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[43] - piCur[43]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[44] - piCur[44]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[45] - piCur[45]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[46] - piCur[46]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[47] - piCur[47]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[48] - piCur[48]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[49] - piCur[49]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[50] - piCur[50]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[51] - piCur[51]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[52] - piCur[52]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[53] - piCur[53]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[54] - piCur[54]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[55] - piCur[55]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[56] - piCur[56]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[57] - piCur[57]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[58] - piCur[58]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[59] - piCur[59]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[60] - piCur[60]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[61] - piCur[61]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[62] - piCur[62]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    iTemp = piOrg[63] - piCur[63]; uiSum += ( iTemp * iTemp ) >> uiShift;
-    
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-  
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[10] - piCur[10]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[11] - piCur[11]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[12] - piCur[12]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[13] - piCur[13]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[14] - piCur[14]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[15] - piCur[15]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[16] - piCur[16]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[17] - piCur[17]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[18] - piCur[18]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[19] - piCur[19]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[20] - piCur[20]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[21] - piCur[21]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[22] - piCur[22]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[23] - piCur[23]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[24] - piCur[24]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[25] - piCur[25]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[26] - piCur[26]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[27] - piCur[27]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[28] - piCur[28]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[29] - piCur[29]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[30] - piCur[30]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[31] - piCur[31]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[32] - piCur[32]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[33] - piCur[33]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[34] - piCur[34]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[35] - piCur[35]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[36] - piCur[36]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[37] - piCur[37]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[38] - piCur[38]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[39] - piCur[39]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[40] - piCur[40]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[41] - piCur[41]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[42] - piCur[42]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[43] - piCur[43]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[44] - piCur[44]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[45] - piCur[45]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[46] - piCur[46]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[47] - piCur[47]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[48] - piCur[48]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[49] - piCur[49]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[50] - piCur[50]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[51] - piCur[51]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[52] - piCur[52]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[53] - piCur[53]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[54] - piCur[54]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[55] - piCur[55]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[56] - piCur[56]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[57] - piCur[57]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[58] - piCur[58]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[59] - piCur[59]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[60] - piCur[60]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[61] - piCur[61]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[62] - piCur[62]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[63] - piCur[63]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
   return ( uiSum );
 }
-#if H_3D_VSO
+
+#if NH_3D_VSO
 //SAIT_VSO_EST_A0033
 UInt TComRdCost::getVSDEstimate( Int dDM, Pel* pOrg, Int iOrgStride,  Pel* pVirRec, Pel* pVirOrg, Int iVirStride, Int x, Int y )
-{
-  Double  dD = ( (Double) ( dDM >> DISTORTION_PRECISION_ADJUSTMENT( g_bitDepthY - 8 ) ) ) * m_dDisparityCoeff;
-
-  Double dDepthWeight = ( pOrg[x] >=  ( (1<<(g_bitDepthY - 3)) + (1<<(g_bitDepthY - 2)) ) ? 4 : pOrg[x] > ((1<<g_bitDepthY) >> 4) ? (Float)(pOrg[x] - ((1<<g_bitDepthY) >> 4))/(Float)((1<<g_bitDepthY) >> 3) + 1 : 1.0 );
+{ 
+  // change to use bit depth from DistParam struct
+  Double  dD = ( (Double) ( dDM >> ( ENC_INTERNAL_BIT_DEPTH - 8 ) ) ) * m_dDisparityCoeff;
+
+  Double dDepthWeight = ( pOrg[x] >=  ( (1<<(REN_BIT_DEPTH - 3)) + (1<<(REN_BIT_DEPTH - 2)) ) ? 4 : pOrg[x] > ((1<<REN_BIT_DEPTH) >> 4) ? (Float)(pOrg[x] - ((1<<REN_BIT_DEPTH) >> 4))/(Float)((1<<REN_BIT_DEPTH) >> 3) + 1 : 1.0 );
+
   Double dTemp = ( 0.5 * fabs(dD) * dDepthWeight * ( abs( (Int) pVirRec[ x+y*iVirStride ] - (Int) pVirRec[ x-1+y*iVirStride ] ) + abs( (Int) pVirRec[ x+y*iVirStride ] - (Int) pVirRec[ x+1+y*iVirStride ] ) ) );
   Int iTemp = (Int) (((dTemp) < 0)? (Int)((dTemp) - 0.5) : (Int)((dTemp) + 0.5));
@@ -3092,7 +3106,8 @@
 // --------------------------------------------------------------------------------------------------------------------
 
-UInt TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int satd = 0, diff[4], m[4];
+Distortion TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Distortion satd = 0;
+  TCoeff diff[4], m[4];
   assert( iStep == 1 );
   diff[0] = piOrg[0             ] - piCur[0];
@@ -3104,17 +3119,19 @@
   m[2] = diff[0] - diff[2];
   m[3] = diff[1] - diff[3];
-  
+
   satd += abs(m[0] + m[1]);
   satd += abs(m[0] - m[1]);
   satd += abs(m[2] + m[3]);
   satd += abs(m[2] - m[3]);
-  
+
   return satd;
 }
 
-UInt TComRdCost::xCalcHADs4x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int k, satd = 0, diff[16], m[16], d[16];
-  
+Distortion TComRdCost::xCalcHADs4x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k;
+  Distortion satd = 0;
+  TCoeff diff[16], m[16], d[16];
+
   assert( iStep == 1 );
   for( k = 0; k < 16; k+=4 )
@@ -3124,9 +3141,9 @@
     diff[k+2] = piOrg[2] - piCur[2];
     diff[k+3] = piOrg[3] - piCur[3];
-    
-    piCur += iStrideCur;
-    piOrg += iStrideOrg;
-  }
-  
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+
   /*===== hadamard transform =====*/
   m[ 0] = diff[ 0] + diff[12];
@@ -3146,5 +3163,5 @@
   m[14] = diff[ 2] - diff[14];
   m[15] = diff[ 3] - diff[15];
-  
+
   d[ 0] = m[ 0] + m[ 4];
   d[ 1] = m[ 1] + m[ 5];
@@ -3163,5 +3180,5 @@
   d[14] = m[14] - m[10];
   d[15] = m[15] - m[11];
-  
+
   m[ 0] = d[ 0] + d[ 3];
   m[ 1] = d[ 1] + d[ 2];
@@ -3180,5 +3197,5 @@
   m[14] = d[13] - d[14];
   m[15] = d[12] - d[15];
-  
+
   d[ 0] = m[ 0] + m[ 1];
   d[ 1] = m[ 0] - m[ 1];
@@ -3197,5 +3214,5 @@
   d[14] = m[14] + m[15];
   d[15] = m[15] - m[14];
-  
+
   for (k=0; k<16; ++k)
   {
@@ -3203,12 +3220,13 @@
   }
   satd = ((satd+1)>>1);
-  
+
   return satd;
 }
 
-UInt TComRdCost::xCalcHADs8x8( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int k, i, j, jj, sad=0;
-  Int diff[64], m1[8][8], m2[8][8], m3[8][8];
+Distortion TComRdCost::xCalcHADs8x8( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj;
+  Distortion sad = 0;
+  TCoeff diff[64], m1[8][8], m2[8][8], m3[8][8];
   assert( iStep == 1 );
   for( k = 0; k < 64; k += 8 )
@@ -3222,9 +3240,9 @@
     diff[k+6] = piOrg[6] - piCur[6];
     diff[k+7] = piOrg[7] - piCur[7];
-    
-    piCur += iStrideCur;
-    piOrg += iStrideOrg;
-  }
-  
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+
   //horizontal
   for (j=0; j < 8; j++)
@@ -3239,5 +3257,5 @@
     m2[j][6] = diff[jj+2] - diff[jj+6];
     m2[j][7] = diff[jj+3] - diff[jj+7];
-    
+
     m1[j][0] = m2[j][0] + m2[j][2];
     m1[j][1] = m2[j][1] + m2[j][3];
@@ -3248,5 +3266,5 @@
     m1[j][6] = m2[j][4] - m2[j][6];
     m1[j][7] = m2[j][5] - m2[j][7];
-    
+
     m2[j][0] = m1[j][0] + m1[j][1];
     m2[j][1] = m1[j][0] - m1[j][1];
@@ -3258,5 +3276,5 @@
     m2[j][7] = m1[j][6] - m1[j][7];
   }
-  
+
   //vertical
   for (i=0; i < 8; i++)
@@ -3270,5 +3288,5 @@
     m3[6][i] = m2[2][i] - m2[6][i];
     m3[7][i] = m2[3][i] - m2[7][i];
-    
+
     m1[0][i] = m3[0][i] + m3[2][i];
     m1[1][i] = m3[1][i] + m3[3][i];
@@ -3279,5 +3297,5 @@
     m1[6][i] = m3[4][i] - m3[6][i];
     m1[7][i] = m3[5][i] - m3[7][i];
-    
+
     m2[0][i] = m1[0][i] + m1[1][i];
     m2[1][i] = m1[0][i] - m1[1][i];
@@ -3289,5 +3307,5 @@
     m2[7][i] = m1[6][i] - m1[7][i];
   }
-  
+
   for (i = 0; i < 8; i++)
   {
@@ -3297,79 +3315,16 @@
     }
   }
-  
+
   sad=((sad+2)>>2);
-  
+
   return sad;
 }
 
-UInt TComRdCost::xGetHADs4( DistParam* pcDtParam )
+
+Distortion TComRdCost::xGetHADs( DistParam* pcDtParam )
 {
   if ( pcDtParam->bApplyWeight )
   {
-    return xGetHADs4w( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
-  Int  iStep  = pcDtParam->iStep;
-  Int  y;
-  Int  iOffsetOrg = iStrideOrg<<2;
-  Int  iOffsetCur = iStrideCur<<2;
-  
-  UInt uiSum = 0;
-  
-  for ( y=0; y<iRows; y+= 4 )
-  {
-    uiSum += xCalcHADs4x4( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
-    piOrg += iOffsetOrg;
-    piCur += iOffsetCur;
-  }
-  
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-UInt TComRdCost::xGetHADs8( DistParam* pcDtParam )
-{
-  if ( pcDtParam->bApplyWeight )
-  {
-    return xGetHADs8w( pcDtParam );
-  }
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
-  Int  iStep  = pcDtParam->iStep;
-  Int  y;
-  
-  UInt uiSum = 0;
-  
-  if ( iRows == 4 )
-  {
-    uiSum += xCalcHADs4x4( piOrg+0, piCur        , iStrideOrg, iStrideCur, iStep );
-    uiSum += xCalcHADs4x4( piOrg+4, piCur+4*iStep, iStrideOrg, iStrideCur, iStep );
-  }
-  else
-  {
-    Int  iOffsetOrg = iStrideOrg<<3;
-    Int  iOffsetCur = iStrideCur<<3;
-    for ( y=0; y<iRows; y+= 8 )
-    {
-      uiSum += xCalcHADs8x8( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
-    }
-  }
-  
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-UInt TComRdCost::xGetHADs( DistParam* pcDtParam )
-{
-  if ( pcDtParam->bApplyWeight )
-  {
-    return xGetHADsw( pcDtParam );
+    return TComRdCostWeightPrediction::xGetHADsw( pcDtParam );
   }
 #if H_3D_IC
@@ -3385,4 +3340,5 @@
   }
 #endif
+
   Pel* piOrg   = pcDtParam->pOrg;
   Pel* piCur   = pcDtParam->pCur;
@@ -3392,9 +3348,9 @@
   Int  iStrideOrg = pcDtParam->iStrideOrg;
   Int  iStep  = pcDtParam->iStep;
-  
+
   Int  x, y;
-  
-  UInt uiSum = 0;
-  
+
+  Distortion uiSum = 0;
+
   if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
   {
@@ -3415,5 +3371,5 @@
     Int  iOffsetOrg = iStrideOrg<<2;
     Int  iOffsetCur = iStrideCur<<2;
-    
+
     for ( y=0; y<iRows; y+= 4 )
     {
@@ -3444,6 +3400,6 @@
     assert(false);
   }
-  
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
 }
 
@@ -3593,6 +3549,5 @@
 }
 #endif
-
-#if H_3D_VSO
+#if NH_3D_VSO
 Void TComRdCost::setLambdaVSO( Double dLambdaVSO )
 {
@@ -3602,5 +3557,6 @@
   m_uiLambdaMotionSSEVSO = (UInt)floor(65536.0 *       m_dLambdaVSO    );
 }
-
+#endif
+#if NH_3D_VSO
 Dist TComRdCost::xGetDistVSOMode4( Int iStartPosX, Int iStartPosY, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD )
 { 
@@ -3621,5 +3577,5 @@
 
 
-Dist TComRdCost::getDistPartVSO( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bHAD )
+Dist TComRdCost::getDistPartVSO( TComDataCU* pcCU, UInt uiAbsPartIndex, Int bitDepth, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bHAD )
 { 
   assert( m_bUseVSO );  
@@ -3635,5 +3591,5 @@
   if ( m_bUseWVSO )   
   {
-    Int iDWeight   = m_iDWeight   * m_iDWeight;
+    Int iDWeight   = m_iDWeight   * m_iDWeight  ;
     Int iVSOWeight = m_iVSOWeight * m_iVSOWeight;
     Dist distDepth;
@@ -3641,9 +3597,9 @@
     if ( !bHAD )
     {
-       distDepth = (Dist) getDistPart( g_bitDepthY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
+       distDepth = (Dist) getDistPart( bitDepth, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight, COMPONENT_Y);
     }
     else
     {
-       distDepth = (Dist) calcHAD( g_bitDepthY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
+       distDepth = (Dist) calcHAD    ( bitDepth, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
     }
     
@@ -3725,5 +3681,16 @@
 }
 
-Void TComRdCost::setRenModelData( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piData, Int iStride, Int iBlkWidth, Int iBlkHeight )
+Void TComRdCost::setRenModelData( const TComDataCU* pcCU, UInt uiAbsPartIndex, const TComYuv* pcYuv, const TComTURecurse* tuRecurseWithPU )
+{
+  const TComRectangle &puRect=tuRecurseWithPU->getRect(COMPONENT_Y);
+  const UInt  uiCompWidth   = puRect.width;
+  const UInt  uiCompHeight  = puRect.height;
+
+  const Pel*  piSrc         = pcYuv->getAddr( COMPONENT_Y, uiAbsPartIndex );
+  const UInt  uiSrcStride   = pcYuv->getStride( COMPONENT_Y);
+  setRenModelData( pcCU, uiAbsPartIndex, piSrc, uiSrcStride, uiCompWidth, uiCompHeight ); 
+}
+
+Void TComRdCost::setRenModelData( const TComDataCU* pcCU, UInt uiAbsPartIndex, const Pel* piData, Int iStride, Int iBlkWidth, Int iBlkHeight )
 {
   UInt iBlkX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIndex]];
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCost.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCost.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,6 +46,8 @@
 #include "TComSlice.h"
 #include "TComRdCostWeightPrediction.h"
-#if H_3D
+#if NH_3D
 #include "../TLibRenderer/TRenModel.h"
+#include "TComYuv.h"
+#include "TComTU.h"
 #endif
 
@@ -53,9 +55,7 @@
 //! \{
 
-#define FIX203 1
-
 class DistParam;
 class TComPattern;
-#if H_3D
+#if NH_3D
 class TComRdCost; 
 #endif
@@ -66,8 +66,8 @@
 
 // for function pointer
-typedef UInt (*FpDistFunc) (DistParam*);
-
-#if H_3D
-#if H_3D_VSO
+typedef Distortion (*FpDistFunc) (DistParam*); // TODO: can this pointer be replaced with a reference? - there are no NULL checks on pointer.
+
+#if NH_3D
+#if NH_3D_VSO
 typedef Dist (TComRdCost::*FpDistFuncVSO) ( Int, Int, Pel*, Int, Pel*, Int, UInt, UInt, Bool );
 #endif
@@ -85,5 +85,5 @@
   Int   iStrideOrg;
   Int   iStrideCur;
-#if H_3D_VSO
+#if NH_3D_VSO
   // SAIT_VSO_EST_A0033
   Pel*  pVirRec;
@@ -103,12 +103,12 @@
   Int   bitDepth;
 
-  Bool            bApplyWeight;     // whether weithed prediction is used or not
-  wpScalingParam  *wpCur;           // weithed prediction scaling parameters for current ref
-  UInt            uiComp;           // uiComp = 0 (luma Y), 1 (chroma U), 2 (chroma V)
+  Bool            bApplyWeight;     // whether weighted prediction is used or not
+  WPScalingParam  *wpCur;           // weighted prediction scaling parameters for current ref
+  ComponentID     compIdx;
 
   // (vertical) subsampling shift (for reducing complexity)
   // - 0 = no subsampling, 1 = even rows, 2 = every 4th, etc.
   Int   iSubShift;
-  
+
   DistParam()
   {
@@ -123,5 +123,5 @@
     iSubShift = 0;
     bitDepth = 0;
-#if H_3D_VSO
+#if NH_3D_VSO
     // SAIT_VSO_EST_A0033
     pVirRec = NULL;
@@ -137,66 +137,55 @@
 /// RD cost computation class
 class TComRdCost
-  : public TComRdCostWeightPrediction
 {
 private:
   // for distortion
-  
-#if AMP_SAD
-  FpDistFunc              m_afpDistortFunc[64]; // [eDFunc]
-#else  
-  FpDistFunc              m_afpDistortFunc[33]; // [eDFunc]
-#endif  
-  
-  Double                  m_cbDistortionWeight; 
-  Double                  m_crDistortionWeight; 
+
+  FpDistFunc              m_afpDistortFunc[DF_TOTAL_FUNCTIONS]; // [eDFunc]
+  CostMode                m_costMode;
+  Double                  m_distortionWeight[MAX_NUM_COMPONENT]; // only chroma values are used.
   Double                  m_dLambda;
   Double                  m_sqrtLambda;
-  UInt                    m_uiLambdaMotionSAD;
-  UInt                    m_uiLambdaMotionSSE;
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  Double                  m_dLambdaMotionSAD[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
+  Double                  m_dLambdaMotionSSE[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
+#else
+  UInt                    m_uiLambdaMotionSAD[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
+  UInt                    m_uiLambdaMotionSSE[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
+#endif
   Double                  m_dFrameLambda;
-#if H_3D_VSO
+#if NH_3D_VSO
   // SAIT_VSO_EST_A0033
   static Double           m_dDisparityCoeff;
 #endif
-  
+
   // for motion cost
-#if FIX203
   TComMv                  m_mvPredictor;
-#else
-  UInt*                   m_puiComponentCostOriginP;
-  UInt*                   m_puiComponentCost;
-  UInt*                   m_puiVerCost;
-  UInt*                   m_puiHorCost;
-#endif
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  Double                  m_dCost;
+#else
   UInt                    m_uiCost;
+#endif
   Int                     m_iCostScale;
-#if !FIX203
-  Int                     m_iSearchLimit;
-#endif
-  
 #if H_3D_DBBP
   Bool                    m_bUseMask;
 #endif
-  
+
 public:
   TComRdCost();
   virtual ~TComRdCost();
-
-#if H_3D_VSO
+#if NH_3D_VSO
   Double  calcRdCost  ( UInt   uiBits, Dist   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
   Double  calcRdCost64( UInt64 uiBits, Dist64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
 #else
-  Double  calcRdCost  ( UInt   uiBits, UInt   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost  ( UInt   uiBits, Distortion uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
   Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
 #endif
 
-  
-  Void    setCbDistortionWeight      ( Double cbDistortionWeight) { m_cbDistortionWeight = cbDistortionWeight; };
-  Void    setCrDistortionWeight      ( Double crDistortionWeight) { m_crDistortionWeight = crDistortionWeight; };
-  Void    setLambda      ( Double dLambda );
+  Void    setDistortionWeight  ( const ComponentID compID, const Double distortionWeight ) { m_distortionWeight[compID] = distortionWeight; }
+  Void    setLambda      ( Double dLambda, const BitDepths &bitDepths );
   Void    setFrameLambda ( Double dLambda ) { m_dFrameLambda = dLambda; }
-  
+
   Double  getSqrtLambda ()   { return m_sqrtLambda; }
-#if H_3D_VSO
+#if NH_3D_VSO
   // SAIT_VSO_EST_A0033
   Void    setDisparityCoeff( Double dDisparityCoeff ) { m_dDisparityCoeff = dDisparityCoeff; }
@@ -205,68 +194,66 @@
 
   Double  getLambda() { return m_dLambda; }
-  Double  getChromaWeight () {return((m_cbDistortionWeight+m_crDistortionWeight)/2.0);}
-  
+  Double  getChromaWeight () { return ((m_distortionWeight[COMPONENT_Cb] + m_distortionWeight[COMPONENT_Cr]) / 2.0); }
+
+  Void    setCostMode(CostMode   m )    { m_costMode = m; }
+
   // Distortion Functions
   Void    init();
-  
+
   Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
   Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
   Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
   Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
-  
+
 #if H_3D_DBBP
   Void    setUseMask(Bool b) { m_bUseMask = b; }
 #endif
-  
-  UInt    calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
-  
+
+  Distortion calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
+
 #if H_3D_FAST_DEPTH_INTRA
   UInt    calcVAR(Pel* pi0, Int stride, Int width, Int height, Int cuDepth);
 #endif  
+
   // for motion cost
-#if !FIX203
-  Void    initRateDistortionModel( Int iSubPelSearchLimit );
-  Void    xUninit();
-#endif
-  UInt    xGetComponentBits( Int iVal );
-  Void    getMotionCost( Bool bSad, Int iAdd ) { m_uiCost = (bSad ? m_uiLambdaMotionSAD + iAdd : m_uiLambdaMotionSSE + iAdd); }
+  static UInt    xGetExpGolombNumberOfBits( Int iVal );
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  Void    getMotionCost( Bool bSad, Int iAdd, Bool bIsTransquantBypass ) { m_dCost = (bSad ? m_dLambdaMotionSAD[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING) ?1:0] + iAdd : m_dLambdaMotionSSE[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING)?1:0] + iAdd); }
+#else
+  Void    getMotionCost( Bool bSad, Int iAdd, Bool bIsTransquantBypass ) { m_uiCost = (bSad ? m_uiLambdaMotionSAD[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING) ?1:0] + iAdd : m_uiLambdaMotionSSE[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING)?1:0] + iAdd); }
+#endif
   Void    setPredictor( TComMv& rcMv )
   {
-#if FIX203
     m_mvPredictor = rcMv;
-#else
-    m_puiHorCost = m_puiComponentCost - rcMv.getHor();
-    m_puiVerCost = m_puiComponentCost - rcMv.getVer();
-#endif
   }
   Void    setCostScale( Int iCostScale )    { m_iCostScale = iCostScale; }
-  __inline UInt getCost( Int x, Int y )
+  __inline Distortion getCost( Int x, Int y )
   {
-#if FIX203
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+    return Distortion((m_dCost * getBits(x, y)) / 65536.0);
+#else
     return m_uiCost * getBits(x, y) >> 16;
-#else
-    return (( m_uiCost * (m_puiHorCost[ x * (1<<m_iCostScale) ] + m_puiVerCost[ y * (1<<m_iCostScale) ]) ) >> 16);
 #endif
   }
-  UInt    getCost( UInt b )                 { return ( m_uiCost * b ) >> 16; }
-  UInt    getBits( Int x, Int y )          
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  Distortion getCost( UInt b )                 { return Distortion(( m_dCost * b ) / 65536.0); }
+#else
+  Distortion getCost( UInt b )                 { return ( m_uiCost * b ) >> 16; }
+#endif
+  UInt    getBits( Int x, Int y )
   {
-#if FIX203
-    return xGetComponentBits((x << m_iCostScale) - m_mvPredictor.getHor())
-    +      xGetComponentBits((y << m_iCostScale) - m_mvPredictor.getVer());
-#else
-    return m_puiHorCost[ x * (1<<m_iCostScale)] + m_puiVerCost[ y * (1<<m_iCostScale) ];
-#endif
+    return xGetExpGolombNumberOfBits((x << m_iCostScale) - m_mvPredictor.getHor())
+    +      xGetExpGolombNumberOfBits((y << m_iCostScale) - m_mvPredictor.getVer());
   }
-  
+
 private:
-  
-  static UInt xGetSSE           ( DistParam* pcDtParam );
-  static UInt xGetSSE4          ( DistParam* pcDtParam );
-  static UInt xGetSSE8          ( DistParam* pcDtParam );
-  static UInt xGetSSE16         ( DistParam* pcDtParam );
-  static UInt xGetSSE32         ( DistParam* pcDtParam );
-  static UInt xGetSSE64         ( DistParam* pcDtParam );
-  static UInt xGetSSE16N        ( DistParam* pcDtParam );
+
+  static Distortion xGetSSE           ( DistParam* pcDtParam );
+  static Distortion xGetSSE4          ( DistParam* pcDtParam );
+  static Distortion xGetSSE8          ( DistParam* pcDtParam );
+  static Distortion xGetSSE16         ( DistParam* pcDtParam );
+  static Distortion xGetSSE32         ( DistParam* pcDtParam );
+  static Distortion xGetSSE64         ( DistParam* pcDtParam );
+  static Distortion xGetSSE16N        ( DistParam* pcDtParam );
 #if H_3D_IC || H_3D_INTER_SDC
   static UInt xGetSADic         ( DistParam* pcDtParam );
@@ -278,13 +265,13 @@
   static UInt xGetSAD16Nic      ( DistParam* pcDtParam );
 #endif
-  static UInt xGetSAD           ( DistParam* pcDtParam );
-  static UInt xGetSAD4          ( DistParam* pcDtParam );
-  static UInt xGetSAD8          ( DistParam* pcDtParam );
-  static UInt xGetSAD16         ( DistParam* pcDtParam );
-  static UInt xGetSAD32         ( DistParam* pcDtParam );
-  static UInt xGetSAD64         ( DistParam* pcDtParam );
-  static UInt xGetSAD16N        ( DistParam* pcDtParam );
-  
-#if H_3D_VSO
+
+  static Distortion xGetSAD           ( DistParam* pcDtParam );
+  static Distortion xGetSAD4          ( DistParam* pcDtParam );
+  static Distortion xGetSAD8          ( DistParam* pcDtParam );
+  static Distortion xGetSAD16         ( DistParam* pcDtParam );
+  static Distortion xGetSAD32         ( DistParam* pcDtParam );
+  static Distortion xGetSAD64         ( DistParam* pcDtParam );
+  static Distortion xGetSAD16N        ( DistParam* pcDtParam );
+#if NH_3D_VSO
   static UInt xGetVSD           ( DistParam* pcDtParam );
   static UInt xGetVSD4          ( DistParam* pcDtParam );
@@ -296,5 +283,4 @@
 #endif
 
-#if AMP_SAD
 #if H_3D_IC || H_3D_INTER_SDC
   static UInt xGetSAD12ic       ( DistParam* pcDtParam );
@@ -302,19 +288,18 @@
   static UInt xGetSAD48ic       ( DistParam* pcDtParam );
 #endif
-  static UInt xGetSAD12         ( DistParam* pcDtParam );
-  static UInt xGetSAD24         ( DistParam* pcDtParam );
-  static UInt xGetSAD48         ( DistParam* pcDtParam );
-
-#endif
+
+  static Distortion xGetSAD12         ( DistParam* pcDtParam );
+  static Distortion xGetSAD24         ( DistParam* pcDtParam );
+  static Distortion xGetSAD48         ( DistParam* pcDtParam );
+
 
 #if H_3D_IC || H_3D_INTER_SDC
   static UInt xGetHADsic          ( DistParam* pcDtParam );
 #endif
-  static UInt xGetHADs4         ( DistParam* pcDtParam );
-  static UInt xGetHADs8         ( DistParam* pcDtParam );
-  static UInt xGetHADs          ( DistParam* pcDtParam );
-  static UInt xCalcHADs2x2      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static UInt xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static UInt xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+
+  static Distortion xGetHADs          ( DistParam* pcDtParam );
+  static Distortion xCalcHADs2x2      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static Distortion xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static Distortion xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
 #if H_3D_DBBP
   static UInt xGetMaskedSSE     ( DistParam* pcDtParam );
@@ -322,7 +307,9 @@
   static UInt xGetMaskedVSD     ( DistParam* pcDtParam );
 #endif
-  
+
+
 public:
-  UInt   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText = TEXT_LUMA, DFunc eDFunc = DF_SSE );
+
+  Distortion   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, const ComponentID compID, DFunc eDFunc = DF_SSE );
 
 #if KWU_RC_MADPRED_E0227
@@ -330,7 +317,7 @@
 #endif
 
-#if H_3D_VSO
-  // SAIT_VSO_EST_A0033
-  UInt        getDistPartVSD( TComDataCU* pcCu, UInt uiPartOffset, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bHad, DFunc eDFunc = DF_VSD); 
+#if NH_3D_VSO
+  // SAIT_VSO_EST_A0033
+  UInt        getDistPartVSD( TComDataCU* pcCu, UInt uiPartOffset, Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bHad, DFunc eDFunc = DF_VSD); 
   static UInt getVSDEstimate( Int dDM, Pel* pOrg, Int iOrgStride,  Pel* pVirRec, Pel* pVirOrg, Int iVirStride, Int x, Int y );
 
@@ -365,5 +352,7 @@
   Void    setRenModel       ( TRenModel* pcRenModel ) { m_pcRenModel = pcRenModel; }
   TRenModel* getRenModel    ( )                       { return m_pcRenModel; }
-  Void    setRenModelData   ( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piData, Int iStride, Int iBlkWidth, Int iBlkHeight );
+  Void    setRenModelData   ( const TComDataCU* pcCU, UInt uiAbsPartIndex, const TComYuv* pcYuv, const TComTURecurse* tuRecurseWithPU );
+  Void    setRenModelData   ( const TComDataCU* pcCU, UInt uiAbsPartIndex, const Pel* piData, Int iStride, Int iBlkWidth, Int iBlkHeight );
+
   Void    setLambdaVSO      ( Double dLambda );
   Void    setFrameLambdaVSO ( Double dLambda ) { m_dFrameLambdaVSO = dLambda; };
@@ -384,6 +373,6 @@
   Double  getLambdaVSO ()       { return m_dLambdaVSO; }
 
-  Dist   getDistPartVSO( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD );
-  Double calcRdCostVSO ( UInt   uiBits, Dist   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Dist    getDistPartVSO( TComDataCU* pcCU, UInt uiAbsPartIndex, Int bitdDepth, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD );
+  Double  calcRdCostVSO ( UInt   uiBits, Dist   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
 
   // SAIT_VSO_EST_A0033
@@ -409,5 +398,6 @@
   Dist xGetDistVSOMode4( Int iStartPosX, Int iStartPosY, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD );
 
-#endif // H_3D_VSO
+#endif // NH_3D_VSO
+
 
 };// END CLASS DEFINITION TComRdCost
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -41,22 +41,8 @@
 #include "TComRdCostWeightPrediction.h"
 
-Int   TComRdCostWeightPrediction::m_w0        = 0;
-Int   TComRdCostWeightPrediction::m_w1        = 0;
-Int   TComRdCostWeightPrediction::m_shift     = 0;
-Int   TComRdCostWeightPrediction::m_offset    = 0;
-Int   TComRdCostWeightPrediction::m_round     = 0;
-Bool  TComRdCostWeightPrediction::m_xSetDone  = false;
-
-// ====================================================================================================================
-// Distortion functions
-// ====================================================================================================================
-
-TComRdCostWeightPrediction::TComRdCostWeightPrediction()
-{
-}
-
-TComRdCostWeightPrediction::~TComRdCostWeightPrediction()
-{
-}
+static Distortion xCalcHADs2x2w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+static Distortion xCalcHADs4x4w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+static Distortion xCalcHADs8x8w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+
 
 // --------------------------------------------------------------------------------------------------------------------
@@ -65,32 +51,32 @@
 /** get weighted SAD cost
  * \param pcDtParam
- * \returns UInt
+ * \returns Distortion
  */
-UInt TComRdCostWeightPrediction::xGetSADw( DistParam* pcDtParam )
-{
-  Pel  pred;
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iCols   = pcDtParam->iCols;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
-
-  UInt            uiComp    = pcDtParam->uiComp;
-  assert(uiComp<3);
-  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
-  Int   w0      = wpCur->w,
-        offset  = wpCur->offset,
-        shift   = wpCur->shift,
-        round   = wpCur->round;
-  
-  UInt uiSum = 0;
-  
-  for( ; iRows != 0; iRows-- )
+Distortion TComRdCostWeightPrediction::xGetSADw( DistParam* pcDtParam )
+{
+  const Pel            *piOrg      = pcDtParam->pOrg;
+  const Pel            *piCur      = pcDtParam->pCur;
+  const Int             iCols      = pcDtParam->iCols;
+  const Int             iStrideCur = pcDtParam->iStrideCur;
+  const Int             iStrideOrg = pcDtParam->iStrideOrg;
+  const ComponentID     compID     = pcDtParam->compIdx;
+
+  assert(compID<MAX_NUM_COMPONENT);
+
+  const WPScalingParam &wpCur      = pcDtParam->wpCur[compID];
+
+  const Int             w0         = wpCur.w;
+  const Int             offset     = wpCur.offset;
+  const Int             shift      = wpCur.shift;
+  const Int             round      = wpCur.round;
+
+  Distortion uiSum = 0;
+
+  for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
   {
     for (Int n = 0; n < iCols; n++ )
     {
-      pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
-      
+      const Pel pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+
       uiSum += abs( piOrg[n] - pred );
     }
@@ -98,9 +84,10 @@
     piCur += iStrideCur;
   }
-  
-  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  pcDtParam->compIdx = MAX_NUM_COMPONENT;  // reset for DEBUG (assert test)
 
   return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
 }
+
 
 // --------------------------------------------------------------------------------------------------------------------
@@ -109,74 +96,69 @@
 /** get weighted SSD cost
  * \param pcDtParam
- * \returns UInt
+ * \returns Distortion
  */
-UInt TComRdCostWeightPrediction::xGetSSEw( DistParam* pcDtParam )
-{
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Pel  pred;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iCols   = pcDtParam->iCols;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-
-  assert( pcDtParam->iSubShift == 0 );
-
-  UInt            uiComp    = pcDtParam->uiComp;
-  assert(uiComp<3);
-  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
-  Int   w0      = wpCur->w,
-        offset  = wpCur->offset,
-        shift   = wpCur->shift,
-        round   = wpCur->round;
- 
-  UInt uiSum = 0;
-  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
-  
-  Int iTemp;
-  
-  for( ; iRows != 0; iRows-- )
+Distortion TComRdCostWeightPrediction::xGetSSEw( DistParam* pcDtParam )
+{
+  const Pel            *piOrg           = pcDtParam->pOrg;
+  const Pel            *piCur           = pcDtParam->pCur;
+  const Int             iCols           = pcDtParam->iCols;
+  const Int             iStrideOrg      = pcDtParam->iStrideOrg;
+  const Int             iStrideCur      = pcDtParam->iStrideCur;
+  const ComponentID     compIdx         = pcDtParam->compIdx;
+
+  assert( pcDtParam->iSubShift == 0 ); // NOTE: what is this protecting?
+
+  assert(compIdx<MAX_NUM_COMPONENT);
+  const WPScalingParam &wpCur           = pcDtParam->wpCur[compIdx];
+  const Int             w0              = wpCur.w;
+  const Int             offset          = wpCur.offset;
+  const Int             shift           = wpCur.shift;
+  const Int             round           = wpCur.round;
+  const UInt            distortionShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Distortion sum = 0;
+
+  for(Int iRows = pcDtParam->iRows ; iRows != 0; iRows-- )
   {
     for (Int n = 0; n < iCols; n++ )
     {
-      pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
-
-      iTemp = piOrg[n  ] - pred;
-      uiSum += ( iTemp * iTemp ) >> uiShift;
+      const Pel pred     = ( (w0*piCur[n] + round) >> shift ) + offset ;
+      const Pel residual = piOrg[n] - pred;
+      sum += ( Distortion(residual) * Distortion(residual) ) >> distortionShift;
     }
     piOrg += iStrideOrg;
     piCur += iStrideCur;
   }
-  
-  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
-
-  return ( uiSum );
-}
+
+  pcDtParam->compIdx = MAX_NUM_COMPONENT; // reset for DEBUG (assert test)
+
+  return sum;
+}
+
 
 // --------------------------------------------------------------------------------------------------------------------
 // HADAMARD with step (used in fractional search)
 // --------------------------------------------------------------------------------------------------------------------
-/** get weighted Hadamard cost for 2x2 block
- * \param *piOrg
- * \param *piCur
- * \param iStrideOrg
- * \param iStrideCur
- * \param iStep
- * \returns UInt
- */
-UInt TComRdCostWeightPrediction::xCalcHADs2x2w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int satd = 0, diff[4], m[4];
-  
-  assert( m_xSetDone );
+//! get weighted Hadamard cost for 2x2 block
+Distortion xCalcHADs2x2w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  const Int round  = wpCur.round;
+  const Int shift  = wpCur.shift;
+  const Int offset = wpCur.offset;
+  const Int w0     = wpCur.w;
+
+  Distortion satd  = 0;
+  TCoeff     diff[4];
+  TCoeff     m[4];
+
   Pel   pred;
 
-  pred    = ( (m_w0*piCur[0*iStep             ] + m_round) >> m_shift ) + m_offset ;
+  pred    = ( (w0*piCur[0*iStep             ] + round) >> shift ) + offset ;
   diff[0] = piOrg[0             ] - pred;
-  pred    = ( (m_w0*piCur[1*iStep             ] + m_round) >> m_shift ) + m_offset ;
+  pred    = ( (w0*piCur[1*iStep             ] + round) >> shift ) + offset ;
   diff[1] = piOrg[1             ] - pred;
-  pred    = ( (m_w0*piCur[0*iStep + iStrideCur] + m_round) >> m_shift ) + m_offset ;
+  pred    = ( (w0*piCur[0*iStep + iStrideCur] + round) >> shift ) + offset ;
   diff[2] = piOrg[iStrideOrg    ] - pred;
-  pred    = ( (m_w0*piCur[1*iStep + iStrideCur] + m_round) >> m_shift ) + m_offset ;
+  pred    = ( (w0*piCur[1*iStep + iStrideCur] + round) >> shift ) + offset ;
   diff[3] = piOrg[iStrideOrg + 1] - pred;
 
@@ -185,37 +167,38 @@
   m[2] = diff[0] - diff[2];
   m[3] = diff[1] - diff[3];
-  
+
   satd += abs(m[0] + m[1]);
   satd += abs(m[0] - m[1]);
   satd += abs(m[2] + m[3]);
   satd += abs(m[2] - m[3]);
-  
+
   return satd;
 }
 
-/** get weighted Hadamard cost for 4x4 block
- * \param *piOrg
- * \param *piCur
- * \param iStrideOrg
- * \param iStrideCur
- * \param iStep
- * \returns UInt
- */
-UInt TComRdCostWeightPrediction::xCalcHADs4x4w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int k, satd = 0, diff[16], m[16], d[16];
-  
-  assert( m_xSetDone );
-  Pel   pred;
-
-  for( k = 0; k < 16; k+=4 )
-  {
-    pred      = ( (m_w0*piCur[0*iStep] + m_round) >> m_shift ) + m_offset ;
+
+//! get weighted Hadamard cost for 4x4 block
+Distortion xCalcHADs4x4w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  const Int round  = wpCur.round;
+  const Int shift  = wpCur.shift;
+  const Int offset = wpCur.offset;
+  const Int w0     = wpCur.w;
+
+  Distortion satd = 0;
+  TCoeff     diff[16];
+  TCoeff     m[16];
+  TCoeff     d[16];
+
+
+  for(Int k = 0; k < 16; k+=4 )
+  {
+    Pel pred;
+    pred      = ( (w0*piCur[0*iStep] + round) >> shift ) + offset ;
     diff[k+0] = piOrg[0] - pred;
-    pred      = ( (m_w0*piCur[1*iStep] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[1*iStep] + round) >> shift ) + offset ;
     diff[k+1] = piOrg[1] - pred;
-    pred      = ( (m_w0*piCur[2*iStep] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[2*iStep] + round) >> shift ) + offset ;
     diff[k+2] = piOrg[2] - pred;
-    pred      = ( (m_w0*piCur[3*iStep] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[3*iStep] + round) >> shift ) + offset ;
     diff[k+3] = piOrg[3] - pred;
 
@@ -223,5 +206,5 @@
     piOrg += iStrideOrg;
   }
-  
+
   /*===== hadamard transform =====*/
   m[ 0] = diff[ 0] + diff[12];
@@ -241,5 +224,5 @@
   m[14] = diff[ 2] - diff[14];
   m[15] = diff[ 3] - diff[15];
-  
+
   d[ 0] = m[ 0] + m[ 4];
   d[ 1] = m[ 1] + m[ 5];
@@ -258,5 +241,5 @@
   d[14] = m[14] - m[10];
   d[15] = m[15] - m[11];
-  
+
   m[ 0] = d[ 0] + d[ 3];
   m[ 1] = d[ 1] + d[ 2];
@@ -275,5 +258,5 @@
   m[14] = d[13] - d[14];
   m[15] = d[12] - d[15];
-  
+
   d[ 0] = m[ 0] + m[ 1];
   d[ 1] = m[ 0] - m[ 1];
@@ -292,26 +275,20 @@
   d[14] = m[14] + m[15];
   d[15] = m[15] - m[14];
-  
-  for (k=0; k<16; ++k)
+
+  for (Int k=0; k<16; ++k)
   {
     satd += abs(d[k]);
   }
   satd = ((satd+1)>>1);
-  
+
   return satd;
 }
 
-/** get weighted Hadamard cost for 8x8 block
- * \param *piOrg
- * \param *piCur
- * \param iStrideOrg
- * \param iStrideCur
- * \param iStep
- * \returns UInt
- */
-UInt TComRdCostWeightPrediction::xCalcHADs8x8w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
-  Int k, i, j, jj, sad=0;
-  Int diff[64], m1[8][8], m2[8][8], m3[8][8];
+
+//! get weighted Hadamard cost for 8x8 block
+Distortion xCalcHADs8x8w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Distortion sad=0;
+  TCoeff diff[64], m1[8][8], m2[8][8], m3[8][8];
   Int iStep2 = iStep<<1;
   Int iStep3 = iStep2 + iStep;
@@ -320,35 +297,38 @@
   Int iStep6 = iStep5 + iStep;
   Int iStep7 = iStep6 + iStep;
-  
-  assert( m_xSetDone );
+  const Int round  = wpCur.round;
+  const Int shift  = wpCur.shift;
+  const Int offset = wpCur.offset;
+  const Int w0     = wpCur.w;
+
   Pel   pred;
 
-  for( k = 0; k < 64; k+=8 )
-  {
-    pred      = ( (m_w0*piCur[     0] + m_round) >> m_shift ) + m_offset ;
+  for(Int k = 0; k < 64; k+=8 )
+  {
+    pred      = ( (w0*piCur[     0] + round) >> shift ) + offset ;
     diff[k+0] = piOrg[0] - pred;
-    pred      = ( (m_w0*piCur[iStep ] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[iStep ] + round) >> shift ) + offset ;
     diff[k+1] = piOrg[1] - pred;
-    pred      = ( (m_w0*piCur[iStep2] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[iStep2] + round) >> shift ) + offset ;
     diff[k+2] = piOrg[2] - pred;
-    pred      = ( (m_w0*piCur[iStep3] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[iStep3] + round) >> shift ) + offset ;
     diff[k+3] = piOrg[3] - pred;
-    pred      = ( (m_w0*piCur[iStep4] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[iStep4] + round) >> shift ) + offset ;
     diff[k+4] = piOrg[4] - pred;
-    pred      = ( (m_w0*piCur[iStep5] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[iStep5] + round) >> shift ) + offset ;
     diff[k+5] = piOrg[5] - pred;
-    pred      = ( (m_w0*piCur[iStep6] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[iStep6] + round) >> shift ) + offset ;
     diff[k+6] = piOrg[6] - pred;
-    pred      = ( (m_w0*piCur[iStep7] + m_round) >> m_shift ) + m_offset ;
+    pred      = ( (w0*piCur[iStep7] + round) >> shift ) + offset ;
     diff[k+7] = piOrg[7] - pred;
-    
+
     piCur += iStrideCur;
     piOrg += iStrideOrg;
   }
-  
+
   //horizontal
-  for (j=0; j < 8; j++)
-  {
-    jj = j << 3;
+  for (Int j=0; j < 8; j++)
+  {
+    const Int jj = j << 3;
     m2[j][0] = diff[jj  ] + diff[jj+4];
     m2[j][1] = diff[jj+1] + diff[jj+5];
@@ -359,5 +339,5 @@
     m2[j][6] = diff[jj+2] - diff[jj+6];
     m2[j][7] = diff[jj+3] - diff[jj+7];
-    
+
     m1[j][0] = m2[j][0] + m2[j][2];
     m1[j][1] = m2[j][1] + m2[j][3];
@@ -368,5 +348,5 @@
     m1[j][6] = m2[j][4] - m2[j][6];
     m1[j][7] = m2[j][5] - m2[j][7];
-    
+
     m2[j][0] = m1[j][0] + m1[j][1];
     m2[j][1] = m1[j][0] - m1[j][1];
@@ -378,7 +358,7 @@
     m2[j][7] = m1[j][6] - m1[j][7];
   }
-  
+
   //vertical
-  for (i=0; i < 8; i++)
+  for (Int i=0; i < 8; i++)
   {
     m3[0][i] = m2[0][i] + m2[4][i];
@@ -390,5 +370,5 @@
     m3[6][i] = m2[2][i] - m2[6][i];
     m3[7][i] = m2[3][i] - m2[7][i];
-    
+
     m1[0][i] = m3[0][i] + m3[2][i];
     m1[1][i] = m3[1][i] + m3[3][i];
@@ -399,5 +379,5 @@
     m1[6][i] = m3[4][i] - m3[6][i];
     m1[7][i] = m3[5][i] - m3[7][i];
-    
+
     m2[0][i] = m1[0][i] + m1[1][i];
     m2[1][i] = m1[0][i] - m1[1][i];
@@ -409,115 +389,44 @@
     m2[7][i] = m1[6][i] - m1[7][i];
   }
-  
-  for (j=0; j < 8; j++)
-  {
-    for (i=0; i < 8; i++)
+
+  for (Int j=0; j < 8; j++)
+  {
+    for (Int i=0; i < 8; i++)
     {
       sad += (abs(m2[j][i]));
     }
   }
-  
+
   sad=((sad+2)>>2);
-  
+
   return sad;
 }
 
-/** get weighted Hadamard cost
- * \param *pcDtParam
- * \returns UInt
- */
-UInt TComRdCostWeightPrediction::xGetHADs4w( DistParam* pcDtParam )
-{
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
-  Int  iStep  = pcDtParam->iStep;
-  Int  y;
-  Int  iOffsetOrg = iStrideOrg<<2;
-  Int  iOffsetCur = iStrideCur<<2;
-  
-  UInt uiSum = 0;
-  
-  for ( y=0; y<iRows; y+= 4 )
-  {
-    uiSum += xCalcHADs4x4w( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
-    piOrg += iOffsetOrg;
-    piCur += iOffsetCur;
-  }
-  
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-/** get weighted Hadamard cost
- * \param *pcDtParam
- * \returns UInt
- */
-UInt TComRdCostWeightPrediction::xGetHADs8w( DistParam* pcDtParam )
-{
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
-  Int  iStep  = pcDtParam->iStep;
-  Int  y;
-  
-  UInt uiSum = 0;
-  
-  if ( iRows == 4 )
-  {
-    uiSum += xCalcHADs4x4w( piOrg+0, piCur        , iStrideOrg, iStrideCur, iStep );
-    uiSum += xCalcHADs4x4w( piOrg+4, piCur+4*iStep, iStrideOrg, iStrideCur, iStep );
-  }
-  else
-  {
-    Int  iOffsetOrg = iStrideOrg<<3;
-    Int  iOffsetCur = iStrideCur<<3;
-    for ( y=0; y<iRows; y+= 8 )
-    {
-      uiSum += xCalcHADs8x8w( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
-      piOrg += iOffsetOrg;
-      piCur += iOffsetCur;
-    }
-  }
-  
-  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
-}
-
-/** get weighted Hadamard cost
- * \param *pcDtParam
- * \returns UInt
- */
-UInt TComRdCostWeightPrediction::xGetHADsw( DistParam* pcDtParam )
-{
-  Pel* piOrg   = pcDtParam->pOrg;
-  Pel* piCur   = pcDtParam->pCur;
-  Int  iRows   = pcDtParam->iRows;
-  Int  iCols   = pcDtParam->iCols;
-  Int  iStrideCur = pcDtParam->iStrideCur;
-  Int  iStrideOrg = pcDtParam->iStrideOrg;
-  Int  iStep  = pcDtParam->iStep;
-  
-  Int  x, y;
-  
-  UInt            uiComp    = pcDtParam->uiComp;
-  assert(uiComp<3);
-  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
-
-  xSetWPscale(wpCur->w, 0, wpCur->shift, wpCur->offset, wpCur->round);
-
-  UInt uiSum = 0;
-  
+
+//! get weighted Hadamard cost
+Distortion TComRdCostWeightPrediction::xGetHADsw( DistParam* pcDtParam )
+{
+  const Pel        *piOrg      = pcDtParam->pOrg;
+  const Pel        *piCur      = pcDtParam->pCur;
+  const Int         iRows      = pcDtParam->iRows;
+  const Int         iCols      = pcDtParam->iCols;
+  const Int         iStrideCur = pcDtParam->iStrideCur;
+  const Int         iStrideOrg = pcDtParam->iStrideOrg;
+  const Int         iStep      = pcDtParam->iStep;
+  const ComponentID compIdx    = pcDtParam->compIdx;
+  assert(compIdx<MAX_NUM_COMPONENT);
+  const WPScalingParam  wpCur    = pcDtParam->wpCur[compIdx];
+
+  Distortion uiSum = 0;
+
   if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
   {
-    Int  iOffsetOrg = iStrideOrg<<3;
-    Int  iOffsetCur = iStrideCur<<3;
-    for ( y=0; y<iRows; y+= 8 )
-    {
-      for ( x=0; x<iCols; x+= 8 )
+    const Int iOffsetOrg = iStrideOrg<<3;
+    const Int iOffsetCur = iStrideCur<<3;
+    for (Int y=0; y<iRows; y+= 8 )
+    {
+      for (Int x=0; x<iCols; x+= 8 )
       {
-        uiSum += xCalcHADs8x8w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs8x8w( wpCur, &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
       }
       piOrg += iOffsetOrg;
@@ -527,12 +436,12 @@
   else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
   {
-    Int  iOffsetOrg = iStrideOrg<<2;
-    Int  iOffsetCur = iStrideCur<<2;
-    
-    for ( y=0; y<iRows; y+= 4 )
-    {
-      for ( x=0; x<iCols; x+= 4 )
+    const Int iOffsetOrg = iStrideOrg<<2;
+    const Int iOffsetCur = iStrideCur<<2;
+
+    for (Int y=0; y<iRows; y+= 4 )
+    {
+      for (Int x=0; x<iCols; x+= 4 )
       {
-        uiSum += xCalcHADs4x4w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs4x4w( wpCur, &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
       }
       piOrg += iOffsetOrg;
@@ -542,9 +451,9 @@
   else
   {
-    for ( y=0; y<iRows; y+=2 )
-    {
-      for ( x=0; x<iCols; x+=2 )
+    for (Int y=0; y<iRows; y+=2 )
+    {
+      for (Int x=0; x<iCols; x+=2 )
       {
-        uiSum += xCalcHADs2x2w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs2x2w( wpCur, &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
       }
       piOrg += iStrideOrg;
@@ -552,6 +461,4 @@
     }
   }
-  
-  m_xSetDone  = false;
 
   return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -33,5 +33,5 @@
 
 /** \file     TComRdCostWeightPrediction.h
-    \brief    RD cost computation classes (header)
+    \brief    RD cost computation namespace (header)
 */
 
@@ -41,8 +41,4 @@
 
 #include "CommonDef.h"
-#include "TComPattern.h"
-#include "TComMv.h"
-#include "TComRdCost.h"
-#include "TComSlice.h"
 
 class DistParam;
@@ -50,46 +46,14 @@
 
 // ====================================================================================================================
-// Class definition
+// Namespace definition
 // ====================================================================================================================
 
-/// RD cost computation class, with Weighted Prediction
-class TComRdCostWeightPrediction
+/// RD cost computation namespace, with Weighted Prediction
+namespace TComRdCostWeightPrediction
 {
-private:
-  static  Int   m_w0, m_w1; // current wp scaling values
-  static  Int   m_shift;
-  static  Int   m_offset;
-  static  Int   m_round;
-  static  Bool  m_xSetDone;
-
-public:
-  TComRdCostWeightPrediction();
-  virtual ~TComRdCostWeightPrediction();
-  
-protected:
-    
-  static inline Void  xSetWPscale(Int w0, Int w1, Int shift, Int offset, Int round);
-
-  static UInt xGetSSEw          ( DistParam* pcDtParam );
-  static UInt xGetSADw          ( DistParam* pcDtParam );
-  static UInt xGetHADs4w        ( DistParam* pcDtParam );
-  static UInt xGetHADs8w        ( DistParam* pcDtParam );
-  static UInt xGetHADsw         ( DistParam* pcDtParam );
-  static UInt xCalcHADs2x2w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static UInt xCalcHADs4x4w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static UInt xCalcHADs8x8w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  
-};// END CLASS DEFINITION TComRdCostWeightPrediction
-
-inline Void  TComRdCostWeightPrediction::xSetWPscale(Int w0, Int w1, Int shift, Int offset, Int round)
-{
-  m_w0        = w0;
-  m_w1        = w1;
-  m_shift     = shift;
-  m_offset    = offset;
-  m_round     = round;
-
-  m_xSetDone  = true;
-}
+  Distortion xGetSSEw ( DistParam* pcDtParam );
+  Distortion xGetSADw ( DistParam* pcDtParam );
+  Distortion xGetHADsw( DistParam* pcDtParam );
+}// END NAMESPACE DEFINITION TComRdCostWeightPrediction
 
 #endif // __TCOMRDCOSTWEIGHTPREDICTION__
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRectangle.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRectangle.h	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRectangle.h	(revision 1200)
@@ -0,0 +1,50 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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 __TCOMRECTANGLE__
+#define __TCOMRECTANGLE__
+
+
+struct TComRectangle
+{
+  UInt width;
+  UInt height;
+  UInt x0;
+  UInt y0;
+};
+
+
+
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRom.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRom.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -31,25 +31,134 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
-
 /** \file     TComRom.cpp
     \brief    global variables & functions
 */
-
 #include "TComRom.h"
 #include <memory.h>
 #include <stdlib.h>
 #include <stdio.h>
+#include <iomanip>
+#include <assert.h>
+#include "TComDataCU.h"
+#include "Debug.h"
 // ====================================================================================================================
 // Initialize / destroy functions
 // ====================================================================================================================
-
 //! \ingroup TLibCommon
 //! \{
-
+const Char* nalUnitTypeToString(NalUnitType type)
+{
+  switch (type)
+  {
+  case NAL_UNIT_CODED_SLICE_TRAIL_R:    return "TRAIL_R";
+  case NAL_UNIT_CODED_SLICE_TRAIL_N:    return "TRAIL_N";
+  case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
+  case NAL_UNIT_CODED_SLICE_TSA_N:      return "TSA_N";
+  case NAL_UNIT_CODED_SLICE_STSA_R:     return "STSA_R";
+  case NAL_UNIT_CODED_SLICE_STSA_N:     return "STSA_N";
+  case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
+  case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
+  case NAL_UNIT_CODED_SLICE_BLA_N_LP:   return "BLA_N_LP";
+  case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
+  case NAL_UNIT_CODED_SLICE_IDR_N_LP:   return "IDR_N_LP";
+  case NAL_UNIT_CODED_SLICE_CRA:        return "CRA";
+  case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
+  case NAL_UNIT_CODED_SLICE_RADL_N:     return "RADL_N";
+  case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
+  case NAL_UNIT_CODED_SLICE_RASL_N:     return "RASL_N";
+  case NAL_UNIT_VPS:                    return "VPS";
+  case NAL_UNIT_SPS:                    return "SPS";
+  case NAL_UNIT_PPS:                    return "PPS";
+  case NAL_UNIT_ACCESS_UNIT_DELIMITER:  return "AUD";
+  case NAL_UNIT_EOS:                    return "EOS";
+  case NAL_UNIT_EOB:                    return "EOB";
+  case NAL_UNIT_FILLER_DATA:            return "FILLER";
+  case NAL_UNIT_PREFIX_SEI:             return "Prefix SEI";
+  case NAL_UNIT_SUFFIX_SEI:             return "Suffix SEI";
+  default:                              return "UNK";
+  }
+}
+class ScanGenerator
+{
+private:
+  UInt m_line, m_column;
+  const UInt m_blockWidth, m_blockHeight;
+  const UInt m_stride;
+  const COEFF_SCAN_TYPE m_scanType;
+public:
+  ScanGenerator(UInt blockWidth, UInt blockHeight, UInt stride, COEFF_SCAN_TYPE scanType)
+    : m_line(0), m_column(0), m_blockWidth(blockWidth), m_blockHeight(blockHeight), m_stride(stride), m_scanType(scanType)
+  { }
+  UInt GetCurrentX() const { return m_column; }
+  UInt GetCurrentY() const { return m_line; }
+  UInt GetNextIndex(UInt blockOffsetX, UInt blockOffsetY)
+  {
+    Int rtn=((m_line + blockOffsetY) * m_stride) + m_column + blockOffsetX;
+    //advance line and column to the next position
+    switch (m_scanType)
+    {
+      //------------------------------------------------
+      case SCAN_DIAG:
+        {
+          if ((m_column == (m_blockWidth - 1)) || (m_line == 0)) //if we reach the end of a rank, go diagonally down to the next one
+          {
+            m_line   += m_column + 1;
+            m_column  = 0;
+            if (m_line >= m_blockHeight) //if that takes us outside the block, adjust so that we are back on the bottom row
+            {
+              m_column += m_line - (m_blockHeight - 1);
+              m_line    = m_blockHeight - 1;
+            }
+          }
+          else
+          {
+            m_column++;
+            m_line--;
+          }
+        }
+        break;
+      //------------------------------------------------
+      case SCAN_HOR:
+        {
+          if (m_column == (m_blockWidth - 1))
+          {
+            m_line++;
+            m_column = 0;
+          }
+          else
+          {
+            m_column++;
+          }
+        }
+        break;
+      //------------------------------------------------
+      case SCAN_VER:
+        {
+          if (m_line == (m_blockHeight - 1))
+          {
+            m_column++;
+            m_line = 0;
+          }
+          else
+          {
+            m_line++;
+          }
+        }
+        break;
+      //------------------------------------------------
+      default:
+        {
+          std::cerr << "ERROR: Unknown scan type \"" << m_scanType << "\"in ScanGenerator::GetNextIndex" << std::endl;
+          exit(1);
+        }
+        break;
+    }
+    return rtn;
+  }
+};
 // initialize ROM variables
 Void initROM()
 {
   Int i, c;
-  
   // g_aucConvertToBit[ x ]: log2(x/4), if x=4 -> 0, x=8 -> 1, x=16 -> 2, ...
   ::memset( g_aucConvertToBit,   -1, sizeof( g_aucConvertToBit ) );
@@ -60,17 +169,56 @@
     c++;
   }
-  
-  c=2;
-  for ( i=0; i<MAX_CU_DEPTH; i++ )
-  {
-    g_auiSigLastScan[0][i] = new UInt[ c*c ];
-    g_auiSigLastScan[1][i] = new UInt[ c*c ];
-    g_auiSigLastScan[2][i] = new UInt[ c*c ];
-    initSigLastScan( g_auiSigLastScan[0][i], g_auiSigLastScan[1][i], g_auiSigLastScan[2][i], c, c);
-
-    c <<= 1;
-  }  
-
-#if H_MV
+  // initialise scan orders
+  for(UInt log2BlockHeight = 0; log2BlockHeight < MAX_CU_DEPTH; log2BlockHeight++)
+  {
+    for(UInt log2BlockWidth = 0; log2BlockWidth < MAX_CU_DEPTH; log2BlockWidth++)
+    {
+      const UInt blockWidth  = 1 << log2BlockWidth;
+      const UInt blockHeight = 1 << log2BlockHeight;
+      const UInt totalValues = blockWidth * blockHeight;
+      //--------------------------------------------------------------------------------------------------
+      //non-grouped scan orders
+      for (UInt scanTypeIndex = 0; scanTypeIndex < SCAN_NUMBER_OF_TYPES; scanTypeIndex++)
+      {
+        const COEFF_SCAN_TYPE scanType = COEFF_SCAN_TYPE(scanTypeIndex);
+        g_scanOrder[SCAN_UNGROUPED][scanType][log2BlockWidth][log2BlockHeight] = new UInt[totalValues];
+        ScanGenerator fullBlockScan(blockWidth, blockHeight, blockWidth, scanType);
+        for (UInt scanPosition = 0; scanPosition < totalValues; scanPosition++)
+        {
+          g_scanOrder[SCAN_UNGROUPED][scanType][log2BlockWidth][log2BlockHeight][scanPosition] = fullBlockScan.GetNextIndex(0, 0);
+        }
+      }
+      //--------------------------------------------------------------------------------------------------
+      //grouped scan orders
+      const UInt  groupWidth           = 1           << MLS_CG_LOG2_WIDTH;
+      const UInt  groupHeight          = 1           << MLS_CG_LOG2_HEIGHT;
+      const UInt  widthInGroups        = blockWidth  >> MLS_CG_LOG2_WIDTH;
+      const UInt  heightInGroups       = blockHeight >> MLS_CG_LOG2_HEIGHT;
+      const UInt  groupSize            = groupWidth    * groupHeight;
+      const UInt  totalGroups          = widthInGroups * heightInGroups;
+      for (UInt scanTypeIndex = 0; scanTypeIndex < SCAN_NUMBER_OF_TYPES; scanTypeIndex++)
+      {
+        const COEFF_SCAN_TYPE scanType = COEFF_SCAN_TYPE(scanTypeIndex);
+        g_scanOrder[SCAN_GROUPED_4x4][scanType][log2BlockWidth][log2BlockHeight] = new UInt[totalValues];
+        ScanGenerator fullBlockScan(widthInGroups, heightInGroups, groupWidth, scanType);
+        for (UInt groupIndex = 0; groupIndex < totalGroups; groupIndex++)
+        {
+          const UInt groupPositionY  = fullBlockScan.GetCurrentY();
+          const UInt groupPositionX  = fullBlockScan.GetCurrentX();
+          const UInt groupOffsetX    = groupPositionX * groupWidth;
+          const UInt groupOffsetY    = groupPositionY * groupHeight;
+          const UInt groupOffsetScan = groupIndex     * groupSize;
+          ScanGenerator groupScan(groupWidth, groupHeight, blockWidth, scanType);
+          for (UInt scanPosition = 0; scanPosition < groupSize; scanPosition++)
+          {
+            g_scanOrder[SCAN_GROUPED_4x4][scanType][log2BlockWidth][log2BlockHeight][groupOffsetScan + scanPosition] = groupScan.GetNextIndex(groupOffsetX, groupOffsetY);
+          }
+          fullBlockScan.GetNextIndex(0,0);
+        }
+      }
+      //--------------------------------------------------------------------------------------------------
+    }
+  }
+#if NH_MV
 #if H_MV_HLS_PTL_LIMITS 
  g_generalTierAndLevelLimits[ Level::LEVEL1   ] = TComGeneralTierAndLevelLimits(    36864,     350,  INT_MIN,   16,   1,   1 );
@@ -89,16 +237,20 @@
 #endif
 #endif
-
-}
-
+}
 Void destroyROM()
 {
-  for (Int i=0; i<MAX_CU_DEPTH; i++ )
-  {
-    delete[] g_auiSigLastScan[0][i];
-    delete[] g_auiSigLastScan[1][i];
-    delete[] g_auiSigLastScan[2][i];
-  }
-
+  for(UInt groupTypeIndex = 0; groupTypeIndex < SCAN_NUMBER_OF_GROUP_TYPES; groupTypeIndex++)
+  {
+    for (UInt scanOrderIndex = 0; scanOrderIndex < SCAN_NUMBER_OF_TYPES; scanOrderIndex++)
+    {
+      for (UInt log2BlockWidth = 0; log2BlockWidth < MAX_CU_DEPTH; log2BlockWidth++)
+      {
+        for (UInt log2BlockHeight = 0; log2BlockHeight < MAX_CU_DEPTH; log2BlockHeight++)
+        {
+          delete [] g_scanOrder[groupTypeIndex][scanOrderIndex][log2BlockWidth][log2BlockHeight];
+        }
+      }
+    }
+  }
 #if H_3D_DIM_DMM
   if( !g_dmmWedgeLists.empty() ) 
@@ -118,5 +270,4 @@
     g_dmmWedgeRefLists.clear();
   }
-
   if( !g_dmmWedgeNodeLists.empty() )
   {
@@ -129,24 +280,15 @@
 #endif
 }
-
 // ====================================================================================================================
 // Data structure related table & variable
 // ====================================================================================================================
-
-UInt g_uiMaxCUWidth  = MAX_CU_SIZE;
-UInt g_uiMaxCUHeight = MAX_CU_SIZE;
-UInt g_uiMaxCUDepth  = MAX_CU_DEPTH;
-UInt g_uiAddCUDepth  = 0;
-UInt g_auiZscanToRaster [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
-UInt g_auiRasterToZscan [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
-UInt g_auiRasterToPelX  [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
-UInt g_auiRasterToPelY  [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
-
-UInt g_auiPUOffset[8] = { 0, 8, 4, 4, 2, 10, 1, 5};
-
+UInt g_auiZscanToRaster [ MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH ] = { 0, };
+UInt g_auiRasterToZscan [ MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH ] = { 0, };
+UInt g_auiRasterToPelX  [ MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH ] = { 0, };
+UInt g_auiRasterToPelY  [ MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH ] = { 0, };
+const UInt g_auiPUOffset[NUMBER_OF_PART_SIZES] = { 0, 8, 4, 4, 2, 10, 1, 5};
 Void initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx )
 {
   Int iStride = 1 << ( iMaxDepth - 1 );
-  
   if ( iDepth == iMaxDepth )
   {
@@ -163,13 +305,10 @@
   }
 }
-
 Void initRasterToZscan ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth )
 {
   UInt  uiMinCUWidth  = uiMaxCUWidth  >> ( uiMaxDepth - 1 );
   UInt  uiMinCUHeight = uiMaxCUHeight >> ( uiMaxDepth - 1 );
-  
   UInt  uiNumPartInWidth  = (UInt)uiMaxCUWidth  / uiMinCUWidth;
   UInt  uiNumPartInHeight = (UInt)uiMaxCUHeight / uiMinCUHeight;
-  
   for ( UInt i = 0; i < uiNumPartInWidth*uiNumPartInHeight; i++ )
   {
@@ -177,18 +316,13 @@
   }
 }
-
 Void initRasterToPelXY ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth )
 {
   UInt    i;
-  
   UInt* uiTempX = &g_auiRasterToPelX[0];
   UInt* uiTempY = &g_auiRasterToPelY[0];
-  
   UInt  uiMinCUWidth  = uiMaxCUWidth  >> ( uiMaxDepth - 1 );
   UInt  uiMinCUHeight = uiMaxCUHeight >> ( uiMaxDepth - 1 );
-  
   UInt  uiNumPartInWidth  = uiMaxCUWidth  / uiMinCUWidth;
   UInt  uiNumPartInHeight = uiMaxCUHeight / uiMinCUHeight;
-  
   uiTempX[0] = 0; uiTempX++;
   for ( i = 1; i < uiNumPartInWidth; i++ )
@@ -201,133 +335,181 @@
     uiTempX += uiNumPartInWidth;
   }
-  
   for ( i = 1; i < uiNumPartInWidth*uiNumPartInHeight; i++ )
   {
     uiTempY[i] = ( i / uiNumPartInWidth ) * uiMinCUWidth;
   }
-};
-
-
-Int g_quantScales[6] =
+}
+const Int g_quantScales[SCALING_LIST_REM_NUM] =
 {
   26214,23302,20560,18396,16384,14564
-};    
-
-Int g_invQuantScales[6] =
+};
+const Int g_invQuantScales[SCALING_LIST_REM_NUM] =
 {
   40,45,51,57,64,72
 };
-
-const Short g_aiT4[4][4] =
-{
-  { 64, 64, 64, 64},
-  { 83, 36,-36,-83},
-  { 64,-64,-64, 64},
-  { 36,-83, 83,-36}
-};
-
-const Short g_aiT8[8][8] =
-{
-  { 64, 64, 64, 64, 64, 64, 64, 64},
-  { 89, 75, 50, 18,-18,-50,-75,-89},
-  { 83, 36,-36,-83,-83,-36, 36, 83},
-  { 75,-18,-89,-50, 50, 89, 18,-75},
-  { 64,-64,-64, 64, 64,-64,-64, 64},
-  { 50,-89, 18, 75,-75,-18, 89,-50},
-  { 36,-83, 83,-36,-36, 83,-83, 36},
-  { 18,-50, 75,-89, 89,-75, 50,-18}
-};
-
-const Short g_aiT16[16][16] =
-{
-  { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64},
-  { 90, 87, 80, 70, 57, 43, 25,  9, -9,-25,-43,-57,-70,-80,-87,-90},
-  { 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89},
-  { 87, 57,  9,-43,-80,-90,-70,-25, 25, 70, 90, 80, 43, -9,-57,-87},
-  { 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83},
-  { 80,  9,-70,-87,-25, 57, 90, 43,-43,-90,-57, 25, 87, 70, -9,-80},
-  { 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75},
-  { 70,-43,-87,  9, 90, 25,-80,-57, 57, 80,-25,-90, -9, 87, 43,-70},
-  { 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64},
-  { 57,-80,-25, 90, -9,-87, 43, 70,-70,-43, 87,  9,-90, 25, 80,-57},
-  { 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50},
-  { 43,-90, 57, 25,-87, 70,  9,-80, 80, -9,-70, 87,-25,-57, 90,-43},
-  { 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36},
-  { 25,-70, 90,-80, 43,  9,-57, 87,-87, 57, -9,-43, 80,-90, 70,-25},
-  { 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18},
-  {  9,-25, 43,-57, 70,-80, 87,-90, 90,-87, 80,-70, 57,-43, 25, -9}
-};
-
-const Short g_aiT32[32][32] =
-{
-  { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64},
-  { 90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13,  4, -4,-13,-22,-31,-38,-46,-54,-61,-67,-73,-78,-82,-85,-88,-90,-90},
-  { 90, 87, 80, 70, 57, 43, 25,  9, -9,-25,-43,-57,-70,-80,-87,-90,-90,-87,-80,-70,-57,-43,-25, -9,  9, 25, 43, 57, 70, 80, 87, 90},
-  { 90, 82, 67, 46, 22, -4,-31,-54,-73,-85,-90,-88,-78,-61,-38,-13, 13, 38, 61, 78, 88, 90, 85, 73, 54, 31,  4,-22,-46,-67,-82,-90},
-  { 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89, 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89},
-  { 88, 67, 31,-13,-54,-82,-90,-78,-46, -4, 38, 73, 90, 85, 61, 22,-22,-61,-85,-90,-73,-38,  4, 46, 78, 90, 82, 54, 13,-31,-67,-88},
-  { 87, 57,  9,-43,-80,-90,-70,-25, 25, 70, 90, 80, 43, -9,-57,-87,-87,-57, -9, 43, 80, 90, 70, 25,-25,-70,-90,-80,-43,  9, 57, 87},
-  { 85, 46,-13,-67,-90,-73,-22, 38, 82, 88, 54, -4,-61,-90,-78,-31, 31, 78, 90, 61,  4,-54,-88,-82,-38, 22, 73, 90, 67, 13,-46,-85},
-  { 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83},
-  { 82, 22,-54,-90,-61, 13, 78, 85, 31,-46,-90,-67,  4, 73, 88, 38,-38,-88,-73, -4, 67, 90, 46,-31,-85,-78,-13, 61, 90, 54,-22,-82},
-  { 80,  9,-70,-87,-25, 57, 90, 43,-43,-90,-57, 25, 87, 70, -9,-80,-80, -9, 70, 87, 25,-57,-90,-43, 43, 90, 57,-25,-87,-70,  9, 80},
-  { 78, -4,-82,-73, 13, 85, 67,-22,-88,-61, 31, 90, 54,-38,-90,-46, 46, 90, 38,-54,-90,-31, 61, 88, 22,-67,-85,-13, 73, 82,  4,-78},
-  { 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75, 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75},
-  { 73,-31,-90,-22, 78, 67,-38,-90,-13, 82, 61,-46,-88, -4, 85, 54,-54,-85,  4, 88, 46,-61,-82, 13, 90, 38,-67,-78, 22, 90, 31,-73},
-  { 70,-43,-87,  9, 90, 25,-80,-57, 57, 80,-25,-90, -9, 87, 43,-70,-70, 43, 87, -9,-90,-25, 80, 57,-57,-80, 25, 90,  9,-87,-43, 70},
-  { 67,-54,-78, 38, 85,-22,-90,  4, 90, 13,-88,-31, 82, 46,-73,-61, 61, 73,-46,-82, 31, 88,-13,-90, -4, 90, 22,-85,-38, 78, 54,-67},
-  { 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64},
-  { 61,-73,-46, 82, 31,-88,-13, 90, -4,-90, 22, 85,-38,-78, 54, 67,-67,-54, 78, 38,-85,-22, 90,  4,-90, 13, 88,-31,-82, 46, 73,-61},
-  { 57,-80,-25, 90, -9,-87, 43, 70,-70,-43, 87,  9,-90, 25, 80,-57,-57, 80, 25,-90,  9, 87,-43,-70, 70, 43,-87, -9, 90,-25,-80, 57},
-  { 54,-85, -4, 88,-46,-61, 82, 13,-90, 38, 67,-78,-22, 90,-31,-73, 73, 31,-90, 22, 78,-67,-38, 90,-13,-82, 61, 46,-88,  4, 85,-54},
-  { 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50, 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50},
-  { 46,-90, 38, 54,-90, 31, 61,-88, 22, 67,-85, 13, 73,-82,  4, 78,-78, -4, 82,-73,-13, 85,-67,-22, 88,-61,-31, 90,-54,-38, 90,-46},
-  { 43,-90, 57, 25,-87, 70,  9,-80, 80, -9,-70, 87,-25,-57, 90,-43,-43, 90,-57,-25, 87,-70, -9, 80,-80,  9, 70,-87, 25, 57,-90, 43},
-  { 38,-88, 73, -4,-67, 90,-46,-31, 85,-78, 13, 61,-90, 54, 22,-82, 82,-22,-54, 90,-61,-13, 78,-85, 31, 46,-90, 67,  4,-73, 88,-38},
-  { 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36},
-  { 31,-78, 90,-61,  4, 54,-88, 82,-38,-22, 73,-90, 67,-13,-46, 85,-85, 46, 13,-67, 90,-73, 22, 38,-82, 88,-54, -4, 61,-90, 78,-31},
-  { 25,-70, 90,-80, 43,  9,-57, 87,-87, 57, -9,-43, 80,-90, 70,-25,-25, 70,-90, 80,-43, -9, 57,-87, 87,-57,  9, 43,-80, 90,-70, 25},
-  { 22,-61, 85,-90, 73,-38, -4, 46,-78, 90,-82, 54,-13,-31, 67,-88, 88,-67, 31, 13,-54, 82,-90, 78,-46,  4, 38,-73, 90,-85, 61,-22},
-  { 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18, 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18},
-  { 13,-38, 61,-78, 88,-90, 85,-73, 54,-31,  4, 22,-46, 67,-82, 90,-90, 82,-67, 46,-22, -4, 31,-54, 73,-85, 90,-88, 78,-61, 38,-13},
-  {  9,-25, 43,-57, 70,-80, 87,-90, 90,-87, 80,-70, 57,-43, 25, -9, -9, 25,-43, 57,-70, 80,-87, 90,-90, 87,-80, 70,-57, 43,-25,  9},
-  {  4,-13, 22,-31, 38,-46, 54,-61, 67,-73, 78,-82, 85,-88, 90,-90, 90,-90, 88,-85, 82,-78, 73,-67, 61,-54, 46,-38, 31,-22, 13, -4}
-};
-
-const UChar g_aucChromaScale[58]=
-{
-   0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,
-  17,18,19,20,21,22,23,24,25,26,27,28,29,29,30,31,32,
-  33,33,34,34,35,35,36,36,37,37,38,39,40,41,42,43,44,
-  45,46,47,48,49,50,51
-};
-
-
-// Mode-Dependent DCT/DST 
-const Short g_as_DST_MAT_4 [4][4]=
-{
-  {29,   55,    74,   84},
-  {74,   74,    0 ,  -74},
-  {84,  -29,   -74,   55},
-  {55,  -84,    74,  -29},
-};
-
-
-// ====================================================================================================================
-// ADI
-// ====================================================================================================================
-
-#if FAST_UDI_USE_MPM
-const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
+//--------------------------------------------------------------------------------------------------
+//structures
+#define DEFINE_DST4x4_MATRIX(a,b,c,d) \
+{ \
+  {  a,  b,  c,  d }, \
+  {  c,  c,  0, -c }, \
+  {  d, -a, -c,  b }, \
+  {  b, -d,  c, -a }, \
+}
+#define DEFINE_DCT4x4_MATRIX(a,b,c) \
+{ \
+  { a,  a,  a,  a}, \
+  { b,  c, -c, -b}, \
+  { a, -a, -a,  a}, \
+  { c, -b,  b, -c}  \
+}
+#define DEFINE_DCT8x8_MATRIX(a,b,c,d,e,f,g) \
+{ \
+  { a,  a,  a,  a,  a,  a,  a,  a}, \
+  { d,  e,  f,  g, -g, -f, -e, -d}, \
+  { b,  c, -c, -b, -b, -c,  c,  b}, \
+  { e, -g, -d, -f,  f,  d,  g, -e}, \
+  { a, -a, -a,  a,  a, -a, -a,  a}, \
+  { f, -d,  g,  e, -e, -g,  d, -f}, \
+  { c, -b,  b, -c, -c,  b, -b,  c}, \
+  { g, -f,  e, -d,  d, -e,  f, -g}  \
+}
+#define DEFINE_DCT16x16_MATRIX(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) \
+{ \
+  { a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a}, \
+  { h,  i,  j,  k,  l,  m,  n,  o, -o, -n, -m, -l, -k, -j, -i, -h}, \
+  { d,  e,  f,  g, -g, -f, -e, -d, -d, -e, -f, -g,  g,  f,  e,  d}, \
+  { i,  l,  o, -m, -j, -h, -k, -n,  n,  k,  h,  j,  m, -o, -l, -i}, \
+  { b,  c, -c, -b, -b, -c,  c,  b,  b,  c, -c, -b, -b, -c,  c,  b}, \
+  { j,  o, -k, -i, -n,  l,  h,  m, -m, -h, -l,  n,  i,  k, -o, -j}, \
+  { e, -g, -d, -f,  f,  d,  g, -e, -e,  g,  d,  f, -f, -d, -g,  e}, \
+  { k, -m, -i,  o,  h,  n, -j, -l,  l,  j, -n, -h, -o,  i,  m, -k}, \
+  { a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a}, \
+  { l, -j, -n,  h, -o, -i,  m,  k, -k, -m,  i,  o, -h,  n,  j, -l}, \
+  { f, -d,  g,  e, -e, -g,  d, -f, -f,  d, -g, -e,  e,  g, -d,  f}, \
+  { m, -h,  l,  n, -i,  k,  o, -j,  j, -o, -k,  i, -n, -l,  h, -m}, \
+  { c, -b,  b, -c, -c,  b, -b,  c,  c, -b,  b, -c, -c,  b, -b,  c}, \
+  { n, -k,  h, -j,  m,  o, -l,  i, -i,  l, -o, -m,  j, -h,  k, -n}, \
+  { g, -f,  e, -d,  d, -e,  f, -g, -g,  f, -e,  d, -d,  e, -f,  g}, \
+  { o, -n,  m, -l,  k, -j,  i, -h,  h, -i,  j, -k,  l, -m,  n, -o}  \
+}
+#define DEFINE_DCT32x32_MATRIX(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E) \
+{ \
+  { a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a}, \
+  { p,  q,  r,  s,  t,  u,  v,  w,  x,  y,  z,  A,  B,  C,  D,  E, -E, -D, -C, -B, -A, -z, -y, -x, -w, -v, -u, -t, -s, -r, -q, -p}, \
+  { h,  i,  j,  k,  l,  m,  n,  o, -o, -n, -m, -l, -k, -j, -i, -h, -h, -i, -j, -k, -l, -m, -n, -o,  o,  n,  m,  l,  k,  j,  i,  h}, \
+  { q,  t,  w,  z,  C, -E, -B, -y, -v, -s, -p, -r, -u, -x, -A, -D,  D,  A,  x,  u,  r,  p,  s,  v,  y,  B,  E, -C, -z, -w, -t, -q}, \
+  { d,  e,  f,  g, -g, -f, -e, -d, -d, -e, -f, -g,  g,  f,  e,  d,  d,  e,  f,  g, -g, -f, -e, -d, -d, -e, -f, -g,  g,  f,  e,  d}, \
+  { r,  w,  B, -D, -y, -t, -p, -u, -z, -E,  A,  v,  q,  s,  x,  C, -C, -x, -s, -q, -v, -A,  E,  z,  u,  p,  t,  y,  D, -B, -w, -r}, \
+  { i,  l,  o, -m, -j, -h, -k, -n,  n,  k,  h,  j,  m, -o, -l, -i, -i, -l, -o,  m,  j,  h,  k,  n, -n, -k, -h, -j, -m,  o,  l,  i}, \
+  { s,  z, -D, -w, -p, -v, -C,  A,  t,  r,  y, -E, -x, -q, -u, -B,  B,  u,  q,  x,  E, -y, -r, -t, -A,  C,  v,  p,  w,  D, -z, -s}, \
+  { b,  c, -c, -b, -b, -c,  c,  b,  b,  c, -c, -b, -b, -c,  c,  b,  b,  c, -c, -b, -b, -c,  c,  b,  b,  c, -c, -b, -b, -c,  c,  b}, \
+  { t,  C, -y, -p, -x,  D,  u,  s,  B, -z, -q, -w,  E,  v,  r,  A, -A, -r, -v, -E,  w,  q,  z, -B, -s, -u, -D,  x,  p,  y, -C, -t}, \
+  { j,  o, -k, -i, -n,  l,  h,  m, -m, -h, -l,  n,  i,  k, -o, -j, -j, -o,  k,  i,  n, -l, -h, -m,  m,  h,  l, -n, -i, -k,  o,  j}, \
+  { u, -E, -t, -v,  D,  s,  w, -C, -r, -x,  B,  q,  y, -A, -p, -z,  z,  p,  A, -y, -q, -B,  x,  r,  C, -w, -s, -D,  v,  t,  E, -u}, \
+  { e, -g, -d, -f,  f,  d,  g, -e, -e,  g,  d,  f, -f, -d, -g,  e,  e, -g, -d, -f,  f,  d,  g, -e, -e,  g,  d,  f, -f, -d, -g,  e}, \
+  { v, -B, -p, -C,  u,  w, -A, -q, -D,  t,  x, -z, -r, -E,  s,  y, -y, -s,  E,  r,  z, -x, -t,  D,  q,  A, -w, -u,  C,  p,  B, -v}, \
+  { k, -m, -i,  o,  h,  n, -j, -l,  l,  j, -n, -h, -o,  i,  m, -k, -k,  m,  i, -o, -h, -n,  j,  l, -l, -j,  n,  h,  o, -i, -m,  k}, \
+  { w, -y, -u,  A,  s, -C, -q,  E,  p,  D, -r, -B,  t,  z, -v, -x,  x,  v, -z, -t,  B,  r, -D, -p, -E,  q,  C, -s, -A,  u,  y, -w}, \
+  { a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a}, \
+  { x, -v, -z,  t,  B, -r, -D,  p, -E, -q,  C,  s, -A, -u,  y,  w, -w, -y,  u,  A, -s, -C,  q,  E, -p,  D,  r, -B, -t,  z,  v, -x}, \
+  { l, -j, -n,  h, -o, -i,  m,  k, -k, -m,  i,  o, -h,  n,  j, -l, -l,  j,  n, -h,  o,  i, -m, -k,  k,  m, -i, -o,  h, -n, -j,  l}, \
+  { y, -s, -E,  r, -z, -x,  t,  D, -q,  A,  w, -u, -C,  p, -B, -v,  v,  B, -p,  C,  u, -w, -A,  q, -D, -t,  x,  z, -r,  E,  s, -y}, \
+  { f, -d,  g,  e, -e, -g,  d, -f, -f,  d, -g, -e,  e,  g, -d,  f,  f, -d,  g,  e, -e, -g,  d, -f, -f,  d, -g, -e,  e,  g, -d,  f}, \
+  { z, -p,  A,  y, -q,  B,  x, -r,  C,  w, -s,  D,  v, -t,  E,  u, -u, -E,  t, -v, -D,  s, -w, -C,  r, -x, -B,  q, -y, -A,  p, -z}, \
+  { m, -h,  l,  n, -i,  k,  o, -j,  j, -o, -k,  i, -n, -l,  h, -m, -m,  h, -l, -n,  i, -k, -o,  j, -j,  o,  k, -i,  n,  l, -h,  m}, \
+  { A, -r,  v, -E, -w,  q, -z, -B,  s, -u,  D,  x, -p,  y,  C, -t,  t, -C, -y,  p, -x, -D,  u, -s,  B,  z, -q,  w,  E, -v,  r, -A}, \
+  { c, -b,  b, -c, -c,  b, -b,  c,  c, -b,  b, -c, -c,  b, -b,  c,  c, -b,  b, -c, -c,  b, -b,  c,  c, -b,  b, -c, -c,  b, -b,  c}, \
+  { B, -u,  q, -x,  E,  y, -r,  t, -A, -C,  v, -p,  w, -D, -z,  s, -s,  z,  D, -w,  p, -v,  C,  A, -t,  r, -y, -E,  x, -q,  u, -B}, \
+  { n, -k,  h, -j,  m,  o, -l,  i, -i,  l, -o, -m,  j, -h,  k, -n, -n,  k, -h,  j, -m, -o,  l, -i,  i, -l,  o,  m, -j,  h, -k,  n}, \
+  { C, -x,  s, -q,  v, -A, -E,  z, -u,  p, -t,  y, -D, -B,  w, -r,  r, -w,  B,  D, -y,  t, -p,  u, -z,  E,  A, -v,  q, -s,  x, -C}, \
+  { g, -f,  e, -d,  d, -e,  f, -g, -g,  f, -e,  d, -d,  e, -f,  g,  g, -f,  e, -d,  d, -e,  f, -g, -g,  f, -e,  d, -d,  e, -f,  g}, \
+  { D, -A,  x, -u,  r, -p,  s, -v,  y, -B,  E,  C, -z,  w, -t,  q, -q,  t, -w,  z, -C, -E,  B, -y,  v, -s,  p, -r,  u, -x,  A, -D}, \
+  { o, -n,  m, -l,  k, -j,  i, -h,  h, -i,  j, -k,  l, -m,  n, -o, -o,  n, -m,  l, -k,  j, -i,  h, -h,  i, -j,  k, -l,  m, -n,  o}, \
+  { E, -D,  C, -B,  A, -z,  y, -x,  w, -v,  u, -t,  s, -r,  q, -p,  p, -q,  r, -s,  t, -u,  v, -w,  x, -y,  z, -A,  B, -C,  D, -E}  \
+}
+//--------------------------------------------------------------------------------------------------
+//coefficients
+#if RExt__HIGH_PRECISION_FORWARD_TRANSFORM
+const TMatrixCoeff g_aiT4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4]   =
+{
+  DEFINE_DCT4x4_MATRIX  (16384, 21266,  9224),
+  DEFINE_DCT4x4_MATRIX  (   64,    83,    36)
+};
+const TMatrixCoeff g_aiT8 [TRANSFORM_NUMBER_OF_DIRECTIONS][8][8]   =
+{
+  DEFINE_DCT8x8_MATRIX  (16384, 21266,  9224, 22813, 19244, 12769,  4563),
+  DEFINE_DCT8x8_MATRIX  (   64,    83,    36,    89,    75,    50,    18)
+};
+const TMatrixCoeff g_aiT16[TRANSFORM_NUMBER_OF_DIRECTIONS][16][16] =
+{
+  DEFINE_DCT16x16_MATRIX(16384, 21266,  9224, 22813, 19244, 12769,  4563, 23120, 22063, 20450, 17972, 14642, 11109,  6446,  2316),
+  DEFINE_DCT16x16_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9)
+};
+const TMatrixCoeff g_aiT32[TRANSFORM_NUMBER_OF_DIRECTIONS][32][32] =
+{
+  DEFINE_DCT32x32_MATRIX(16384, 21266,  9224, 22813, 19244, 12769,  4563, 23120, 22063, 20450, 17972, 14642, 11109,  6446,  2316, 23106, 22852, 22445, 21848, 20995, 19810, 18601, 17143, 15718, 13853, 11749,  9846,  7908,  5573,  3281,   946),
+  DEFINE_DCT32x32_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9,    90,    90,    88,    85,    82,    78,    73,    67,    61,    54,    46,    38,    31,    22,    13,     4)
+};
+const TMatrixCoeff g_as_DST_MAT_4[TRANSFORM_NUMBER_OF_DIRECTIONS][4][4] =
+{
+  DEFINE_DST4x4_MATRIX( 7424, 14081, 18893, 21505),
+  DEFINE_DST4x4_MATRIX(   29,    55,    74,    84)
+};
+#else
+const TMatrixCoeff g_aiT4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4]   =
+{
+  DEFINE_DCT4x4_MATRIX  (   64,    83,    36),
+  DEFINE_DCT4x4_MATRIX  (   64,    83,    36)
+};
+const TMatrixCoeff g_aiT8 [TRANSFORM_NUMBER_OF_DIRECTIONS][8][8]   =
+{
+  DEFINE_DCT8x8_MATRIX  (   64,    83,    36,    89,    75,    50,    18),
+  DEFINE_DCT8x8_MATRIX  (   64,    83,    36,    89,    75,    50,    18)
+};
+const TMatrixCoeff g_aiT16[TRANSFORM_NUMBER_OF_DIRECTIONS][16][16] =
+{
+  DEFINE_DCT16x16_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9),
+  DEFINE_DCT16x16_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9)
+};
+const TMatrixCoeff g_aiT32[TRANSFORM_NUMBER_OF_DIRECTIONS][32][32] =
+{
+  DEFINE_DCT32x32_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9,    90,    90,    88,    85,    82,    78,    73,    67,    61,    54,    46,    38,    31,    22,    13,     4),
+  DEFINE_DCT32x32_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9,    90,    90,    88,    85,    82,    78,    73,    67,    61,    54,    46,    38,    31,    22,    13,     4)
+};
+const TMatrixCoeff g_as_DST_MAT_4[TRANSFORM_NUMBER_OF_DIRECTIONS][4][4] =
+{
+  DEFINE_DST4x4_MATRIX(   29,    55,    74,    84),
+  DEFINE_DST4x4_MATRIX(   29,    55,    74,    84)
+};
+#endif
+//--------------------------------------------------------------------------------------------------
+#undef DEFINE_DST4x4_MATRIX
+#undef DEFINE_DCT4x4_MATRIX
+#undef DEFINE_DCT8x8_MATRIX
+#undef DEFINE_DCT16x16_MATRIX
+#undef DEFINE_DCT32x32_MATRIX
+//--------------------------------------------------------------------------------------------------
+const UChar g_aucChromaScale[NUM_CHROMA_FORMAT][chromaQPMappingTableSize]=
+{
+  //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57
+  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
+  { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,29,30,31,32,33,33,34,34,35,35,36,36,37,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51 },
+  { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,51,51,51,51,51,51 },
+  { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,51,51,51,51,51,51 }
+};
+// ====================================================================================================================
+// Intra prediction
+// ====================================================================================================================
+const UChar g_aucIntraModeNumFast_UseMPM[MAX_CU_DEPTH] =
 {
   3,  //   2x2
   8,  //   4x4
   8,  //   8x8
-  3,  //  16x16   
-  3,  //  32x32   
-  3   //  64x64   
-};
-#else // FAST_UDI_USE_MPM
-const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
+  3,  //  16x16
+  3,  //  32x32
+  3   //  64x64
+};
+const UChar g_aucIntraModeNumFast_NotUseMPM[MAX_CU_DEPTH] =
 {
   3,  //   2x2
@@ -338,21 +520,7 @@
   5   //  64x64   33
 };
-#endif // FAST_UDI_USE_MPM
-
-// chroma
-
-const UChar g_aucConvertTxtTypeToIdx[4] = { 0, 1, 1, 2 };
-
-
-// ====================================================================================================================
-// Bit-depth
-// ====================================================================================================================
-
-Int  g_bitDepthY = 8;
-Int  g_bitDepthC = 8;
-
-UInt g_uiPCMBitDepthLuma     = 8;    // PCM bit-depth
-UInt g_uiPCMBitDepthChroma   = 8;    // PCM bit-depth
-
+const UChar g_chroma422IntraAngleMappingTable[NUM_INTRA_MODE] =
+  //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, DM
+  { 0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 29, 30, 31, DM_CHROMA_IDX};
 #if H_3D_DIM_DMM
 // ====================================================================================================================
@@ -368,30 +536,24 @@
   FULL_PEL     // 128x128
 };
-
 const UChar g_dmm1TabIdxBits[6] =
 { //2x2   4x4   8x8 16x16 32x32 64x64
      0,    7,   10,   9,    9,   13 };
-
 const UChar g_dmm3IntraTabIdxBits[6] =
 { //2x2   4x4   8x8 16x16 32x32 64x64
      0,    4,    7,    8,    8,    0 };
-
 Bool g_wedgePattern[32*32];
-
 extern std::vector< std::vector<TComWedgelet> >   g_dmmWedgeLists;
 extern std::vector< std::vector<TComWedgeRef> >   g_dmmWedgeRefLists;
 extern std::vector< std::vector<TComWedgeNode> >  g_dmmWedgeNodeLists;
 #endif
-
 // ====================================================================================================================
 // Misc.
 // ====================================================================================================================
-
 Char  g_aucConvertToBit  [ MAX_CU_SIZE+1 ];
 #if ENC_DEC_TRACE
-FILE*  g_hTrace = NULL;
+FILE*  g_hTrace = NULL; // Set to NULL to open up a file. Set to stdout to use the current output
 const Bool g_bEncDecTraceEnable  = true;
 const Bool g_bEncDecTraceDisable = false;
-Bool   g_HLSTraceEnable = true;
+Bool   g_HLSTraceEnable = false;
 Bool   g_bJustDoIt = false;
 UInt64 g_nSymbolCounter = 0;
@@ -407,8 +569,8 @@
 Bool g_decTraceMvFromMerge   = false; 
 Bool g_decTracePicOutput     = false; 
-Bool g_stopAtPos             = true; 
-Bool g_outputPos             = true;   
+Bool g_stopAtPos             = false; 
+Bool g_outputPos             = false;   
 Bool g_traceCameraParameters = false; 
-Bool g_encNumberOfWrittenBits     = true; 
+Bool g_encNumberOfWrittenBits     = false; 
 #endif
 #endif
@@ -416,148 +578,74 @@
 // Scanning order & context model mapping
 // ====================================================================================================================
-
 // scanning order table
-UInt* g_auiSigLastScan[ 3 ][ MAX_CU_DEPTH ];
-
-const UInt g_sigLastScan8x8[ 3 ][ 4 ] =
-{
-  {0, 2, 1, 3},
-  {0, 1, 2, 3},
-  {0, 2, 1, 3}
-};
-UInt g_sigLastScanCG32x32[ 64 ];
-
-const UInt g_uiMinInGroup[ 10 ] = {0,1,2,3,4,6,8,12,16,24};
-const UInt g_uiGroupIdx[ 32 ]   = {0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9};
-
-Void initSigLastScan(UInt* pBuffD, UInt* pBuffH, UInt* pBuffV, Int iWidth, Int iHeight)
-{
-  const UInt  uiNumScanPos  = UInt( iWidth * iWidth );
-  UInt        uiNextScanPos = 0;
-
-  if( iWidth < 16 )
-  {
-  UInt* pBuffTemp = pBuffD;
-  if( iWidth == 8 )
-  {
-    pBuffTemp = g_sigLastScanCG32x32;
-  }
-  for( UInt uiScanLine = 0; uiNextScanPos < uiNumScanPos; uiScanLine++ )
-  {
-    Int    iPrimDim  = Int( uiScanLine );
-    Int    iScndDim  = 0;
-    while( iPrimDim >= iWidth )
-    {
-      iScndDim++;
-      iPrimDim--;
-    }
-    while( iPrimDim >= 0 && iScndDim < iWidth )
-    {
-      pBuffTemp[ uiNextScanPos ] = iPrimDim * iWidth + iScndDim ;
-      uiNextScanPos++;
-      iScndDim++;
-      iPrimDim--;
-    }
-  }
-  }
-  if( iWidth > 4 )
-  {
-    UInt uiNumBlkSide = iWidth >> 2;
-    UInt uiNumBlks    = uiNumBlkSide * uiNumBlkSide;
-    UInt log2Blk      = g_aucConvertToBit[ uiNumBlkSide ] + 1;
-
-    for( UInt uiBlk = 0; uiBlk < uiNumBlks; uiBlk++ )
-    {
-      uiNextScanPos   = 0;
-      UInt initBlkPos = g_auiSigLastScan[ SCAN_DIAG ][ log2Blk ][ uiBlk ];
-      if( iWidth == 32 )
-      {
-        initBlkPos = g_sigLastScanCG32x32[ uiBlk ];
-      }
-      UInt offsetY    = initBlkPos / uiNumBlkSide;
-      UInt offsetX    = initBlkPos - offsetY * uiNumBlkSide;
-      UInt offsetD    = 4 * ( offsetX + offsetY * iWidth );
-      UInt offsetScan = 16 * uiBlk;
-      for( UInt uiScanLine = 0; uiNextScanPos < 16; uiScanLine++ )
-      {
-        Int    iPrimDim  = Int( uiScanLine );
-        Int    iScndDim  = 0;
-        while( iPrimDim >= 4 )
-        {
-          iScndDim++;
-          iPrimDim--;
-        }
-        while( iPrimDim >= 0 && iScndDim < 4 )
-        {
-          pBuffD[ uiNextScanPos + offsetScan ] = iPrimDim * iWidth + iScndDim + offsetD;
-          uiNextScanPos++;
-          iScndDim++;
-          iPrimDim--;
-        }
-      }
-    }
-  }
-  
-  UInt uiCnt = 0;
-  if( iWidth > 2 )
-  {
-    UInt numBlkSide = iWidth >> 2;
-    for(Int blkY=0; blkY < numBlkSide; blkY++)
-    {
-      for(Int blkX=0; blkX < numBlkSide; blkX++)
-      {
-        UInt offset    = blkY * 4 * iWidth + blkX * 4;
-        for(Int y=0; y < 4; y++)
-        {
-          for(Int x=0; x < 4; x++)
-          {
-            pBuffH[uiCnt] = y*iWidth + x + offset;
-            uiCnt ++;
-          }
-        }
-      }
-    }
-
-    uiCnt = 0;
-    for(Int blkX=0; blkX < numBlkSide; blkX++)
-    {
-      for(Int blkY=0; blkY < numBlkSide; blkY++)
-      {
-        UInt offset    = blkY * 4 * iWidth + blkX * 4;
-        for(Int x=0; x < 4; x++)
-        {
-          for(Int y=0; y < 4; y++)
-          {
-            pBuffV[uiCnt] = y*iWidth + x + offset;
-            uiCnt ++;
-          }
-        }
-      }
-    }
-  }
-  else
-  {
-  for(Int iY=0; iY < iHeight; iY++)
-  {
-    for(Int iX=0; iX < iWidth; iX++)
-    {
-      pBuffH[uiCnt] = iY*iWidth + iX;
-      uiCnt ++;
-    }
-  }
-
-  uiCnt = 0;
-  for(Int iX=0; iX < iWidth; iX++)
-  {
-    for(Int iY=0; iY < iHeight; iY++)
-    {
-      pBuffV[uiCnt] = iY*iWidth + iX;
-      uiCnt ++;
-    }
-  }    
-  }
-}
-
-Int g_quantTSDefault4x4[16] =
+UInt* g_scanOrder[SCAN_NUMBER_OF_GROUP_TYPES][SCAN_NUMBER_OF_TYPES][ MAX_CU_DEPTH ][ MAX_CU_DEPTH ];
+const UInt ctxIndMap4x4[4*4] =
+{
+  0, 1, 4, 5,
+  2, 3, 4, 5,
+  6, 6, 8, 8,
+  7, 7, 8, 8
+};
+const UInt g_uiMinInGroup[ LAST_SIGNIFICANT_GROUPS ] = {0,1,2,3,4,6,8,12,16,24};
+const UInt g_uiGroupIdx[ MAX_TU_SIZE ]   = {0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9};
+const Char *MatrixType[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM] =
+{
+  {
+    "INTRA4X4_LUMA",
+    "INTRA4X4_CHROMAU",
+    "INTRA4X4_CHROMAV",
+    "INTER4X4_LUMA",
+    "INTER4X4_CHROMAU",
+    "INTER4X4_CHROMAV"
+  },
+  {
+    "INTRA8X8_LUMA",
+    "INTRA8X8_CHROMAU",
+    "INTRA8X8_CHROMAV",
+    "INTER8X8_LUMA",
+    "INTER8X8_CHROMAU",
+    "INTER8X8_CHROMAV"
+  },
+  {
+    "INTRA16X16_LUMA",
+    "INTRA16X16_CHROMAU",
+    "INTRA16X16_CHROMAV",
+    "INTER16X16_LUMA",
+    "INTER16X16_CHROMAU",
+    "INTER16X16_CHROMAV"
+  },
+  {
+   "INTRA32X32_LUMA",
+   "INTRA32X32_CHROMAU_FROM16x16_CHROMAU",
+   "INTRA32X32_CHROMAV_FROM16x16_CHROMAV",
+   "INTER32X32_LUMA",
+   "INTER32X32_CHROMAU_FROM16x16_CHROMAU",
+   "INTER32X32_CHROMAV_FROM16x16_CHROMAV"
+  },
+};
+const Char *MatrixType_DC[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM] =
+{
+  {
+  },
+  {
+  },
+  {
+    "INTRA16X16_LUMA_DC",
+    "INTRA16X16_CHROMAU_DC",
+    "INTRA16X16_CHROMAV_DC",
+    "INTER16X16_LUMA_DC",
+    "INTER16X16_CHROMAU_DC",
+    "INTER16X16_CHROMAV_DC"
+  },
+  {
+    "INTRA32X32_LUMA_DC",
+    "INTRA32X32_CHROMAU_DC_FROM16x16_CHROMAU",
+    "INTRA32X32_CHROMAV_DC_FROM16x16_CHROMAV",
+    "INTER32X32_LUMA_DC",
+    "INTER32X32_CHROMAU_DC_FROM16x16_CHROMAU",
+    "INTER32X32_CHROMAV_DC_FROM16x16_CHROMAV"
+  },
+};
+const Int g_quantTSDefault4x4[4*4] =
 {
   16,16,16,16,
@@ -566,6 +654,5 @@
   16,16,16,16
 };
-
-Int g_quantIntraDefault8x8[64] =
+const Int g_quantIntraDefault8x8[8*8] =
 {
   16,16,16,16,17,18,21,24,
@@ -578,6 +665,5 @@
   24,25,29,36,47,65,88,115
 };
-
-Int g_quantInterDefault8x8[64] =
+const Int g_quantInterDefault8x8[8*8] =
 {
   16,16,16,16,17,18,20,24,
@@ -590,14 +676,21 @@
   24,25,28,33,41,54,71,91
 };
-UInt g_scalingListSize   [4] = {16,64,256,1024}; 
-UInt g_scalingListSizeX  [4] = { 4, 8, 16,  32};
-UInt g_scalingListNum[SCALING_LIST_SIZE_NUM]={6,6,6,2};
-Int  g_eTTable[4] = {0,3,1,2};
-
+const UInt g_scalingListSize   [SCALING_LIST_SIZE_NUM] = {16,64,256,1024};
+const UInt g_scalingListSizeX  [SCALING_LIST_SIZE_NUM] = { 4, 8, 16,  32};
 #if H_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
+Void tracePSHeader( const Char* psName, Int layerId )
+{  
+  if ( !g_disableHLSTrace  ) 
+  {
+    fprintf( g_hTrace, "=========== ");    
+    fprintf( g_hTrace, "%s", psName );    
+    fprintf( g_hTrace, " Layer %d ===========", layerId );    
+    fprintf( g_hTrace, "\n" );    
+    fflush ( g_hTrace );    
+  }
+}
 Void stopAtPos( Int poc, Int layerId, Int cuPelX, Int cuPelY, Int cuWidth, Int cuHeight )
 {
-
   if ( g_outputPos ) 
   {
@@ -610,5 +703,4 @@
               << std::endl; 
   }
-
   Bool stopFlag = false; 
   if ( g_stopAtPos && poc == 0 && layerId == 2 )
@@ -623,12 +715,9 @@
       Int xPos = 888; 
       Int yPos = 248; 
-
       Int cuPelXEnd = cuPelX + cuWidth  - 1; 
       Int cuPelYEnd = cuPelY + cuHeight - 1; 
-
       stopFlag = (cuPelX <= xPos ) && (cuPelXEnd >= xPos ) && (cuPelY <= yPos ) && (cuPelYEnd >= yPos ); 
     }
   }
-  
   if ( stopFlag )
   { // Set breakpoint here. 
@@ -636,5 +725,4 @@
   }  
 }
-
 Void writeToTraceFile( const Char* symbolName, Int val, Bool doIt )
 {
@@ -654,5 +742,4 @@
   }
 }
-
 Void writeToTraceFile( const Char* symbolName, Bool doIt )
 {
@@ -664,5 +751,4 @@
   }
 }
-
 #endif
 #endif
@@ -671,9 +757,7 @@
 std::vector< std::vector<TComWedgeRef>  > g_dmmWedgeRefLists;
 std::vector< std::vector<TComWedgeNode> > g_dmmWedgeNodeLists;
-
 Void initWedgeLists( Bool initNodeList )
 {
   if( !g_dmmWedgeLists.empty() ) return;
-
   for( UInt ui = g_aucConvertToBit[DIM_MIN_SIZE]; ui < (g_aucConvertToBit[DIM_MAX_SIZE]); ui++ )
   {
@@ -684,5 +768,4 @@
     g_dmmWedgeLists.push_back( acWedgeList );
     g_dmmWedgeRefLists.push_back( acWedgeRefList );
-
     if( initNodeList )
     {
@@ -695,5 +778,4 @@
           TComWedgeNode cWedgeNode;
           cWedgeNode.setPatternIdx( uiPos );
-
           UInt uiRefPos = 0;
           for( Int iOffS = -1; iOffS <= 1; iOffS++ )
@@ -702,10 +784,8 @@
             {
               if( iOffS == 0 && iOffE == 0 ) { continue; }
-
               Int iSx = (Int)acWedgeList[uiPos].getStartX();
               Int iSy = (Int)acWedgeList[uiPos].getStartY();
               Int iEx = (Int)acWedgeList[uiPos].getEndX();
               Int iEy = (Int)acWedgeList[uiPos].getEndY();
-
               switch( acWedgeList[uiPos].getOri() )
               {
@@ -718,5 +798,4 @@
               default: assert( 0 );
               }
-
               for( UInt k = 0; k < acWedgeRefList.size(); k++ )
               {
@@ -730,5 +809,4 @@
                     Bool bNew = true;
                     for( UInt m = 0; m < uiRefPos; m++ ) { if( acWedgeRefList[k].getRefIdx() == cWedgeNode.getRefineIdx( m ) ) { bNew = false; break; } }
-
                     if( bNew ) 
                     {
@@ -749,11 +827,8 @@
   }
 }
-
 Void createWedgeList( UInt uiWidth, UInt uiHeight, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList, WedgeResolution eWedgeRes )
 {
   assert( uiWidth == uiHeight );
-
   Int posStart = 0, posEnd = 0;
-
   UInt uiBlockSize = 0;
   switch( eWedgeRes )
@@ -762,9 +837,7 @@
   case(   HALF_PEL ): { uiBlockSize = (uiWidth<<1); break; }
   }
-
   TComWedgelet cTempWedgelet( uiWidth, uiHeight );
   for( UInt uiOri = 0; uiOri < 6; uiOri++ )
   {
-
     posEnd = (Int) racWedgeList.size();
     if (uiOri == 0 || uiOri == 4)
@@ -793,8 +866,5 @@
     posStart = posEnd;
   }
-
-
-}
-
+}
 Void addWedgeletToList( TComWedgelet cWedgelet, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList )
 {
@@ -838,4 +908,3 @@
 }
 #endif //H_3D_DIM_DMM
-
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRom.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRom.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComRom.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -31,123 +31,64 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
-
 /** \file     TComRom.h
     \brief    global variables & functions (header)
 */
-
 #ifndef __TCOMROM__
 #define __TCOMROM__
-
 #include "CommonDef.h"
-#include "TypeDef.h"
-
 #include<stdio.h>
 #include<iostream>
-
 #if H_3D_DIM
 #include "TComWedgelet.h"
 #endif
-
 //! \ingroup TLibCommon
 //! \{
-
-// ====================================================================================================================
-// Macros
-// ====================================================================================================================
-
-#define     MAX_CU_DEPTH            6                           // log2(LCUSize)
-#define     MAX_CU_SIZE             (1<<(MAX_CU_DEPTH))         // maximum allowable size of CU
-#define     MIN_PU_SIZE             4
-#define     MAX_NUM_SPU_W           (MAX_CU_SIZE/MIN_PU_SIZE)   // maximum number of SPU in horizontal line
-
 // ====================================================================================================================
 // Initialize / destroy functions
 // ====================================================================================================================
-
 Void         initROM();
 Void         destroyROM();
-Void         initSigLastScan(UInt* pBuffD, UInt* pBuffH, UInt* pBuffV, Int iWidth, Int iHeight);
 // ====================================================================================================================
 // Data structure related table & variable
 // ====================================================================================================================
-
 // flexible conversion from relative to absolute index
-extern       UInt   g_auiZscanToRaster[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-extern       UInt   g_auiRasterToZscan[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-
+extern       UInt   g_auiZscanToRaster[ MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH ];
+extern       UInt   g_auiRasterToZscan[ MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH ];
+extern       UInt*  g_scanOrder[SCAN_NUMBER_OF_GROUP_TYPES][SCAN_NUMBER_OF_TYPES][ MAX_CU_DEPTH ][ MAX_CU_DEPTH ];
 Void         initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx );
 Void         initRasterToZscan ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth         );
-
 // conversion of partition index to picture pel position
-extern       UInt   g_auiRasterToPelX[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-extern       UInt   g_auiRasterToPelY[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-
+extern       UInt   g_auiRasterToPelX[ MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH ];
+extern       UInt   g_auiRasterToPelY[ MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH ];
 Void         initRasterToPelXY ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth );
-
-// global variable (LCU width/height, max. CU depth)
-extern       UInt g_uiMaxCUWidth;
-extern       UInt g_uiMaxCUHeight;
-extern       UInt g_uiMaxCUDepth;
-extern       UInt g_uiAddCUDepth;
-
-#define MAX_TS_WIDTH  4
-#define MAX_TS_HEIGHT 4
-
-extern       UInt g_auiPUOffset[8];
-
-#define QUANT_IQUANT_SHIFT    20 // Q(QP%6) * IQ(QP%6) = 2^20
-#define QUANT_SHIFT           14 // Q(4) = 2^14
-#define SCALE_BITS            15 // Inherited from TMuC, pressumably for fractional bit estimates in RDOQ
-#define MAX_TR_DYNAMIC_RANGE  15 // Maximum transform dynamic range (excluding sign bit)
-
-#define SHIFT_INV_1ST          7 // Shift after first inverse transform stage
-#define SHIFT_INV_2ND         12 // Shift after second inverse transform stage
-
-extern Int g_quantScales[6];             // Q(QP%6)  
-extern Int g_invQuantScales[6];          // IQ(QP%6)
-extern const Short g_aiT4[4][4];
-extern const Short g_aiT8[8][8];
-extern const Short g_aiT16[16][16];
-extern const Short g_aiT32[32][32];
-
+extern const UInt g_auiPUOffset[NUMBER_OF_PART_SIZES];
+extern const Int g_quantScales[SCALING_LIST_REM_NUM];             // Q(QP%6)
+extern const Int g_invQuantScales[SCALING_LIST_REM_NUM];          // IQ(QP%6)
+#if RExt__HIGH_PRECISION_FORWARD_TRANSFORM
+static const Int g_transformMatrixShift[TRANSFORM_NUMBER_OF_DIRECTIONS] = { 14, 6 };
+#else
+static const Int g_transformMatrixShift[TRANSFORM_NUMBER_OF_DIRECTIONS] = {  6, 6 };
+#endif
+extern const TMatrixCoeff g_aiT4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4];
+extern const TMatrixCoeff g_aiT8 [TRANSFORM_NUMBER_OF_DIRECTIONS][8][8];
+extern const TMatrixCoeff g_aiT16[TRANSFORM_NUMBER_OF_DIRECTIONS][16][16];
+extern const TMatrixCoeff g_aiT32[TRANSFORM_NUMBER_OF_DIRECTIONS][32][32];
 // ====================================================================================================================
 // Luma QP to Chroma QP mapping
 // ====================================================================================================================
-
-extern const UChar  g_aucChromaScale      [58];
-
+static const Int chromaQPMappingTableSize = 58;
+extern const UChar  g_aucChromaScale[NUM_CHROMA_FORMAT][chromaQPMappingTableSize];
 // ====================================================================================================================
 // Scanning order & context mapping table
 // ====================================================================================================================
-
-extern       UInt*  g_auiSigLastScan[ 3 ][ MAX_CU_DEPTH ];  // raster index from scanning index (diag, hor, ver)
-
-extern const UInt   g_uiGroupIdx[ 32 ];
-extern const UInt   g_uiMinInGroup[ 10 ];
-
-extern const UInt   g_sigLastScan8x8[ 3 ][ 4 ];           //!< coefficient group scan order for 8x8 TUs
-extern       UInt   g_sigLastScanCG32x32[ 64 ];
-
-// ====================================================================================================================
-// ADI table
-// ====================================================================================================================
-
-extern const UChar  g_aucIntraModeNumFast[ MAX_CU_DEPTH ];
-
-// ====================================================================================================================
-// Bit-depth
-// ====================================================================================================================
-
-extern        Int g_bitDepthY;
-extern        Int g_bitDepthC;
-extern       UInt g_uiPCMBitDepthLuma;
-extern       UInt g_uiPCMBitDepthChroma;
-
-// ====================================================================================================================
-// Texture type to integer mapping
-// ====================================================================================================================
-
-extern const UChar g_aucConvertTxtTypeToIdx[4];
-
+extern const UInt   ctxIndMap4x4[4*4];
+extern const UInt   g_uiGroupIdx[ MAX_TU_SIZE ];
+extern const UInt   g_uiMinInGroup[ LAST_SIGNIFICANT_GROUPS ];
+// ====================================================================================================================
+// Intra prediction table
+// ====================================================================================================================
+extern const UChar  g_aucIntraModeNumFast_UseMPM[MAX_CU_DEPTH];
+extern const UChar  g_aucIntraModeNumFast_NotUseMPM[MAX_CU_DEPTH];
+extern const UChar  g_chroma422IntraAngleMappingTable[NUM_INTRA_MODE];
 #if H_3D_DIM
 // ====================================================================================================================
@@ -156,20 +97,15 @@
 __inline Void mapDepthModeToIntraDir( UInt& intraMode ) { if( isDimMode( intraMode ) ) intraMode = DC_IDX; }
 __inline Void mapDepthModeToIntraDir(  Int& intraMode ) { if( isDimMode( intraMode ) ) intraMode = DC_IDX; }
-
 #if H_3D_DIM_SDC || H_3D_DIM_DLT
 __inline UInt numBitsForValue( UInt value ) { UInt bits = 0; while (value != 0) { value >>= 1; bits++; } return bits; };
 #endif
-
 #if H_3D_DIM_DMM
 extern const WedgeResolution                                 g_dmmWedgeResolution [6];
 extern const UChar                                           g_dmm1TabIdxBits     [6];
 extern const UChar                                           g_dmm3IntraTabIdxBits[6];
-
 extern Bool                                                  g_wedgePattern[32*32];
-
 extern       std::vector< std::vector<TComWedgelet> >        g_dmmWedgeLists;
 extern       std::vector< std::vector<TComWedgeRef> >        g_dmmWedgeRefLists;
 extern       std::vector< std::vector<TComWedgeNode> >       g_dmmWedgeNodeLists;
-
 Void initWedgeLists( Bool initNodeList = false );
 Void createWedgeList( UInt uiWidth, UInt uiHeight, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList, WedgeResolution eWedgeRes );
@@ -177,12 +113,8 @@
 #endif
 #endif
-
-// ==========================================
+// ====================================================================================================================
 // Mode-Dependent DST Matrices
-extern const Short g_as_DST_MAT_4 [4][4];
-extern const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE];
-extern const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE];
-// ==========================================
-
+// ====================================================================================================================
+extern const TMatrixCoeff g_as_DST_MAT_4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4];
 #if H_MV_HLS_PTL_LIMITS
 class TComGeneralTierAndLevelLimits
@@ -203,5 +135,4 @@
     m_maxTileCols               ( maxTileCols                   );
   {};
-
   Int getMaxLumaPs                 ( ) { return m_maxLumaPs                 ; };
   Int getMaxCPBMainTier            ( ) { return m_maxCPBMainTier            ; };
@@ -210,5 +141,4 @@
   Int getMaxTileRows               ( ) { return m_maxTileRows               ; };
   Int getMaxTileCols               ( ) { return m_maxTileCols               ; };
-
 private:
   const Int m_maxLumaPs;
@@ -219,18 +149,16 @@
   const Int m_maxTileCols; 
 };
-
 extern std::map< Level::Name, TComGeneralTierAndLevelLimits > g_generalTierAndLevelLimits;   
-
 #endif
 // ====================================================================================================================
 // Misc.
 // ====================================================================================================================
-
 extern       Char   g_aucConvertToBit  [ MAX_CU_SIZE+1 ];   // from width to log2(width)-2
-
+#if NH_MV
+// Change later
 #ifndef ENC_DEC_TRACE
-#define ENC_DEC_TRACE   0  
-#endif
-
+#define ENC_DEC_TRACE 0
+#endif
+#endif
 #if ENC_DEC_TRACE
 extern FILE*  g_hTrace;
@@ -240,8 +168,6 @@
 extern Bool   g_HLSTraceEnable;
 extern UInt64 g_nSymbolCounter;
-
 #define COUNTER_START    1
 #define COUNTER_END      0 //( UInt64(1) << 63 )
-
 #define DTRACE_CABAC_F(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%f", x );
 #define DTRACE_CABAC_V(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%d", x );
@@ -251,8 +177,7 @@
 #define DTRACE_CABAC_R( x,y ) if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, x,    y );
 #define DTRACE_CABAC_N        if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "\n"    );
-
 #if H_MV_ENC_DEC_TRAC
  extern Bool   g_traceCU; 
- extern Bool   g_tracePU; 
+ extern Bool   g_tracePU ; 
  extern Bool   g_traceTU; 
  extern Bool   g_disableHLSTrace;       // USE g_HLSTraceEnable to toggle HLS trace. Not this one!
@@ -267,5 +192,4 @@
  extern Bool   g_traceCameraParameters; // Trace camera parameters
  extern Bool   g_encNumberOfWrittenBits;// Trace number of written bits
-
 #define DTRACE_CU(x,y)             writeToTraceFile( x,y, g_traceCU );
 #define DTRACE_PU(x,y)             writeToTraceFile( x,y, g_tracePU );
@@ -274,11 +198,10 @@
 #define DTRACE_PU_S(x)             writeToTraceFile( x,   g_tracePU );
 #define DTRACE_TU_S(x)             writeToTraceFile( x,   g_traceTU );
-
+ Void           tracePSHeader   ( const Char* psName, Int layerId ); 
  Void           writeToTraceFile( const Char* symbolName, Int val, Bool doIt );
  Void           writeToTraceFile( const Char* symbolName, Bool doIt );
- Void           stopAtPos       ( Int poc, Int layerId, Int cuPelX, Int cuPelY, Int cuWidth, Int cuHeight );
+ Void           stopAtPos       ( Int poc, Int layerId, Int cuPelX, Int cuPelY, Int cuWidth, Int cuHeight );           
 #endif
 #else
-
 #define DTRACE_CABAC_F(x)
 #define DTRACE_CABAC_V(x)
@@ -288,96 +211,21 @@
 #define DTRACE_CABAC_R( x,y )
 #define DTRACE_CABAC_N
-
 #if H_MV_ENC_DEC_TRAC
 #define DTRACE_CU(x,y) ;             
 #define DTRACE_PU(x,y) ;            
 #define DTRACE_TU(x,y) ;            
-
 #define DTRACE_CU_S(x) ;            
 #define DTRACE_PU_S(x) ;            
 #define DTRACE_TU_S(x) ;            
-
-#endif
-#endif
-
-
-#define SCALING_LIST_NUM 6         ///< list number for quantization matrix
-#define SCALING_LIST_NUM_32x32 2   ///< list number for quantization matrix 32x32
-#define SCALING_LIST_REM_NUM 6     ///< remainder of QP/6
-#define SCALING_LIST_START_VALUE 8 ///< start value for dpcm mode
-#define MAX_MATRIX_COEF_NUM 64     ///< max coefficient number for quantization matrix
-#define MAX_MATRIX_SIZE_NUM 8      ///< max size number for quantization matrix
-#define SCALING_LIST_DC 16         ///< default DC value
-enum ScalingListSize
-{
-  SCALING_LIST_4x4 = 0,
-  SCALING_LIST_8x8,
-  SCALING_LIST_16x16,
-  SCALING_LIST_32x32,
-  SCALING_LIST_SIZE_NUM
-};
-static const Char MatrixType[4][6][20] =
-{
-  {
-  "INTRA4X4_LUMA",
-  "INTRA4X4_CHROMAU",
-  "INTRA4X4_CHROMAV",
-  "INTER4X4_LUMA",
-  "INTER4X4_CHROMAU",
-  "INTER4X4_CHROMAV"
-  },
-  {
-  "INTRA8X8_LUMA",
-  "INTRA8X8_CHROMAU", 
-  "INTRA8X8_CHROMAV", 
-  "INTER8X8_LUMA",
-  "INTER8X8_CHROMAU", 
-  "INTER8X8_CHROMAV"  
-  },
-  {
-  "INTRA16X16_LUMA",
-  "INTRA16X16_CHROMAU", 
-  "INTRA16X16_CHROMAV", 
-  "INTER16X16_LUMA",
-  "INTER16X16_CHROMAU", 
-  "INTER16X16_CHROMAV"  
-  },
-  {
-  "INTRA32X32_LUMA",
-  "INTER32X32_LUMA",
-  },
-};
-static const Char MatrixType_DC[4][12][22] =
-{
-  {
-  },
-  {
-  },
-  {
-  "INTRA16X16_LUMA_DC",
-  "INTRA16X16_CHROMAU_DC", 
-  "INTRA16X16_CHROMAV_DC", 
-  "INTER16X16_LUMA_DC",
-  "INTER16X16_CHROMAU_DC", 
-  "INTER16X16_CHROMAV_DC"  
-  },
-  {
-  "INTRA32X32_LUMA_DC",
-  "INTER32X32_LUMA_DC",
-  },
-};
-extern Int g_quantIntraDefault8x8[64];
-extern Int g_quantIntraDefault16x16[256];
-extern Int g_quantIntraDefault32x32[1024];
-extern Int g_quantInterDefault8x8[64];
-extern Int g_quantInterDefault16x16[256];
-extern Int g_quantInterDefault32x32[1024];
-extern Int g_quantTSDefault4x4[16];
-extern UInt g_scalingListSize [SCALING_LIST_SIZE_NUM];
-extern UInt g_scalingListSizeX[SCALING_LIST_SIZE_NUM];
-extern UInt g_scalingListNum  [SCALING_LIST_SIZE_NUM];
-extern Int  g_eTTable[4];
+#endif
+#endif
+const Char* nalUnitTypeToString(NalUnitType type);
+extern const Char *MatrixType[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
+extern const Char *MatrixType_DC[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
+extern const Int g_quantTSDefault4x4[4*4];
+extern const Int g_quantIntraDefault8x8[8*8];
+extern const Int g_quantInterDefault8x8[8*8];
+extern const UInt g_scalingListSize [SCALING_LIST_SIZE_NUM];
+extern const UInt g_scalingListSizeX[SCALING_LIST_SIZE_NUM];
 //! \}
-
 #endif  //__TCOMROM__
-
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1200)
@@ -2,5 +2,5 @@
  * 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.  
+ * granted under this license.
  *
  * Copyright (c) 2010-2015, ITU/ISO/IEC
@@ -44,8 +44,7 @@
 //! \ingroup TLibCommon
 //! \{
-UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS];
 
 SAOOffset::SAOOffset()
-{ 
+{
   reset();
 }
@@ -87,5 +86,5 @@
 Void SAOBlkParam::reset()
 {
-  for(Int compIdx=0; compIdx< 3; compIdx++)
+  for(Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
   {
     offsetParam[compIdx].reset();
@@ -95,5 +94,5 @@
 const SAOBlkParam& SAOBlkParam::operator= (const SAOBlkParam& src)
 {
-  for(Int compIdx=0; compIdx< 3; compIdx++)
+  for(Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
   {
     offsetParam[compIdx] = src.offsetParam[compIdx];
@@ -106,12 +105,4 @@
 {
   m_tempPicYuv = NULL;
-  for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
-  {
-    m_offsetClipTable[compIdx] = NULL;
-  }
-#if !SAO_SGN_FUNC
-  m_signTable = NULL; 
-#endif
-  
   m_lineBufWidth = 0;
   m_signLineBuf1 = NULL;
@@ -123,21 +114,30 @@
 {
   destroy();
-  
-  if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
-  if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
-}
-
-Void TComSampleAdaptiveOffset::create( Int picWidth, Int picHeight, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth )
+
+  if (m_signLineBuf1)
+  {
+    delete[] m_signLineBuf1;
+    m_signLineBuf1 = NULL;
+  }
+  if (m_signLineBuf2)
+  {
+    delete[] m_signLineBuf2;
+    m_signLineBuf2 = NULL;
+  }
+}
+
+Void TComSampleAdaptiveOffset::create( Int picWidth, Int picHeight, ChromaFormat format, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth, UInt lumaBitShift, UInt chromaBitShift )
 {
   destroy();
 
-  m_picWidth = picWidth;    
-  m_picHeight= picHeight;
-  m_maxCUWidth= maxCUWidth; 
-  m_maxCUHeight= maxCUHeight;
-
-  m_numCTUInWidth = (m_picWidth/m_maxCUWidth) + ((m_picWidth % m_maxCUWidth)?1:0);
-  m_numCTUInHeight= (m_picHeight/m_maxCUHeight) + ((m_picHeight % m_maxCUHeight)?1:0);
-  m_numCTUsPic = m_numCTUInHeight*m_numCTUInWidth;
+  m_picWidth        = picWidth;
+  m_picHeight       = picHeight;
+  m_chromaFormatIDC = format;
+  m_maxCUWidth      = maxCUWidth;
+  m_maxCUHeight     = maxCUHeight;
+
+  m_numCTUInWidth   = (m_picWidth/m_maxCUWidth) + ((m_picWidth % m_maxCUWidth)?1:0);
+  m_numCTUInHeight  = (m_picHeight/m_maxCUHeight) + ((m_picHeight % m_maxCUHeight)?1:0);
+  m_numCTUsPic      = m_numCTUInHeight*m_numCTUInWidth;
 
   //temporary picture buffer
@@ -145,55 +145,12 @@
   {
     m_tempPicYuv = new TComPicYuv;
-    m_tempPicYuv->create( m_picWidth, m_picHeight, m_maxCUWidth, m_maxCUHeight, maxCUDepth );
+    m_tempPicYuv->create( m_picWidth, m_picHeight, m_chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, maxCUDepth, true );
   }
 
   //bit-depth related
-  for(Int compIdx =0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
-  {
-    Int bitDepthSample = (compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC;
-    m_offsetStepLog2  [compIdx] = max(bitDepthSample - MAX_SAO_TRUNCATED_BITDEPTH, 0);
-    g_saoMaxOffsetQVal[compIdx] = (1<<(min(bitDepthSample,MAX_SAO_TRUNCATED_BITDEPTH)-5))-1; //Table 9-32, inclusive
-  }
-
-#if !SAO_SGN_FUNC
-  //look-up table for clipping
-  Int overallMaxSampleValue=0;
-#endif
-  for(Int compIdx =0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
-  {
-    Int bitDepthSample = (compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC; //exclusive
-    Int maxSampleValue = (1<< bitDepthSample); //exclusive
-    Int maxOffsetValue = (g_saoMaxOffsetQVal[compIdx] << m_offsetStepLog2[compIdx]); 
-#if !SAO_SGN_FUNC
-    if (maxSampleValue>overallMaxSampleValue) overallMaxSampleValue=maxSampleValue;
-#endif
-
-    m_offsetClipTable[compIdx] = new Int[(maxSampleValue + maxOffsetValue -1)+ (maxOffsetValue)+1 ]; //positive & negative range plus 0
-    m_offsetClip[compIdx] = &(m_offsetClipTable[compIdx][maxOffsetValue]);
-
-    //assign clipped values 
-    Int* offsetClipPtr = m_offsetClip[compIdx];
-    for(Int k=0; k< maxSampleValue; k++)
-    {
-      *(offsetClipPtr + k) = k;
-    }
-    for(Int k=0; k< maxOffsetValue; k++ )
-    {
-      *(offsetClipPtr + maxSampleValue+ k) = maxSampleValue-1;
-      *(offsetClipPtr -k -1 )              = 0;
-    }
-  }
-
-#if !SAO_SGN_FUNC
-  m_signTable = new Short[ 2*(overallMaxSampleValue-1) + 1 ];
-  m_sign = &(m_signTable[overallMaxSampleValue-1]);
-
-      m_sign[0] = 0;
-  for(Int k=1; k< overallMaxSampleValue; k++)
-      {
-        m_sign[k] = 1;
-        m_sign[-k]= -1;
-      }
-#endif
+  for(Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+  {
+    m_offsetStepLog2  [compIdx] = isLuma(ComponentID(compIdx))? lumaBitShift : chromaBitShift;
+  }
 }
 
@@ -206,21 +163,7 @@
     m_tempPicYuv = NULL;
   }
-
-  for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
-  {
-    if(m_offsetClipTable[compIdx])
-    {
-      delete[] m_offsetClipTable[compIdx]; m_offsetClipTable[compIdx] = NULL;
-    }
-  }
-#if !SAO_SGN_FUNC
-  if( m_signTable )
-  {
-    delete[] m_signTable; m_signTable = NULL;
-  }
-#endif
-}
-
-Void TComSampleAdaptiveOffset::invertQuantOffsets(Int compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets)
+}
+
+Void TComSampleAdaptiveOffset::invertQuantOffsets(ComponentID compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets)
 {
   Int codedOffset[MAX_NUM_SAO_CLASSES];
@@ -247,8 +190,8 @@
 }
 
-Int TComSampleAdaptiveOffset::getMergeList(TComPic* pic, Int ctu, SAOBlkParam* blkParams, std::vector<SAOBlkParam*>& mergeList)
-{
-  Int ctuX = ctu % m_numCTUInWidth;
-  Int ctuY = ctu / m_numCTUInWidth;
+Int TComSampleAdaptiveOffset::getMergeList(TComPic* pic, Int ctuRsAddr, SAOBlkParam* blkParams, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES])
+{
+  Int ctuX = ctuRsAddr % m_numCTUInWidth;
+  Int ctuY = ctuRsAddr / m_numCTUInWidth;
   Int mergedCTUPos;
   Int numValidMergeCandidates = 0;
@@ -264,6 +207,6 @@
         if(ctuY > 0)
         {
-          mergedCTUPos = ctu- m_numCTUInWidth;
-          if( pic->getSAOMergeAvailability(ctu, mergedCTUPos) )
+          mergedCTUPos = ctuRsAddr- m_numCTUInWidth;
+          if( pic->getSAOMergeAvailability(ctuRsAddr, mergedCTUPos) )
           {
             mergeCandidate = &(blkParams[mergedCTUPos]);
@@ -276,6 +219,6 @@
         if(ctuX > 0)
         {
-          mergedCTUPos = ctu- 1;
-          if( pic->getSAOMergeAvailability(ctu, mergedCTUPos) )
+          mergedCTUPos = ctuRsAddr- 1;
+          if( pic->getSAOMergeAvailability(ctuRsAddr, mergedCTUPos) )
           {
             mergeCandidate = &(blkParams[mergedCTUPos]);
@@ -292,5 +235,5 @@
     }
 
-    mergeList.push_back(mergeCandidate);
+    mergeList[mergeType]=mergeCandidate;
     if (mergeCandidate != NULL)
     {
@@ -303,9 +246,11 @@
 
 
-Void TComSampleAdaptiveOffset::reconstructBlkSAOParam(SAOBlkParam& recParam, std::vector<SAOBlkParam*>& mergeList)
-{
-  for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
-  {
-    SAOOffset& offsetParam = recParam[compIdx];
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParam(SAOBlkParam& recParam, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES])
+{
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    const ComponentID component = ComponentID(compIdx);
+    SAOOffset& offsetParam = recParam[component];
 
     if(offsetParam.modeIdc == SAO_MODE_OFF)
@@ -318,5 +263,5 @@
     case SAO_MODE_NEW:
       {
-        invertQuantOffsets(compIdx, offsetParam.typeIdc, offsetParam.typeAuxInfo, offsetParam.offset, offsetParam.offset);
+        invertQuantOffsets(component, offsetParam.typeIdc, offsetParam.typeAuxInfo, offsetParam.offset, offsetParam.offset);
       }
       break;
@@ -326,5 +271,5 @@
         assert(mergeTarget != NULL);
 
-        offsetParam = (*mergeTarget)[compIdx];
+        offsetParam = (*mergeTarget)[component];
       }
       break;
@@ -341,16 +286,21 @@
 Void TComSampleAdaptiveOffset::reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams)
 {
-  m_picSAOEnabled[SAO_Y] = m_picSAOEnabled[SAO_Cb] = m_picSAOEnabled[SAO_Cr] = false;
-
-  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
-  {
-    std::vector<SAOBlkParam*> mergeList;
-    getMergeList(pic, ctu, saoBlkParams, mergeList);
-
-    reconstructBlkSAOParam(saoBlkParams[ctu], mergeList);
-
-    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
-    {
-      if(saoBlkParams[ctu][compIdx].modeIdc != SAO_MODE_OFF)
+  for(Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+  {
+    m_picSAOEnabled[compIdx] = false;
+  }
+
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+
+  for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
+  {
+    SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES] = { NULL };
+    getMergeList(pic, ctuRsAddr, saoBlkParams, mergeList);
+
+    reconstructBlkSAOParam(saoBlkParams[ctuRsAddr], mergeList);
+
+    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+    {
+      if(saoBlkParams[ctuRsAddr][compIdx].modeIdc != SAO_MODE_OFF)
       {
         m_picSAOEnabled[compIdx] = true;
@@ -358,10 +308,8 @@
     }
   }
-
-
-}
-
-
-Void TComSampleAdaptiveOffset::offsetBlock(Int compIdx, Int typeIdx, Int* offset  
+}
+
+
+Void TComSampleAdaptiveOffset::offsetBlock(const Int channelBitDepth, Int typeIdx, Int* offset
                                           , Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
                                           , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail)
@@ -370,13 +318,21 @@
   {
     m_lineBufWidth = m_maxCUWidth;
-    
-    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+
+    if (m_signLineBuf1)
+    {
+      delete[] m_signLineBuf1;
+      m_signLineBuf1 = NULL;
+    }
     m_signLineBuf1 = new Char[m_lineBufWidth+1];
-    
-    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+
+    if (m_signLineBuf2)
+    {
+      delete[] m_signLineBuf2;
+      m_signLineBuf2 = NULL;
+    }
     m_signLineBuf2 = new Char[m_lineBufWidth+1];
   }
 
-  Int* offsetClip = m_offsetClip[compIdx];
+  const Int maxSampleValueIncl = (1<< channelBitDepth )-1;
 
   Int x,y, startX, startY, endX, endY, edgeType;
@@ -396,20 +352,12 @@
       for (y=0; y< height; y++)
       {
-#if SAO_SGN_FUNC
         signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
-#else
-        signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
-#endif
         for (x=startX; x< endX; x++)
         {
-#if SAO_SGN_FUNC
           signRight = (Char)sgn(srcLine[x] - srcLine[x+1]); 
-#else
-          signRight = (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
-#endif
           edgeType =  signRight + signLeft;
           signLeft  = -signRight;
 
-          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
         }
         srcLine  += srcStride;
@@ -435,9 +383,5 @@
       for (x=0; x< width; x++)
       {
-#if SAO_SGN_FUNC
         signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
-#else
-        signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
-#endif
       }
 
@@ -449,13 +393,9 @@
         for (x=0; x< width; x++)
         {
-#if SAO_SGN_FUNC
           signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]);
-#else
-          signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
-#endif
           edgeType = signDown + signUpLine[x];
           signUpLine[x]= -signDown;
 
-          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
         }
         srcLine += srcStride;
@@ -480,9 +420,5 @@
       for (x=startX; x< endX+1; x++)
       {
-#if SAO_SGN_FUNC
         signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x- 1]);
-#else
-        signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x- 1]];
-#endif
       }
 
@@ -493,10 +429,7 @@
       for(x= firstLineStartX; x< firstLineEndX; x++)
       {
-#if SAO_SGN_FUNC
         edgeType  =  sgn(srcLine[x] - srcLineAbove[x- 1]) - signUpLine[x+1];
-#else
-        edgeType  =  m_sign[srcLine[x] - srcLineAbove[x- 1]] - signUpLine[x+1];
-#endif
-        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+        resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
       }
       srcLine  += srcStride;
@@ -511,19 +444,11 @@
         for (x=startX; x<endX; x++)
         {
-#if SAO_SGN_FUNC
           signDown =  (Char)sgn(srcLine[x] - srcLineBelow[x+ 1]);
-#else
-          signDown =  (Char)m_sign[srcLine[x] - srcLineBelow[x+ 1]] ;
-#endif
           edgeType =  signDown + signUpLine[x];
-          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
-
-          signDownLine[x+1] = -signDown; 
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+
+          signDownLine[x+1] = -signDown;
         }
-#if SAO_SGN_FUNC
         signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
-#else
-        signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
-#endif
 
         signTmpLine  = signUpLine;
@@ -541,10 +466,6 @@
       for(x= lastLineStartX; x< lastLineEndX; x++)
       {
-#if SAO_SGN_FUNC
         edgeType =  sgn(srcLine[x] - srcLineBelow[x+ 1]) + signUpLine[x];
-#else
-        edgeType =  m_sign[srcLine[x] - srcLineBelow[x+ 1]] + signUpLine[x];
-#endif
-        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
 
       }
@@ -563,9 +484,5 @@
       for (x=startX-1; x< endX; x++)
       {
-#if SAO_SGN_FUNC
         signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
-#else
-        signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
-#endif
       }
 
@@ -577,10 +494,6 @@
       for(x= firstLineStartX; x< firstLineEndX; x++)
       {
-#if SAO_SGN_FUNC
         edgeType = sgn(srcLine[x] - srcLineAbove[x+1]) -signUpLine[x-1];
-#else
-        edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] -signUpLine[x-1];
-#endif
-        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
       }
       srcLine += srcStride;
@@ -594,18 +507,10 @@
         for(x= startX; x< endX; x++)
         {
-#if SAO_SGN_FUNC
           signDown =  (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
-#else
-          signDown =  (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
-#endif
           edgeType =  signDown + signUpLine[x];
-          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
-          signUpLine[x-1] = -signDown; 
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+          signUpLine[x-1] = -signDown;
         }
-#if SAO_SGN_FUNC
         signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
-#else
-        signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
-#endif
         srcLine  += srcStride;
         resLine += resStride;
@@ -618,10 +523,6 @@
       for(x= lastLineStartX; x< lastLineEndX; x++)
       {
-#if SAO_SGN_FUNC
         edgeType = sgn(srcLine[x] - srcLineBelow[x-1]) + signUpLine[x];
-#else
-        edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + signUpLine[x];
-#endif
-        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
 
       }
@@ -630,10 +531,10 @@
   case SAO_TYPE_BO:
     {
-      Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+      const Int shiftBits = channelBitDepth - NUM_SAO_BO_CLASSES_LOG2;
       for (y=0; y< height; y++)
       {
         for (x=0; x< width; x++)
         {
-          resLine[x] = offsetClip[ srcLine[x] + offset[srcLine[x] >> shiftBits] ];
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[srcLine[x] >> shiftBits] );
         }
         srcLine += srcStride;
@@ -649,17 +550,20 @@
     }
   }
-
-
-}
-
-Void TComSampleAdaptiveOffset::offsetCTU(Int ctu, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic)
+}
+
+Void TComSampleAdaptiveOffset::offsetCTU(Int ctuRsAddr, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic)
 {
   Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
 
-  if( 
-    (saoblkParam[SAO_Y ].modeIdc == SAO_MODE_OFF) &&
-    (saoblkParam[SAO_Cb].modeIdc == SAO_MODE_OFF) &&
-    (saoblkParam[SAO_Cr].modeIdc == SAO_MODE_OFF)
-    )
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  Bool bAllOff=true;
+  for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    if (saoblkParam[compIdx].modeIdc != SAO_MODE_OFF)
+    {
+      bAllOff=false;
+    }
+  }
+  if (bAllOff)
   {
     return;
@@ -667,32 +571,33 @@
 
   //block boundary availability
-  pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
-
-  Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
-  Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+  pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctuRsAddr, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+  Int yPos   = (ctuRsAddr / m_numCTUInWidth)*m_maxCUHeight;
+  Int xPos   = (ctuRsAddr % m_numCTUInWidth)*m_maxCUWidth;
   Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
   Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
 
-  for(Int compIdx= 0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
-  {
+  for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    const ComponentID component = ComponentID(compIdx);
     SAOOffset& ctbOffset = saoblkParam[compIdx];
 
     if(ctbOffset.modeIdc != SAO_MODE_OFF)
     {
-      Bool isLuma     = (compIdx == SAO_Y);
-      Int  formatShift= isLuma?0:1;
-
-      Int  blkWidth   = (width  >> formatShift);
-      Int  blkHeight  = (height >> formatShift);
-      Int  blkYPos    = (yPos   >> formatShift);
-      Int  blkXPos    = (xPos   >> formatShift);
-
-      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
-      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
-
-      Int  resStride  = isLuma?resYuv->getStride():resYuv->getCStride();
-      Pel* resBlk     = getPicBuf(resYuv, compIdx)+ blkYPos*resStride+ blkXPos;
-
-      offsetBlock( compIdx, ctbOffset.typeIdc, ctbOffset.offset
+      const UInt componentScaleX = getComponentScaleX(component, pPic->getChromaFormat());
+      const UInt componentScaleY = getComponentScaleY(component, pPic->getChromaFormat());
+
+      Int  blkWidth   = (width  >> componentScaleX);
+      Int  blkHeight  = (height >> componentScaleY);
+      Int  blkXPos    = (xPos   >> componentScaleX);
+      Int  blkYPos    = (yPos   >> componentScaleY);
+
+      Int  srcStride  = srcYuv->getStride(component);
+      Pel* srcBlk     = srcYuv->getAddr(component) + blkYPos*srcStride + blkXPos;
+
+      Int  resStride  = resYuv->getStride(component);
+      Pel* resBlk     = resYuv->getAddr(component) + blkYPos*resStride + blkXPos;
+
+      offsetBlock( pPic->getPicSym()->getSPS().getBitDepth(toChannelType(component)), ctbOffset.typeIdc, ctbOffset.offset
                   , srcBlk, resBlk, srcStride, resStride, blkWidth, blkHeight
                   , isLeftAvail, isRightAvail
@@ -709,52 +614,30 @@
 Void TComSampleAdaptiveOffset::SAOProcess(TComPic* pDecPic)
 {
-  if(!m_picSAOEnabled[SAO_Y] && !m_picSAOEnabled[SAO_Cb] && !m_picSAOEnabled[SAO_Cr])
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  Bool bAllDisabled=true;
+  for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    if (m_picSAOEnabled[compIdx])
+    {
+      bAllDisabled=false;
+    }
+  }
+  if (bAllDisabled)
   {
     return;
   }
+
   TComPicYuv* resYuv = pDecPic->getPicYuvRec();
   TComPicYuv* srcYuv = m_tempPicYuv;
   resYuv->copyToPic(srcYuv);
-  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
-  {
-    offsetCTU(ctu, srcYuv, resYuv, (pDecPic->getPicSym()->getSAOBlkParam())[ctu], pDecPic);
+  for(Int ctuRsAddr= 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
+  {
+    offsetCTU(ctuRsAddr, srcYuv, resYuv, (pDecPic->getPicSym()->getSAOBlkParam())[ctuRsAddr], pDecPic);
   } //ctu
 }
 
-
-Pel* TComSampleAdaptiveOffset::getPicBuf(TComPicYuv* pPicYuv, Int compIdx)
-{
-  Pel* pBuf = NULL;
-  switch(compIdx)
-  {
-  case SAO_Y:
-    {
-      pBuf = pPicYuv->getLumaAddr();
-    }
-    break;
-  case SAO_Cb:
-    {
-      pBuf = pPicYuv->getCbAddr();
-    }
-    break;
-  case SAO_Cr:
-    {
-      pBuf = pPicYuv->getCrAddr();
-    }
-    break;
-  default:
-    {
-      printf("Not a legal component ID for SAO\n");
-      assert(0);
-      exit(-1);
-    }
-  }
-
-  return pBuf;
-}
 
 /** PCM LF disable process.
  * \param pcPic picture (TComPic) pointer
- * \returns Void
  *
  * \note Replace filtered sample values of PCM mode blocks with the transmitted and reconstructed ones.
@@ -765,7 +648,6 @@
 }
 
-/** Picture-level PCM restoration. 
+/** Picture-level PCM restoration.
  * \param pcPic picture (TComPic) pointer
- * \returns Void
  */
 Void TComSampleAdaptiveOffset::xPCMRestoration(TComPic* pcPic)
@@ -775,23 +657,22 @@
   if(bPCMFilter || pcPic->getSlice(0)->getPPS()->getTransquantBypassEnableFlag())
   {
-    for( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame() ; uiCUAddr++ )
-    {
-      TComDataCU* pcCU = pcPic->getCU(uiCUAddr);
-
-      xPCMCURestoration(pcCU, 0, 0); 
-    } 
-  }
-}
-
-/** PCM CU restoration. 
- * \param pcCU pointer to current CU
- * \param uiAbsPartIdx part index
- * \param uiDepth CU depth
- * \returns Void
+    for( UInt ctuRsAddr = 0; ctuRsAddr < pcPic->getNumberOfCtusInFrame() ; ctuRsAddr++ )
+    {
+      TComDataCU* pcCU = pcPic->getCtu(ctuRsAddr);
+
+      xPCMCURestoration(pcCU, 0, 0);
+    }
+  }
+}
+
+/** PCM CU restoration.
+ * \param pcCU            pointer to current CU
+ * \param uiAbsZorderIdx  part index
+ * \param uiDepth         CU depth
  */
 Void TComSampleAdaptiveOffset::xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth )
 {
   TComPic* pcPic     = pcCU->getPic();
-  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiCurNumParts = pcPic->getNumPartitionsInCtu() >> (uiDepth<<1);
   UInt uiQNumParts   = uiCurNumParts>>2;
 
@@ -804,5 +685,7 @@
       UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
       if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+      {
         xPCMCURestoration( pcCU, uiAbsZorderIdx, uiDepth+1 );
+      }
     }
     return;
@@ -812,76 +695,46 @@
   if ((pcCU->getIPCMFlag(uiAbsZorderIdx)&& pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag()) || pcCU->isLosslessCoded( uiAbsZorderIdx))
   {
-    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_LUMA    );
-    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_CHROMA_U);
-    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_CHROMA_V);
-  }
-}
-
-/** PCM sample restoration. 
- * \param pcCU pointer to current CU
- * \param uiAbsPartIdx part index
- * \param uiDepth CU depth
- * \param ttText texture component type
- * \returns Void
+    const UInt numComponents=pcPic->getNumberValidComponents();
+    for(UInt comp=0; comp<numComponents; comp++)
+    {
+      xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, ComponentID(comp));
+    }
+  }
+}
+
+/** PCM sample restoration.
+ * \param pcCU           pointer to current CU
+ * \param uiAbsZorderIdx part index
+ * \param uiDepth        CU depth
+ * \param compID         texture component type
  */
-Void TComSampleAdaptiveOffset::xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText)
-{
-  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
-  Pel* piSrc;
-  Pel* piPcm;
-  UInt uiStride;
-  UInt uiWidth;
-  UInt uiHeight;
-  UInt uiPcmLeftShiftBit; 
-  UInt uiX, uiY;
-  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
-  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsZorderIdx;
-  UInt uiChromaOffset = uiLumaOffset>>2;
-
-  if( ttText == TEXT_LUMA )
-  {
-    piSrc = pcPicYuvRec->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx);
-    piPcm = pcCU->getPCMSampleY() + uiLumaOffset;
-    uiStride  = pcPicYuvRec->getStride();
-    uiWidth  = (g_uiMaxCUWidth >> uiDepth);
-    uiHeight = (g_uiMaxCUHeight >> uiDepth);
-    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) && !pcCU->getIPCMFlag(uiAbsZorderIdx) )
-    {
-      uiPcmLeftShiftBit = 0;
-    }
-    else
-    {
-      uiPcmLeftShiftBit = g_bitDepthY - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
-    }
+Void TComSampleAdaptiveOffset::xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, const ComponentID compID)
+{
+        TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+        UInt uiPcmLeftShiftBit;
+  const UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  const UInt csx=pcPicYuvRec->getComponentScaleX(compID);
+  const UInt csy=pcPicYuvRec->getComponentScaleY(compID);
+  const UInt uiOffset   = (uiMinCoeffSize*uiAbsZorderIdx)>>(csx+csy);
+
+        Pel *piSrc = pcPicYuvRec->getAddr(compID, pcCU->getCtuRsAddr(), uiAbsZorderIdx);
+  const Pel *piPcm = pcCU->getPCMSample(compID) + uiOffset;
+  const UInt uiStride  = pcPicYuvRec->getStride(compID);
+  const TComSPS &sps = *(pcCU->getSlice()->getSPS());
+  const UInt uiWidth  = ((sps.getMaxCUWidth()  >> uiDepth) >> csx);
+  const UInt uiHeight = ((sps.getMaxCUHeight() >> uiDepth) >> csy);
+
+  if ( pcCU->isLosslessCoded(uiAbsZorderIdx) && !pcCU->getIPCMFlag(uiAbsZorderIdx) )
+  {
+    uiPcmLeftShiftBit = 0;
   }
   else
   {
-    if( ttText == TEXT_CHROMA_U )
-    {
-      piSrc = pcPicYuvRec->getCbAddr( pcCU->getAddr(), uiAbsZorderIdx );
-      piPcm = pcCU->getPCMSampleCb() + uiChromaOffset;
-    }
-    else
-    {
-      piSrc = pcPicYuvRec->getCrAddr( pcCU->getAddr(), uiAbsZorderIdx );
-      piPcm = pcCU->getPCMSampleCr() + uiChromaOffset;
-    }
-
-    uiStride = pcPicYuvRec->getCStride();
-    uiWidth  = ((g_uiMaxCUWidth >> uiDepth)/2);
-    uiHeight = ((g_uiMaxCUWidth >> uiDepth)/2);
-    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) && !pcCU->getIPCMFlag(uiAbsZorderIdx) )
-    {
-      uiPcmLeftShiftBit = 0;
-    }
-    else
-    {
-      uiPcmLeftShiftBit = g_bitDepthC - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
-    }
-  }
-
-  for( uiY = 0; uiY < uiHeight; uiY++ )
-  {
-    for( uiX = 0; uiX < uiWidth; uiX++ )
+    uiPcmLeftShiftBit = sps.getBitDepth(toChannelType(compID)) - sps.getPCMBitDepth(toChannelType(compID));
+  }
+
+  for(UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for(UInt uiX = 0; uiX < uiWidth; uiX++ )
     {
       piSrc[uiX] = (piPcm[uiX] << uiPcmLeftShiftBit);
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1200)
@@ -2,5 +2,5 @@
  * 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.  
+ * granted under this license.
  *
  * Copyright (c) 2010-2015, ITU/ISO/IEC
@@ -45,20 +45,19 @@
 //! \{
 
+
 // ====================================================================================================================
 // Constants
 // ====================================================================================================================
 
-#define MAX_SAO_TRUNCATED_BITDEPTH     10 
+#define MAX_SAO_TRUNCATED_BITDEPTH     10
+
 // ====================================================================================================================
 // Class definition
 // ====================================================================================================================
-extern UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS]; 
 
-#if SAO_SGN_FUNC
-template <typename T> int sgn(T val) 
+template <typename T> Int sgn(T val)
 {
   return (T(0) < val) - (val < T(0));
 }
-#endif
 
 class TComSampleAdaptiveOffset
@@ -68,25 +67,22 @@
   virtual ~TComSampleAdaptiveOffset();
   Void SAOProcess(TComPic* pDecPic);
-  Void create( Int picWidth, Int picHeight, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth );
+  Void create( Int picWidth, Int picHeight, ChromaFormat format, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth, UInt lumaBitShift, UInt chromaBitShift );
   Void destroy();
   Void reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams);
   Void PCMLFDisableProcess (TComPic* pcPic);
+  static Int getMaxOffsetQVal(const Int channelBitDepth) { return (1<<(std::min<Int>(channelBitDepth,MAX_SAO_TRUNCATED_BITDEPTH)-5))-1; } //Table 9-32, inclusive
+
 protected:
-  Void offsetBlock(Int compIdx, Int typeIdx, Int* offset, Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+  Void offsetBlock(const Int channelBitDepth, Int typeIdx, Int* offset, Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
                   , Bool isLeftAvail, Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail);
-  Pel* getPicBuf(TComPicYuv* pPicYuv, Int compIdx);
-  Void invertQuantOffsets(Int compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets);
-  Void reconstructBlkSAOParam(SAOBlkParam& recParam, std::vector<SAOBlkParam*>& mergeList);
-  Int  getMergeList(TComPic* pic, Int ctu, SAOBlkParam* blkParams, std::vector<SAOBlkParam*>& mergeList);
-  Void offsetCTU(Int ctu, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic);
+  Void invertQuantOffsets(ComponentID compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets);
+  Void reconstructBlkSAOParam(SAOBlkParam& recParam, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES]);
+  Int  getMergeList(TComPic* pic, Int ctuRsAddr, SAOBlkParam* blkParams, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES]);
+  Void offsetCTU(Int ctuRsAddr, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic);
   Void xPCMRestoration(TComPic* pcPic);
   Void xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth );
-  Void xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
+  Void xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, const ComponentID compID);
 protected:
-  UInt m_offsetStepLog2[NUM_SAO_COMPONENTS]; //offset step  
-  Int* m_offsetClip[NUM_SAO_COMPONENTS]; //clip table for fast operation
-#if !SAO_SGN_FUNC
-  Short* m_sign; //sign table for fast operation
-#endif
+  UInt m_offsetStepLog2[MAX_NUM_COMPONENT]; //offset step
   TComPicYuv*   m_tempPicYuv; //temporary buffer
   Int m_picWidth;
@@ -97,15 +93,12 @@
   Int m_numCTUInHeight;
   Int m_numCTUsPic;
-  
-  
+
+
   Int m_lineBufWidth;
   Char* m_signLineBuf1;
   Char* m_signLineBuf2;
+  ChromaFormat m_chromaFormatIDC;
 private:
-  Bool m_picSAOEnabled[NUM_SAO_COMPONENTS];
-  Int*   m_offsetClipTable[NUM_SAO_COMPONENTS];
-#if !SAO_SGN_FUNC
-  Short* m_signTable;
-#endif
+  Bool m_picSAOEnabled[MAX_NUM_COMPONENT];
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSlice.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSlice.cpp	(revision 1200)
@@ -1,8 +1,8 @@
-/*  The copyright in this software is being made available under the BSD
+/* The copyright in this software is being made available under the 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -42,73 +42,81 @@
 #include "TLibDecoder/TDecSbac.h"
 
+
 //! \ingroup TLibCommon
 //! \{
 
-
 TComSlice::TComSlice()
 : m_iPPSId                        ( -1 )
-#if H_MV
+, m_PicOutputFlag                 ( true )
+#if NH_MV
 , m_slicePicOrderCntLsb           ( 0 )
 #endif
 , m_iPOC                          ( 0 )
 , m_iLastIDR                      ( 0 )
+, m_iAssociatedIRAP               ( 0 )
+, m_iAssociatedIRAPType           ( NAL_UNIT_INVALID )
+, m_pcRPS                         ( 0 )
+, m_LocalRPS                      ( )
+, m_iBDidx                        ( 0 )
+, m_RefPicListModification        ( )
 , m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR_W_RADL )
 , m_eSliceType                    ( I_SLICE )
 , m_iSliceQp                      ( 0 )
-, m_dependentSliceSegmentFlag            ( false )
+, m_dependentSliceSegmentFlag     ( false )
 #if ADAPTIVE_QP_SELECTION
 , m_iSliceQpBase                  ( 0 )
 #endif
-, m_deblockingFilterDisable        ( false )
-, m_deblockingFilterOverrideFlag   ( false )
-, m_deblockingFilterBetaOffsetDiv2 ( 0 )
-, m_deblockingFilterTcOffsetDiv2   ( 0 )
+, m_ChromaQpAdjEnabled            ( false )
+, m_deblockingFilterDisable       ( false )
+, m_deblockingFilterOverrideFlag  ( false )
+, m_deblockingFilterBetaOffsetDiv2( 0 )
+, m_deblockingFilterTcOffsetDiv2  ( 0 )
 , m_bCheckLDC                     ( false )
 , m_iSliceQpDelta                 ( 0 )
-, m_iSliceQpDeltaCb               ( 0 )
-, m_iSliceQpDeltaCr               ( 0 )
 , m_iDepth                        ( 0 )
 , m_bRefenced                     ( false )
+, m_pcVPS                         ( NULL )
 , m_pcSPS                         ( NULL )
 , m_pcPPS                         ( NULL )
 , m_pcPic                         ( NULL )
-, m_colFromL0Flag                 ( 1 )
-#if SETTING_NO_OUT_PIC_PRIOR
+, m_colFromL0Flag                 ( true )
 , m_noOutputPriorPicsFlag         ( false )
 , m_noRaslOutputFlag              ( false )
-, m_handleCraAsBlaFlag              ( false )
-#endif
+, m_handleCraAsBlaFlag            ( false )
 , m_colRefIdx                     ( 0 )
+, m_maxNumMergeCand               ( 0 )
 , m_uiTLayer                      ( 0 )
 , m_bTLayerSwitchingFlag          ( false )
-, m_sliceMode                   ( 0 )
-, m_sliceArgument               ( 0 )
-, m_sliceCurStartCUAddr         ( 0 )
-, m_sliceCurEndCUAddr           ( 0 )
-, m_sliceIdx                    ( 0 )
-, m_sliceSegmentMode            ( 0 )
-, m_sliceSegmentArgument        ( 0 )
-, m_sliceSegmentCurStartCUAddr  ( 0 )
-, m_sliceSegmentCurEndCUAddr    ( 0 )
-, m_nextSlice                    ( false )
-, m_nextSliceSegment             ( false )
-, m_sliceBits                   ( 0 )
-, m_sliceSegmentBits         ( 0 )
+, m_sliceMode                     ( NO_SLICES )
+, m_sliceArgument                 ( 0 )
+, m_sliceCurStartCtuTsAddr        ( 0 )
+, m_sliceCurEndCtuTsAddr          ( 0 )
+, m_sliceIdx                      ( 0 )
+, m_sliceSegmentMode              ( NO_SLICES )
+, m_sliceSegmentArgument          ( 0 )
+, m_sliceSegmentCurStartCtuTsAddr ( 0 )
+, m_sliceSegmentCurEndCtuTsAddr   ( 0 )
+, m_nextSlice                     ( false )
+, m_nextSliceSegment              ( false )
+, m_sliceBits                     ( 0 )
+, m_sliceSegmentBits              ( 0 )
 , m_bFinalized                    ( false )
-, m_uiTileOffstForMultES          ( 0 )
-, m_puiSubstreamSizes             ( NULL )
+, m_bTestWeightPred               ( false )
+, m_bTestWeightBiPred             ( false )
+, m_substreamSizes                ( )
 , m_cabacInitFlag                 ( false )
 , m_bLMvdL1Zero                   ( false )
-, m_numEntryPointOffsets          ( 0 )
 , m_temporalLayerNonReferenceFlag ( false )
+, m_LFCrossSliceBoundaryFlag      ( false )
 , m_enableTMVPFlag                ( true )
-#if H_MV
+, m_encCABACTableIdx              (I_SLICE)
+#if NH_MV
 , m_availableForTMVPRefFlag       ( true )
-, m_refPicSetInterLayer0           ( NULL )
-, m_refPicSetInterLayer1           ( NULL )
+, m_refPicSetInterLayer0          ( NULL )
+, m_refPicSetInterLayer1          ( NULL )
 , m_layerId                       (0)
 , m_viewId                        (0)
 , m_viewIndex                     (0)
-#if H_3D
+#if NH_3D
 , m_isDepth                       (false)
 #endif
@@ -116,5 +124,5 @@
 , m_pocResetFlag                  (false)
 #endif
-#if H_MV
+#if NH_MV
 , m_crossLayerBlaFlag             (false)
 #endif
@@ -122,57 +130,68 @@
 , m_interLayerPredEnabledFlag     (false)
 , m_numInterLayerRefPicsMinus1    (0)
-#if H_MV
+#if NH_MV
 , m_sliceSegmentHeaderExtensionLength (0)
-, m_pocResetIdc                       (0)
-, m_pocResetPeriodId                  (0)
-, m_fullPocResetFlag                  (false)
-, m_pocLsbVal                         (0)
-, m_pocMsbValPresentFlag              (false)
-, m_pocMsbVal                         (0)
-, m_pocMsbValRequiredFlag         ( false )
+, m_pocResetIdc                   (0)
+, m_pocResetPeriodId              (0)
+, m_fullPocResetFlag              (false)
+, m_pocLsbVal                     (0)
+, m_pocMsbValPresentFlag          (false)
+, m_pocMsbVal                     (0)
+, m_pocMsbValRequiredFlag         (false)
 #endif
 #if H_3D_IC
-, m_bApplyIC                      ( false )
-, m_icSkipParseFlag               ( false )
+, m_bApplyIC                      (false)
+, m_icSkipParseFlag               (false)
+#endif
+#if NH_3D
+, m_inCmpPredFlag                 (false)
+, m_numViews                      (0)
+, m_depthToDisparityB             (NULL)
+, m_depthToDisparityF             (NULL)
 #endif
 #if H_3D
-, m_inCmpPredFlag                 ( false )
-, m_numViews                        ( 0    )
-, m_depthToDisparityB             ( NULL )
-, m_depthToDisparityF             ( NULL )
-
 , m_bApplyDIS                     (false)
 #endif
 #endif
 {
-  m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = 0;
-  
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_aiNumRefIdx[i] = 0;
+  }
+
+  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
+  {
+    m_lambdas            [component] = 0.0;
+    m_iSliceChromaQpDelta[component] = 0;
+  }
+
   initEqualRef();
-  
-  for (Int component = 0; component < 3; component++)
-  {
-    m_lambdas[component] = 0.0;
-  }
-  
+
   for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
   {
     m_list1IdxToList0Idx[idx] = -1;
   }
+
   for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
   {
-    m_apcRefPicList [0][iNumCount] = NULL;
-    m_apcRefPicList [1][iNumCount] = NULL;
-    m_aiRefPOCList  [0][iNumCount] = 0;
-    m_aiRefPOCList  [1][iNumCount] = 0;
-#if H_MV
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_apcRefPicList [i][iNumCount] = NULL;
+      m_aiRefPOCList  [i][iNumCount] = 0;
+    }
+#if NH_MV
     m_aiRefLayerIdList[0][iNumCount] = 0;
     m_aiRefLayerIdList[1][iNumCount] = 0;
 #endif
   }
+
   resetWpScaling();
   initWpAcDcParam();
-  m_saoEnabledFlag = false;
-  m_saoEnabledFlagChroma = false;
-#if H_MV
+
+  for(Int ch=0; ch < MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_saoEnabledFlag[ch] = false;
+  }
+#if NH_MV
   for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
   {
@@ -180,7 +199,7 @@
   }
 #endif
+#if NH_3D
   m_iDefaultRefViewIdx = -1;
   m_bDefaultRefViewIdxAvailableFlag = false;
-#if H_3D
   m_ivMvPredFlag           = false;
   m_ivMvScalingFlag        = false;
@@ -197,12 +216,20 @@
   m_subPbSize              =  1 << 6;
   m_mpiSubPbSize           =  1 << 6;
-#endif
+
+  m_aaiCodedOffset.resize(2);
+  m_aaiCodedScale .resize(2);
+  for (Int i = 0; i < 2; i++)
+  {
+    m_aaiCodedOffset[i].resize(MAX_NUM_LAYERS);
+    m_aaiCodedScale [i].resize(MAX_NUM_LAYERS);
+  }
+  
+#endif
+
 }
 
 TComSlice::~TComSlice()
 {
-  delete[] m_puiSubstreamSizes;
-  m_puiSubstreamSizes = NULL;
-#if H_3D
+#if NH_3D
   for( UInt i = 0; i < m_numViews; i++ )
   {
@@ -230,4 +257,5 @@
   m_depthToDisparityB = NULL;
 #endif
+
 }
 
@@ -235,15 +263,19 @@
 Void TComSlice::initSlice()
 {
-  m_aiNumRefIdx[0]      = 0;
-  m_aiNumRefIdx[1]      = 0;
-  
-  m_colFromL0Flag = 1;
-  
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_aiNumRefIdx[i]      = 0;
+  }
+  m_colFromL0Flag = true;
+
   m_colRefIdx = 0;
   initEqualRef();
+
   m_bCheckLDC = false;
-  m_iSliceQpDeltaCb = 0;
-  m_iSliceQpDeltaCr = 0;
-
+
+  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
+  {
+    m_iSliceChromaQpDelta[component] = 0;
+  }
 #if H_3D_IV_MERGE
   m_maxNumMergeCand = MRG_MAX_NUM_CANDS_MEM;
@@ -254,7 +286,6 @@
   m_bFinalized=false;
 
-  m_tileByteLocation.clear();
+  m_substreamSizes.clear();
   m_cabacInitFlag        = false;
-  m_numEntryPointOffsets = 0;
   m_enableTMVPFlag = true;
 #if H_3D_TMVP
@@ -264,5 +295,5 @@
 }
 
-Bool TComSlice::getRapPicFlag()
+Bool TComSlice::getRapPicFlag() const
 {
   return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
@@ -274,14 +305,4 @@
 }
 
-/**
- - allocate table to contain substream sizes to be written to the slice header.
- .
- \param uiNumSubstreams Number of substreams -- the allocation will be this value - 1.
- */
-Void  TComSlice::allocSubstreamSizes(UInt uiNumSubstreams)
-{
-  delete[] m_puiSubstreamSizes;
-  m_puiSubstreamSizes = new UInt[uiNumSubstreams > 0 ? uiNumSubstreams-1 : 0];
-}
 
 Void  TComSlice::sortPicList        (TComList<TComPic*>& rcListPic)
@@ -289,16 +310,19 @@
   TComPic*    pcPicExtract;
   TComPic*    pcPicInsert;
-  
+
   TComList<TComPic*>::iterator    iterPicExtract;
   TComList<TComPic*>::iterator    iterPicExtract_1;
   TComList<TComPic*>::iterator    iterPicInsert;
-  
+
   for (Int i = 1; i < (Int)(rcListPic.size()); i++)
   {
     iterPicExtract = rcListPic.begin();
-    for (Int j = 0; j < i; j++) iterPicExtract++;
+    for (Int j = 0; j < i; j++)
+    {
+      iterPicExtract++;
+    }
     pcPicExtract = *(iterPicExtract);
     pcPicExtract->setCurrSliceIdx(0);
-    
+
     iterPicInsert = rcListPic.begin();
     while (iterPicInsert != iterPicExtract)
@@ -310,10 +334,10 @@
         break;
       }
-      
+
       iterPicInsert++;
     }
-    
+
     iterPicExtract_1 = iterPicExtract;    iterPicExtract_1++;
-    
+
     //  swap iterPicExtract and iterPicInsert, iterPicExtract = curr. / iterPicInsert = insertion position
     rcListPic.insert (iterPicInsert, iterPicExtract, iterPicExtract_1);
@@ -322,8 +346,7 @@
 }
 
-TComPic* TComSlice::xGetRefPic (TComList<TComPic*>& rcListPic,
-                                Int                 poc)
-{
-  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+TComPic* TComSlice::xGetRefPic (TComList<TComPic*>& rcListPic, Int poc)
+{
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
   TComPic*                      pcPic = *(iterPic);
   while ( iterPic != rcListPic.end() )
@@ -342,8 +365,8 @@
 TComPic* TComSlice::xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb)
 {
-  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
   TComPic*                      pcPic = *(iterPic);
   TComPic*                      pcStPic = pcPic;
-  
+
   Int pocCycle = 1 << getSPS()->getBitsForPOC();
   if (!pocHasMsb)
@@ -351,5 +374,5 @@
     poc = poc & (pocCycle - 1);
   }
-  
+
   while ( iterPic != rcListPic.end() )
   {
@@ -362,22 +385,22 @@
         picPoc = picPoc & (pocCycle - 1);
       }
-      
+
       if (poc == picPoc)
-    {
-      if(pcPic->getIsLongTerm())
-      {
-        return pcPic;
-      }
-      else
-      {
-        pcStPic = pcPic;
-      }
-      break;
-    }
+      {
+        if(pcPic->getIsLongTerm())
+        {
+          return pcPic;
+        }
+        else
+        {
+          pcStPic = pcPic;
+        }
+        break;
+      }
     }
 
     iterPic++;
   }
-  
+
   return  pcStPic;
 }
@@ -385,10 +408,10 @@
 Void TComSlice::setRefPOCList       ()
 {
-  for (Int iDir = 0; iDir < 2; iDir++)
+  for (Int iDir = 0; iDir < NUM_REF_PIC_LIST_01; iDir++)
   {
     for (Int iNumRefIdx = 0; iNumRefIdx < m_aiNumRefIdx[iDir]; iNumRefIdx++)
     {
       m_aiRefPOCList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getPOC();
-#if H_MV
+#if NH_MV
       m_aiRefLayerIdList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getLayerId();
 #endif
@@ -415,5 +438,5 @@
 }
 
-#if !H_MV
+#if !NH_MV
 Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
 {
@@ -428,6 +451,160 @@
     }
 
+    m_aiNumRefIdx[REF_PIC_LIST_0] = getNumRefIdx(REF_PIC_LIST_0);
+    m_aiNumRefIdx[REF_PIC_LIST_1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
+
+  TComPic*  pcRefPic= NULL;
+  static const UInt MAX_NUM_NEGATIVE_PICTURES=16;
+  TComPic*  RefPicSetStCurr0[MAX_NUM_NEGATIVE_PICTURES];
+  TComPic*  RefPicSetStCurr1[MAX_NUM_NEGATIVE_PICTURES];
+  TComPic*  RefPicSetLtCurr[MAX_NUM_NEGATIVE_PICTURES];
+  UInt NumPicStCurr0 = 0;
+  UInt NumPicStCurr1 = 0;
+  UInt NumPicLtCurr = 0;
+  Int i;
+
+  for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
+      pcRefPic->setIsLongTerm(0);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetStCurr0[NumPicStCurr0] = pcRefPic;
+      NumPicStCurr0++;
+      pcRefPic->setCheckLTMSBPresent(false);
+    }
+  }
+
+  for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
+      pcRefPic->setIsLongTerm(0);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetStCurr1[NumPicStCurr1] = pcRefPic;
+      NumPicStCurr1++;
+      pcRefPic->setCheckLTMSBPresent(false);
+    }
+  }
+
+  for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
+      pcRefPic->setIsLongTerm(1);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetLtCurr[NumPicLtCurr] = pcRefPic;
+      NumPicLtCurr++;
+    }
+    if(pcRefPic==NULL)
+    {
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
+    }
+    pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i));
+  }
+
+  // ref_pic_list_init
+  TComPic*  rpsCurrList0[MAX_NUM_REF+1];
+  TComPic*  rpsCurrList1[MAX_NUM_REF+1];
+  Int numPicTotalCurr = NumPicStCurr0 + NumPicStCurr1 + NumPicLtCurr;
+
+  if (checkNumPocTotalCurr)
+  {
+    // The variable NumPocTotalCurr is derived as specified in subclause 7.4.7.2. It is a requirement of bitstream conformance that the following applies to the value of NumPocTotalCurr:
+    // - If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
+    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
+    if (getRapPicFlag())
+    {
+      assert(numPicTotalCurr == 0);
+    }
+
+    if (m_eSliceType == I_SLICE)
+    {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+
+      return;
+    }
+
+    assert(numPicTotalCurr > 0);
+    // general tier and level limit:
+    assert(numPicTotalCurr <= 8);
+
     m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
     m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
+
+  Int cIdx = 0;
+  for ( i=0; i<NumPicStCurr0; i++, cIdx++)
+  {
+    rpsCurrList0[cIdx] = RefPicSetStCurr0[i];
+  }
+  for ( i=0; i<NumPicStCurr1; i++, cIdx++)
+  {
+    rpsCurrList0[cIdx] = RefPicSetStCurr1[i];
+  }
+  for ( i=0; i<NumPicLtCurr;  i++, cIdx++)
+  {
+    rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
+  }
+  assert(cIdx == numPicTotalCurr);
+
+  if (m_eSliceType==B_SLICE)
+  {
+    cIdx = 0;
+    for ( i=0; i<NumPicStCurr1; i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetStCurr1[i];
+    }
+    for ( i=0; i<NumPicStCurr0; i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetStCurr0[i];
+    }
+    for ( i=0; i<NumPicLtCurr;  i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetLtCurr[i];
+    }
+    assert(cIdx == numPicTotalCurr);
+  }
+
+  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
+
+  for (Int rIdx = 0; rIdx < m_aiNumRefIdx[REF_PIC_LIST_0]; rIdx ++)
+  {
+    cIdx = m_RefPicListModification.getRefPicListModificationFlagL0() ? m_RefPicListModification.getRefPicSetIdxL0(rIdx) : rIdx % numPicTotalCurr;
+    assert(cIdx >= 0 && cIdx < numPicTotalCurr);
+    m_apcRefPicList[REF_PIC_LIST_0][rIdx] = rpsCurrList0[ cIdx ];
+    m_bIsUsedAsLongTerm[REF_PIC_LIST_0][rIdx] = ( cIdx >= NumPicStCurr0 + NumPicStCurr1 );
+  }
+  if ( m_eSliceType != B_SLICE )
+  {
+    m_aiNumRefIdx[REF_PIC_LIST_1] = 0;
+    ::memset( m_apcRefPicList[REF_PIC_LIST_1], 0, sizeof(m_apcRefPicList[REF_PIC_LIST_1]));
+  }
+  else
+  {
+    for (Int rIdx = 0; rIdx < m_aiNumRefIdx[REF_PIC_LIST_1]; rIdx ++)
+    {
+      cIdx = m_RefPicListModification.getRefPicListModificationFlagL1() ? m_RefPicListModification.getRefPicSetIdxL1(rIdx) : rIdx % numPicTotalCurr;
+      assert(cIdx >= 0 && cIdx < numPicTotalCurr);
+      m_apcRefPicList[REF_PIC_LIST_1][rIdx] = rpsCurrList1[ cIdx ];
+      m_bIsUsedAsLongTerm[REF_PIC_LIST_1][rIdx] = ( cIdx >= NumPicStCurr0 + NumPicStCurr1 );
+    }
+  }
+}
+#else
+Void TComSlice::getTempRefPicLists( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1,                                     
+                                   std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int& numPocTotalCurr, Bool checkNumPocTotalCurr )
+{
+  if (!checkNumPocTotalCurr)
+  {
+    if (m_eSliceType == I_SLICE)
+    {      
+      return;
+    }    
   }
 
@@ -440,5 +617,7 @@
   UInt NumPocLtCurr = 0;
   Int i;
-
+#if NH_3D
+  m_pocsInCurrRPSs.clear();
+#endif
   for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
   {
@@ -451,7 +630,10 @@
       NumPocStCurr0++;
       pcRefPic->setCheckLTMSBPresent(false);  
-    }
-  }
-
+#if NH_3D
+      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
+#endif
+    }
+  }
+  
   for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
   {
@@ -464,7 +646,10 @@
       NumPocStCurr1++;
       pcRefPic->setCheckLTMSBPresent(false);  
-    }
-  }
-
+#if NH_3D
+      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
+#endif
+    }
+  }
+  
   for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
   {
@@ -476,4 +661,7 @@
       RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
       NumPocLtCurr++;
+#if NH_3D
+      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
+#endif
     }
     if(pcRefPic==NULL) 
@@ -484,168 +672,6 @@
   }
 
-  // ref_pic_list_init
-  TComPic*  rpsCurrList0[MAX_NUM_REF+1];
-  TComPic*  rpsCurrList1[MAX_NUM_REF+1];
-  Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
-  if (checkNumPocTotalCurr)
-  {
-    // The variable NumPocTotalCurr is derived as specified in subclause 7.4.7.2. It is a requirement of bitstream conformance that the following applies to the value of NumPocTotalCurr:
-    // - If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
-    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
-    if (getRapPicFlag())
-    {
-      assert(numPocTotalCurr == 0);
-    }
-
-    if (m_eSliceType == I_SLICE)
-    {
-      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
-      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
-
-      return;
-    }
-
-    assert(numPocTotalCurr > 0);
-
-    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
-    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
-  }
-
-  Int cIdx = 0;
-  for ( i=0; i<NumPocStCurr0; i++, cIdx++)
-  {
-    rpsCurrList0[cIdx] = RefPicSetStCurr0[i];
-  }
-  for ( i=0; i<NumPocStCurr1; i++, cIdx++)
-  {
-    rpsCurrList0[cIdx] = RefPicSetStCurr1[i];
-  }
-  for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
-  {
-    rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
-  }
-  assert(cIdx == numPocTotalCurr);
-
-  if (m_eSliceType==B_SLICE)
-  {
-    cIdx = 0;
-    for ( i=0; i<NumPocStCurr1; i++, cIdx++)
-    {
-      rpsCurrList1[cIdx] = RefPicSetStCurr1[i];
-    }
-    for ( i=0; i<NumPocStCurr0; i++, cIdx++)
-    {
-      rpsCurrList1[cIdx] = RefPicSetStCurr0[i];
-    }
-    for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
-    {
-      rpsCurrList1[cIdx] = RefPicSetLtCurr[i];
-    }
-    assert(cIdx == numPocTotalCurr);
-  }
-
-  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
-
-  for (Int rIdx = 0; rIdx < m_aiNumRefIdx[0]; rIdx ++)
-  {
-    cIdx = m_RefPicListModification.getRefPicListModificationFlagL0() ? m_RefPicListModification.getRefPicSetIdxL0(rIdx) : rIdx % numPocTotalCurr;
-    assert(cIdx >= 0 && cIdx < numPocTotalCurr);
-    m_apcRefPicList[0][rIdx] = rpsCurrList0[ cIdx ];
-    m_bIsUsedAsLongTerm[0][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
-  }
-  if ( m_eSliceType != B_SLICE )
-  {
-    m_aiNumRefIdx[1] = 0;
-    ::memset( m_apcRefPicList[1], 0, sizeof(m_apcRefPicList[1]));
-  }
-  else
-  {
-    for (Int rIdx = 0; rIdx < m_aiNumRefIdx[1]; rIdx ++)
-    {
-      cIdx = m_RefPicListModification.getRefPicListModificationFlagL1() ? m_RefPicListModification.getRefPicSetIdxL1(rIdx) : rIdx % numPocTotalCurr;
-      assert(cIdx >= 0 && cIdx < numPocTotalCurr);
-      m_apcRefPicList[1][rIdx] = rpsCurrList1[ cIdx ];
-      m_bIsUsedAsLongTerm[1][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
-    }
-  }
-}
-
-#else
-Void TComSlice::getTempRefPicLists( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1,                                     
-                                   std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int& numPocTotalCurr, Bool checkNumPocTotalCurr )
-{
-  if (!checkNumPocTotalCurr)
-  {
-    if (m_eSliceType == I_SLICE)
-    {      
-      return;
-    }    
-  }
-
-  TComPic*  pcRefPic= NULL;
-  TComPic*  RefPicSetStCurr0[16];
-  TComPic*  RefPicSetStCurr1[16];
-  TComPic*  RefPicSetLtCurr[16];
-  UInt NumPocStCurr0 = 0;
-  UInt NumPocStCurr1 = 0;
-  UInt NumPocLtCurr = 0;
-  Int i;
-#if H_3D
-  m_pocsInCurrRPSs.clear();
-#endif
-  for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
-  {
-    if(m_pcRPS->getUsed(i))
-    {
-      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
-      pcRefPic->setIsLongTerm(0);
-      pcRefPic->getPicYuvRec()->extendPicBorder();
-      RefPicSetStCurr0[NumPocStCurr0] = pcRefPic;
-      NumPocStCurr0++;
-      pcRefPic->setCheckLTMSBPresent(false);  
-#if H_3D
-      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
-#endif
-    }
-  }
-  
-  for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
-  {
-    if(m_pcRPS->getUsed(i))
-    {
-      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
-      pcRefPic->setIsLongTerm(0);
-      pcRefPic->getPicYuvRec()->extendPicBorder();
-      RefPicSetStCurr1[NumPocStCurr1] = pcRefPic;
-      NumPocStCurr1++;
-      pcRefPic->setCheckLTMSBPresent(false);  
-#if H_3D
-      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
-#endif
-    }
-  }
-  
-  for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
-  {
-    if(m_pcRPS->getUsed(i))
-    {
-      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
-      pcRefPic->setIsLongTerm(1);
-      pcRefPic->getPicYuvRec()->extendPicBorder();
-      RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
-      NumPocLtCurr++;
-#if H_3D
-      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
-#endif
-    }
-    if(pcRefPic==NULL) 
-    {
-      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
-    }
-    pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i));  
-  }
-
   Int numPocInterCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr; 
-#if H_3D
+#if NH_3D
   assert( numPocInterCurr == (Int) m_pocsInCurrRPSs.size() ); 
 #endif
@@ -763,9 +789,10 @@
 }
 #endif
-Int TComSlice::getNumRpsCurrTempList()
+
+Int TComSlice::getNumRpsCurrTempList() const
 {
   Int numRpsCurrTempList = 0;
 
-  if (m_eSliceType == I_SLICE) 
+  if (m_eSliceType == I_SLICE)
   {
     return 0;
@@ -778,5 +805,5 @@
     }
   }
-#if H_MV
+#if NH_MV
   numRpsCurrTempList = numRpsCurrTempList + getNumActiveRefLayerPics();
 #endif
@@ -786,5 +813,5 @@
 Void TComSlice::initEqualRef()
 {
-  for (Int iDir = 0; iDir < 2; iDir++)
+  for (Int iDir = 0; iDir < NUM_REF_PIC_LIST_01; iDir++)
   {
     for (Int iRefIdx1 = 0; iRefIdx1 < MAX_NUM_REF; iRefIdx1++)
@@ -820,4 +847,7 @@
 }
 #endif
+#endif
+
+#if NH_3D
 Void TComSlice::setCamparaSlice( Int** aaiScale, Int** aaiOffset )
 {  
@@ -846,5 +876,5 @@
   Int i;
   TComSlice* curSlice = pic->getSlice(curSliceIdx);
-  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(1-curSlice->getColFromL0Flag()), curSlice->getColRefIdx());
+  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(1 - curSlice->getColFromL0Flag()), curSlice->getColRefIdx());
   TComSlice* preSlice;
   Int preColRefPOC;
@@ -854,5 +884,5 @@
     if(preSlice->getSliceType() != I_SLICE)
     {
-      preColRefPOC  = preSlice->getRefPOC( RefPicList(1-preSlice->getColFromL0Flag()), preSlice->getColRefIdx());
+      preColRefPOC  = preSlice->getRefPOC( RefPicList(1 - preSlice->getColFromL0Flag()), preSlice->getColRefIdx());
       if(currColRefPOC != preColRefPOC)
       {
@@ -868,5 +898,5 @@
 }
 
-Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic)
+Void TComSlice::checkCRA(const TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic)
 {
   for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
@@ -887,7 +917,7 @@
       else
       {
-      assert(pReferencePictureSet->getPOC(i) >= pocCRA);
-    }
-  }
+        assert(pReferencePictureSet->getPOC(i) >= pocCRA);
+      }
+    }
   }
   if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
@@ -915,24 +945,21 @@
  * \param rcListPic reference to the reference picture list
  * This function marks the reference pictures as "unused for reference" in the following conditions.
- * If the nal_unit_type is IDR/BLA/BLANT, all pictures in the reference picture list  
+ * If the nal_unit_type is IDR/BLA/BLANT, all pictures in the reference picture list
  * are marked as "unused for reference"
  *    If the nal_unit_type is BLA/BLANT, set the pocCRA to the temporal reference of the current picture.
  * Otherwise
- *    If the bRefreshPending flag is true (a deferred decoding refresh is pending) and the current 
- *    temporal reference is greater than the temporal reference of the latest CRA/CRANT/BLA/BLANT picture (pocCRA), 
- *    mark all reference pictures except the latest CRA/CRANT/BLA/BLANT picture as "unused for reference" and set 
+ *    If the bRefreshPending flag is true (a deferred decoding refresh is pending) and the current
+ *    temporal reference is greater than the temporal reference of the latest CRA/CRANT/BLA/BLANT picture (pocCRA),
+ *    mark all reference pictures except the latest CRA/CRANT/BLA/BLANT picture as "unused for reference" and set
  *    the bRefreshPending flag to false.
- *    If the nal_unit_type is CRA/CRANT, set the bRefreshPending flag to true and pocCRA to the temporal 
+ *    If the nal_unit_type is CRA/CRANT, set the bRefreshPending flag to true and pocCRA to the temporal
  *    reference of the current picture.
  * Note that the current picture is already placed in the reference list and its marking is not changed.
  * If the current picture has a nal_ref_idc that is not 0, it will remain marked as "used for reference".
  */
-Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic)
-{
-  TComPic*                 rpcPic;
-#if !FIX1172
-  setAssociatedIRAPPOC(pocCRA);
-#endif
-  Int pocCurr = getPOC(); 
+Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, const bool bEfficientFieldIRAPEnabled)
+{
+  TComPic* rpcPic;
+  Int      pocCurr = getPOC();
 
   if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
@@ -948,5 +975,8 @@
       rpcPic = *(iterPic);
       rpcPic->setCurrSliceIdx(0);
-      if (rpcPic->getPOC() != pocCurr) rpcPic->getSlice(0)->setReferenced(false);
+      if (rpcPic->getPOC() != pocCurr)
+      {
+        rpcPic->getSlice(0)->setReferenced(false);
+      }
       iterPic++;
     }
@@ -957,12 +987,12 @@
       pocCRA = pocCurr;
     }
-#if EFFICIENT_FIELD_IRAP
+    if (bEfficientFieldIRAPEnabled)
+    {
     bRefreshPending = true;
-#endif
+    }
   }
   else // CRA or No DR
   {
-#if EFFICIENT_FIELD_IRAP
-    if(getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
+    if(bEfficientFieldIRAPEnabled && (getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL))
     {
       if (bRefreshPending==true && pocCurr > m_iLastIDR) // IDR reference marking pending 
@@ -983,25 +1013,22 @@
     else
     {
-#endif
-    if (bRefreshPending==true && pocCurr > pocCRA) // CRA reference marking pending 
-    {
-      TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
-      while (iterPic != rcListPic.end())
-      {
-        rpcPic = *(iterPic);
-        if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA)
-        {
-          rpcPic->getSlice(0)->setReferenced(false);
-        }
-        iterPic++;
-      }
-      bRefreshPending = false; 
-    }
-#if EFFICIENT_FIELD_IRAP
-    }
-#endif
+      if (bRefreshPending==true && pocCurr > pocCRA) // CRA reference marking pending
+      {
+        TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+        while (iterPic != rcListPic.end())
+        {
+          rpcPic = *(iterPic);
+          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA)
+          {
+            rpcPic->getSlice(0)->setReferenced(false);
+          }
+          iterPic++;
+        }
+        bRefreshPending = false;
+      }
+    }
     if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
     {
-      bRefreshPending = true; 
+      bRefreshPending = true;
       pocCRA = pocCurr;
     }
@@ -1017,5 +1044,5 @@
   m_iPOC                 = pSrc->m_iPOC;
   m_eNalUnitType         = pSrc->m_eNalUnitType;
-#if H_MV
+#if NH_MV
   m_layerId              = pSrc->m_layerId;
   // GT: Copying of several other values might be be missing here, or is above not necessary? 
@@ -1026,10 +1053,11 @@
   m_iSliceQpBase         = pSrc->m_iSliceQpBase;
 #endif
+  m_ChromaQpAdjEnabled = pSrc->m_ChromaQpAdjEnabled;
   m_deblockingFilterDisable   = pSrc->m_deblockingFilterDisable;
   m_deblockingFilterOverrideFlag = pSrc->m_deblockingFilterOverrideFlag;
   m_deblockingFilterBetaOffsetDiv2 = pSrc->m_deblockingFilterBetaOffsetDiv2;
   m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
-  
-  for (i = 0; i < 2; i++)
+
+  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
   {
     m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
@@ -1039,10 +1067,13 @@
   {
     m_list1IdxToList0Idx[i] = pSrc->m_list1IdxToList0Idx[i];
-  } 
+  }
+
   m_bCheckLDC             = pSrc->m_bCheckLDC;
   m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
-  m_iSliceQpDeltaCb      = pSrc->m_iSliceQpDeltaCb;
-  m_iSliceQpDeltaCr      = pSrc->m_iSliceQpDeltaCr;
-  for (i = 0; i < 2; i++)
+  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
+  {
+    m_iSliceChromaQpDelta[component] = pSrc->m_iSliceChromaQpDelta[component];
+  }
+  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
   {
     for (j = 0; j < MAX_NUM_REF; j++)
@@ -1050,15 +1081,10 @@
       m_apcRefPicList[i][j]  = pSrc->m_apcRefPicList[i][j];
       m_aiRefPOCList[i][j]   = pSrc->m_aiRefPOCList[i][j];
-#if H_MV
+      m_bIsUsedAsLongTerm[i][j] = pSrc->m_bIsUsedAsLongTerm[i][j];
+#if NH_MV
       m_aiRefLayerIdList[i][j] = pSrc->m_aiRefLayerIdList[i][j];
 #endif
     }
-  }
-  for (i = 0; i < 2; i++)
-  {
-    for (j = 0; j < MAX_NUM_REF + 1; j++)
-    {
-      m_bIsUsedAsLongTerm[i][j] = pSrc->m_bIsUsedAsLongTerm[i][j];
-    }
+    m_bIsUsedAsLongTerm[i][MAX_NUM_REF] = pSrc->m_bIsUsedAsLongTerm[i][MAX_NUM_REF];
   }
   m_iDepth               = pSrc->m_iDepth;
@@ -1068,9 +1094,7 @@
 
   // access channel
-#if H_MV
+#if NH_MV
   m_pcVPS                = pSrc->m_pcVPS;
 #endif
-  m_pcSPS                = pSrc->m_pcSPS;
-  m_pcPPS                = pSrc->m_pcPPS;
   m_pcRPS                = pSrc->m_pcRPS;
   m_iLastIDR             = pSrc->m_iLastIDR;
@@ -1080,6 +1104,8 @@
   m_colFromL0Flag        = pSrc->m_colFromL0Flag;
   m_colRefIdx            = pSrc->m_colRefIdx;
+
   setLambdas(pSrc->getLambdas());
-  for (i = 0; i < 2; i++)
+
+  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
   {
     for (j = 0; j < MAX_NUM_REF; j++)
@@ -1095,33 +1121,38 @@
   m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
 
-  m_sliceMode                   = pSrc->m_sliceMode;
-  m_sliceArgument               = pSrc->m_sliceArgument;
-  m_sliceCurStartCUAddr         = pSrc->m_sliceCurStartCUAddr;
-  m_sliceCurEndCUAddr           = pSrc->m_sliceCurEndCUAddr;
-  m_sliceIdx                    = pSrc->m_sliceIdx;
-  m_sliceSegmentMode            = pSrc->m_sliceSegmentMode;
-  m_sliceSegmentArgument        = pSrc->m_sliceSegmentArgument; 
-  m_sliceSegmentCurStartCUAddr  = pSrc->m_sliceSegmentCurStartCUAddr;
-  m_sliceSegmentCurEndCUAddr    = pSrc->m_sliceSegmentCurEndCUAddr;
-  m_nextSlice                    = pSrc->m_nextSlice;
-  m_nextSliceSegment             = pSrc->m_nextSliceSegment;
-  for ( Int e=0 ; e<2 ; e++ )
-  {
-    for ( Int n=0 ; n<MAX_NUM_REF ; n++ )
-    {
-      memcpy(m_weightPredTable[e][n], pSrc->m_weightPredTable[e][n], sizeof(wpScalingParam)*3 );
-    }
-  }
-  m_saoEnabledFlag = pSrc->m_saoEnabledFlag; 
-  m_saoEnabledFlagChroma = pSrc->m_saoEnabledFlagChroma;
-  m_cabacInitFlag                = pSrc->m_cabacInitFlag;
-  m_numEntryPointOffsets  = pSrc->m_numEntryPointOffsets;
-
-  m_bLMvdL1Zero = pSrc->m_bLMvdL1Zero;
-  m_LFCrossSliceBoundaryFlag = pSrc->m_LFCrossSliceBoundaryFlag;
+  m_sliceMode                     = pSrc->m_sliceMode;
+  m_sliceArgument                 = pSrc->m_sliceArgument;
+  m_sliceCurStartCtuTsAddr        = pSrc->m_sliceCurStartCtuTsAddr;
+  m_sliceCurEndCtuTsAddr          = pSrc->m_sliceCurEndCtuTsAddr;
+  m_sliceIdx                      = pSrc->m_sliceIdx;
+  m_sliceSegmentMode              = pSrc->m_sliceSegmentMode;
+  m_sliceSegmentArgument          = pSrc->m_sliceSegmentArgument;
+  m_sliceSegmentCurStartCtuTsAddr = pSrc->m_sliceSegmentCurStartCtuTsAddr;
+  m_sliceSegmentCurEndCtuTsAddr   = pSrc->m_sliceSegmentCurEndCtuTsAddr;
+  m_nextSlice                     = pSrc->m_nextSlice;
+  m_nextSliceSegment              = pSrc->m_nextSliceSegment;
+
+  for ( UInt e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
+  {
+    for ( UInt n=0 ; n<MAX_NUM_REF ; n++ )
+    {
+      memcpy(m_weightPredTable[e][n], pSrc->m_weightPredTable[e][n], sizeof(WPScalingParam)*MAX_NUM_COMPONENT );
+    }
+  }
+
+  for( UInt ch = 0 ; ch < MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_saoEnabledFlag[ch] = pSrc->m_saoEnabledFlag[ch];
+  }
+
+  m_cabacInitFlag                 = pSrc->m_cabacInitFlag;
+
+  m_bLMvdL1Zero                   = pSrc->m_bLMvdL1Zero;
+  m_LFCrossSliceBoundaryFlag      = pSrc->m_LFCrossSliceBoundaryFlag;
   m_enableTMVPFlag                = pSrc->m_enableTMVPFlag;
   m_maxNumMergeCand               = pSrc->m_maxNumMergeCand;
-
-#if H_MV
+  m_encCABACTableIdx              = pSrc->m_encCABACTableIdx;
+
+#if NH_MV
   // Additional slice header syntax elements 
 #if !H_MV_HLS7_GEN
@@ -1144,12 +1175,12 @@
   m_icSkipParseFlag = pSrc->m_icSkipParseFlag;
 #endif
-}
-
-Int TComSlice::m_prevTid0POC = 0;
+
+}
+
 
 /** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
  * \param uiTLayer Temporal layer ID of the current slice
- * The decoder calls this function to set temporal_layer_switching_point_flag for each temporal layer based on 
- * the SPS's temporal_id_nesting_flag and the parsed PPS.  Then, current slice's temporal layer ID and 
+ * The decoder calls this function to set temporal_layer_switching_point_flag for each temporal layer based on
+ * the SPS's temporal_id_nesting_flag and the parsed PPS.  Then, current slice's temporal layer ID and
  * temporal_layer_switching_point_flag is set accordingly.
  */
@@ -1161,5 +1192,5 @@
 /** Function for checking if this is a switching-point
 */
-Bool TComSlice::isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic )
+Bool TComSlice::isTemporalLayerSwitchingPoint(TComList<TComPic*>& rcListPic)
 {
   TComPic* rpcPic;
@@ -1180,23 +1211,23 @@
 }
 
-/** Function for checking if this is a STSA candidate 
+/** Function for checking if this is a STSA candidate
  */
-Bool TComSlice::isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic )
-{
-    TComPic* rpcPic;
-    
-    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
-    while ( iterPic != rcListPic.end())
-    {
-        rpcPic = *(iterPic++);
-        if(rpcPic->getSlice(0)->isReferenced() &&  (rpcPic->getUsedByCurr()==true) && rpcPic->getPOC() != getPOC())
-        {
-            if(rpcPic->getTLayer() >= getTLayer())
-            {
-                return false;
-            }
-        }
-    }
-    return true;
+Bool TComSlice::isStepwiseTemporalLayerSwitchingPointCandidate(TComList<TComPic*>& rcListPic)
+{
+  TComPic* rpcPic;
+
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if(rpcPic->getSlice(0)->isReferenced() &&  (rpcPic->getUsedByCurr()==true) && rpcPic->getPOC() != getPOC())
+    {
+      if(rpcPic->getTLayer() >= getTLayer())
+      {
+        return false;
+      }
+    }
+  }
+  return true;
 }
 
@@ -1264,10 +1295,8 @@
   {
     rpcPic = *(iterPic++);
-#if BUGFIX_INTRAPERIOD
     if(!rpcPic->getReconMark())
     {
       continue;
     }
-#endif
     if (rpcPic->getPOC() == this->getPOC())
     {
@@ -1278,9 +1307,5 @@
     // in decoding order shall precede the IRAP picture in output order.
     // (Note that any picture following in output order would be present in the DPB)
-#if !SETTING_NO_OUT_PIC_PRIOR
-    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
-#else
     if(rpcPic->getSlice(0)->getPicOutputFlag() == 1 && !this->getNoOutputPriorPicsFlag())
-#endif
     {
       if(nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP    ||
@@ -1317,16 +1342,16 @@
     // When a picture is a leading picture, it shall precede, in decoding order,
     // all trailing pictures that are associated with the same IRAP picture.
-    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
-       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
-       nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
-       nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
-    {
-      if(rpcPic->getSlice(0)->getAssociatedIRAPPOC() == this->getAssociatedIRAPPOC())
-      {
-        // rpcPic is a picture that preceded the leading in decoding order since it exist in the DPB
-        // rpcPic would violate the constraint if it was a trailing picture
-        assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
-      }
-    }
+      if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
+      {
+        if(rpcPic->getSlice(0)->getAssociatedIRAPPOC() == this->getAssociatedIRAPPOC())
+        {
+          // rpcPic is a picture that preceded the leading in decoding order since it exist in the DPB
+          // rpcPic would violate the constraint if it was a trailing picture
+          assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
+        }
+      }
 
     // Any RASL picture associated with a CRA or BLA picture shall precede any
@@ -1334,5 +1359,5 @@
     if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
        nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
-    { 
+    {
       if((this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
           this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
@@ -1372,7 +1397,8 @@
 
 
+
 /** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
 */
-Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet)
 {
   TComPic* rpcPic;
@@ -1414,5 +1440,5 @@
         }
       }
-      else 
+      else
       {
         Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
@@ -1427,5 +1453,5 @@
 
     }
-#if H_MV
+#if NH_MV
     if( isReference ) // Current picture is in the temporal RPS
     {
@@ -1435,7 +1461,7 @@
     // mark the picture as "unused for reference" if it is not in
     // the Reference Picture Set
-    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && isReference == 0)    
-    {            
-      rpcPic->getSlice( 0 )->setReferenced( false );   
+    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && isReference == 0)
+    {
+      rpcPic->getSlice( 0 )->setReferenced( false );
       rpcPic->setUsedByCurr(0);
       rpcPic->setIsLongTerm(0);
@@ -1458,14 +1484,8 @@
 /** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
 */
-#if ALLOW_RECOVERY_POINT_AS_RAP
-Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess, Bool bUseRecoveryPoint)
-#else
-Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess)
-#endif
-{
-#if ALLOW_RECOVERY_POINT_AS_RAP
+Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess, Bool bUseRecoveryPoint)
+{
   Int atLeastOneUnabledByRecoveryPoint = 0;
   Int atLeastOneFlushedByPreviousIDR = 0;
-#endif
   TComPic* rpcPic;
   Int i, isAvailable;
@@ -1488,5 +1508,4 @@
         if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i) && rpcPic->getSlice(0)->isReferenced())
         {
-#if ALLOW_RECOVERY_POINT_AS_RAP
           if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
           {
@@ -1495,12 +1514,9 @@
           else
           {
-          isAvailable = 1;
-        }
-#else
-          isAvailable = 1;
-#endif
-        }
-      }
-      else 
+            isAvailable = 1;
+          }
+        }
+      }
+      else
       {
         Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
@@ -1509,5 +1525,4 @@
         if(rpcPic->getIsLongTerm() && curPoc == refPoc && rpcPic->getSlice(0)->isReferenced())
         {
-#if ALLOW_RECOVERY_POINT_AS_RAP
           if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
           {
@@ -1516,9 +1531,6 @@
           else
           {
-          isAvailable = 1;
-        }
-#else
-          isAvailable = 1;
-#endif
+            isAvailable = 1;
+          }
         }
       }
@@ -1540,8 +1552,7 @@
           refPoc = refPoc & (pocCycle - 1);
         }
-        
+
         if (rpcPic->getSlice(0)->isReferenced() && curPoc == refPoc)
         {
-#if ALLOW_RECOVERY_POINT_AS_RAP
           if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
           {
@@ -1550,13 +1561,8 @@
           else
           {
-          isAvailable = 1;
-          rpcPic->setIsLongTerm(1);
-          break;
-        }
-#else
-          isAvailable = 1;
-          rpcPic->setIsLongTerm(1);
-          break;
-#endif
+            isAvailable = 1;
+            rpcPic->setIsLongTerm(1);
+            break;
+          }
         }
       }
@@ -1564,6 +1570,6 @@
     // report that a picture is lost if it is in the Reference Picture Set
     // but not available as reference picture
-    if(isAvailable == 0)    
-    {            
+    if(isAvailable == 0)
+    {
       if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
       {
@@ -1586,5 +1592,4 @@
         }
       }
-#if ALLOW_RECOVERY_POINT_AS_RAP
       else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
       {
@@ -1595,7 +1600,6 @@
         atLeastOneFlushedByPreviousIDR = 1;
       }
-#endif
-    }
-  }  
+    }
+  }
   // loop through all short-term pictures in the Reference Picture Set
   // to see if the picture should be kept as reference picture
@@ -1611,5 +1615,4 @@
       if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
       {
-#if ALLOW_RECOVERY_POINT_AS_RAP
         if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
         {
@@ -1618,15 +1621,12 @@
         else
         {
-        isAvailable = 1;
-      }
-#else
-        isAvailable = 1;
-#endif
+          isAvailable = 1;
+        }
       }
     }
     // report that a picture is lost if it is in the Reference Picture Set
     // but not available as reference picture
-    if(isAvailable == 0)    
-    {            
+    if(isAvailable == 0)
+    {
       if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
       {
@@ -1649,22 +1649,19 @@
         }
       }
-#if ALLOW_RECOVERY_POINT_AS_RAP
       else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
       {
         atLeastOneUnabledByRecoveryPoint = 1;
-    }
+      }
       else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
       {
         atLeastOneFlushedByPreviousIDR = 1;
-  }    
-#endif
-    }
-    }
-#if ALLOW_RECOVERY_POINT_AS_RAP
+      }
+    }
+  }
+
   if(atLeastOneUnabledByRecoveryPoint || atLeastOneFlushedByPreviousIDR)
   {
     return -1;
   }    
-#endif
   if(atLeastOneLost)
   {
@@ -1683,9 +1680,5 @@
 /** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
 */
-#if ALLOW_RECOVERY_POINT_AS_RAP
-Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess, Bool bUseRecoveryPoint)
-#else
-Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP)
-#endif
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess, Bool bUseRecoveryPoint, const Bool bEfficientFieldIRAPEnabled)
 {
   TComPic* rpcPic;
@@ -1695,4 +1688,5 @@
   Int nrOfPositivePictures = 0;
   TComReferencePictureSet* pcRPS = this->getLocalRPS();
+  Bool irapIsInRPS = false; // Used when bEfficientFieldIRAPEnabled==true
 
   // loop through all pictures in the Reference Picture Set
@@ -1713,7 +1707,9 @@
         pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
         pcRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
-#if ALLOW_RECOVERY_POINT_AS_RAP
+        if (bEfficientFieldIRAPEnabled)
+        {
         pcRPS->setUsed(k, pcRPS->getUsed(k) && !(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess) ); 
-#endif
+        }
+
         if(pcRPS->getDeltaPOC(k) < 0)
         {
@@ -1722,4 +1718,8 @@
         else
         {
+          if(bEfficientFieldIRAPEnabled && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
+          {
+            irapIsInRPS = true;
+          }
           nrOfPositivePictures++;
         }
@@ -1728,8 +1728,8 @@
     }
   }
-#if EFFICIENT_FIELD_IRAP
+
   Bool useNewRPS = false;
   // if current picture is complimentary field associated to IRAP, add the IRAP to its RPS. 
-  if(m_pcPic->isField())
+  if(bEfficientFieldIRAPEnabled && m_pcPic->isField() && !irapIsInRPS)
   {
     TComList<TComPic*>::iterator iterPic = rcListPic.begin();
@@ -1747,16 +1747,11 @@
     }
   }
-#endif
   pcRPS->setNumberOfNegativePictures(nrOfNegativePictures);
   pcRPS->setNumberOfPositivePictures(nrOfPositivePictures);
   pcRPS->setNumberOfPictures(nrOfNegativePictures+nrOfPositivePictures);
-  // This is a simplistic inter rps example. A smarter encoder will look for a better reference RPS to do the 
+  // This is a simplistic inter rps example. A smarter encoder will look for a better reference RPS to do the
   // inter RPS prediction with.  Here we just use the reference used by pReferencePictureSet.
   // If pReferencePictureSet is not inter_RPS_predicted, then inter_RPS_prediction is for the current RPS also disabled.
-  if (!pReferencePictureSet->getInterRPSPrediction()
-#if EFFICIENT_FIELD_IRAP
-    || useNewRPS
-#endif
-    )
+  if (!pReferencePictureSet->getInterRPSPrediction() || useNewRPS )
   {
     pcRPS->setInterRPSPrediction(false);
@@ -1767,8 +1762,8 @@
     Int rIdx =  this->getRPSidx() - pReferencePictureSet->getDeltaRIdxMinus1() - 1;
     Int deltaRPS = pReferencePictureSet->getDeltaRPS();
-    TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
+    const TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
     Int iRefPics = pcRefRPS->getNumberOfPictures();
     Int iNewIdc=0;
-    for(i=0; i<= iRefPics; i++) 
+    for(i=0; i<= iRefPics; i++)
     {
       Int deltaPOC = ((i != iRefPics)? pcRefRPS->getDeltaPOC(i) : 0);  // check if the reference abs POC is >= 0
@@ -1793,5 +1788,5 @@
     pcRPS->setInterRPSPrediction(true);
     pcRPS->setNumRefIdc(iNewIdc);
-    pcRPS->setDeltaRPS(deltaRPS); 
+    pcRPS->setDeltaRPS(deltaRPS);
     pcRPS->setDeltaRIdxMinus1(pReferencePictureSet->getDeltaRIdxMinus1() + this->getSPS()->getRPSList()->getNumberOfReferencePictureSets() - this->getRPSidx());
   }
@@ -1801,19 +1796,14 @@
 }
 
-/** get AC and DC values for weighted pred
- * \param *wp
- * \returns Void
- */
-Void  TComSlice::getWpAcDcParam(wpACDCParam *&wp)
+//! get AC and DC values for weighted pred
+Void  TComSlice::getWpAcDcParam(WPACDCParam *&wp)
 {
   wp = m_weightACDCParam;
 }
 
-/** init AC and DC values for weighted pred
- * \returns Void
- */
+//! init AC and DC values for weighted pred
 Void  TComSlice::initWpAcDcParam()
 {
-  for(Int iComp = 0; iComp < 3; iComp++ )
+  for(Int iComp = 0; iComp < MAX_NUM_COMPONENT; iComp++ )
   {
     m_weightACDCParam[iComp].iAC = 0;
@@ -1822,28 +1812,21 @@
 }
 
-/** get WP tables for weighted pred
- * \param RefPicList
- * \param iRefIdx
- * \param *&wpScalingParam
- * \returns Void
- */
-Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, wpScalingParam *&wp )
-{
+//! get tables for weighted prediction
+Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, WPScalingParam *&wp )
+{
+  assert (e<NUM_REF_PIC_LIST_01);
   wp = m_weightPredTable[e][iRefIdx];
 }
 
-/** reset Default WP tables settings : no weight. 
- * \param wpScalingParam
- * \returns Void
- */
+//! reset Default WP tables settings : no weight.
 Void  TComSlice::resetWpScaling()
 {
-  for ( Int e=0 ; e<2 ; e++ )
+  for ( Int e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
   {
     for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
     {
-      for ( Int yuv=0 ; yuv<3 ; yuv++ )
-      {
-        wpScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
+      for ( Int yuv=0 ; yuv<MAX_NUM_COMPONENT ; yuv++ )
+      {
+        WPScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
         pwp->bPresentFlag      = false;
         pwp->uiLog2WeightDenom = 0;
@@ -1856,17 +1839,16 @@
 }
 
-/** init WP table
- * \returns Void
- */
-Void  TComSlice::initWpScaling()
-{
-  for ( Int e=0 ; e<2 ; e++ )
+//! init WP table
+Void  TComSlice::initWpScaling(const TComSPS *sps)
+{
+  const Bool bUseHighPrecisionPredictionWeighting = sps->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
+  for ( Int e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
   {
     for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
     {
-      for ( Int yuv=0 ; yuv<3 ; yuv++ )
-      {
-        wpScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
-        if ( !pwp->bPresentFlag ) 
+      for ( Int yuv=0 ; yuv<MAX_NUM_COMPONENT ; yuv++ )
+      {
+        WPScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
+        if ( !pwp->bPresentFlag )
         {
           // Inferring values not present :
@@ -1875,7 +1857,8 @@
         }
 
+        const Int offsetScalingFactor = bUseHighPrecisionPredictionWeighting ? 1 : (1 << (sps->getBitDepth(toChannelType(ComponentID(yuv)))-8));
+
         pwp->w      = pwp->iWeight;
-        Int bitDepth = yuv ? g_bitDepthC : g_bitDepthY;
-        pwp->o      = pwp->iOffset << (bitDepth-8);
+        pwp->o      = pwp->iOffset * offsetScalingFactor; //NOTE: This value of the ".o" variable is never used - .o is set immediately before it gets used
         pwp->shift  = pwp->uiLog2WeightDenom;
         pwp->round  = (pwp->uiLog2WeightDenom>=1) ? (1 << (pwp->uiLog2WeightDenom-1)) : (0);
@@ -1891,5 +1874,5 @@
 : m_VPSId                     (  0)
 , m_uiMaxTLayers              (  1)
-#if H_MV
+#if NH_MV
 , m_uiMaxLayersMinus1         (  0)
 #else
@@ -1898,18 +1881,14 @@
 , m_bTemporalIdNestingFlag    (false)
 , m_numHrdParameters          (  0)
-#if H_MV
+#if NH_MV
 , m_maxLayerId             (  0)
 #else
 , m_maxNuhReservedZeroLayerId (  0)
 #endif
-, m_hrdParameters             (NULL)
-, m_hrdOpSetIdx               (NULL)
-, m_cprmsPresentFlag          (NULL)
-#if H_MV
-, m_dpbSize                   (NULL)
-, m_vpsVUI                 (  NULL )
-#endif
-{
-#if H_MV
+, m_hrdParameters             ()
+, m_hrdOpSetIdx               ()
+, m_cprmsPresentFlag          ()
+{
+#if NH_MV
   m_vpsBaseLayerInternalFlag = true; 
   m_vpsBaseLayerAvailableFlag = true; 
@@ -1922,8 +1901,8 @@
   {
     m_numReorderPics[i] = 0;
-    m_uiMaxDecPicBuffering[i] = 1; 
+    m_uiMaxDecPicBuffering[i] = 1;
     m_uiMaxLatencyIncrease[i] = 0;
   }
-#if H_MV
+#if NH_MV
   for (Int lsIdx = 0; lsIdx < MAX_VPS_OP_SETS_PLUS1; lsIdx++ )
   {  
@@ -1988,13 +1967,12 @@
     m_layerIdInNuh      [i] = ( i == 0 ) ? 0 : -1; 
     m_numDirectRefLayers[i] = 0; 
-#if H_3D
+#if NH_3D
     m_numRefListLayers[i] = 0; 
 #endif
     m_vpsRepFormatIdx    [i] = 0; 
-    m_pocLsbNotPresentFlag[i] = 0;
-    m_repFormat          [i] = NULL; 
+    m_pocLsbNotPresentFlag[i] = 0;    
     m_viewIdVal          [i] = 0; 
 
-#if H_3D
+#if NH_3D
     m_viewIndex         [i] = -1; 
 #endif
@@ -2006,5 +1984,5 @@
       m_dependencyFlag  [i][j]    = false; 
       m_idDirectRefLayer[i][j]    = -1; 
-#if H_3D
+#if NH_3D
       m_idRefListLayer[i][j]    = -1; 
 #endif
@@ -2020,9 +1998,5 @@
 #if H_3D_ARP
 #endif
-  }
-  m_vpsVUI = new TComVPSVUI; 
-  m_dpbSize = new TComDpbSize; 
-
-
+  }  
 #endif
 }
@@ -2030,22 +2004,7 @@
 TComVPS::~TComVPS()
 {
-  if( m_hrdParameters    != NULL )     delete[] m_hrdParameters;
-  if( m_hrdOpSetIdx      != NULL )     delete[] m_hrdOpSetIdx;
-  if( m_cprmsPresentFlag != NULL )     delete[] m_cprmsPresentFlag;
-#if H_MV
-  if ( m_vpsVUI          != NULL )     delete m_vpsVUI; 
-  if ( m_dpbSize         != NULL )     delete m_dpbSize; 
-
-  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
-  {
-    if (m_repFormat[ i ] != NULL )      delete m_repFormat[ i ];    
-  }
-#endif
-#if H_3D
-  deleteCamPars();
-#endif
-}
-
-#if H_MV
+}
+
+#if NH_MV
 
 Bool TComVPS::checkVPSExtensionSyntax()
@@ -2066,10 +2025,10 @@
 }
 
-Int TComVPS::getNumScalabilityTypes()
+Int TComVPS::getNumScalabilityTypes() const
 {
   return scalTypeToScalIdx( ScalabilityType(MAX_NUM_SCALABILITY_TYPES) );
 }
 
-Int TComVPS::scalTypeToScalIdx( ScalabilityType scalType )
+Int TComVPS::scalTypeToScalIdx( ScalabilityType scalType ) const
 {
   assert( scalType >= 0 && scalType <= MAX_NUM_SCALABILITY_TYPES ); 
@@ -2114,5 +2073,5 @@
     Int iNuhLId = getLayerIdInNuh( i );
     Int d = 0;
-#if H_3D
+#if NH_3D
     Int l = 0; 
 #endif
@@ -2127,5 +2086,5 @@
         m_idDirectRefLayer[iNuhLId][d++] = jNuhLid;
       }
-#if H_3D
+#if NH_3D
       if( getDirectDependencyFlag( i , j ) && ( getDepthId( iNuhLId ) == getDepthId( jNuhLid ) ))
       {
@@ -2144,5 +2103,5 @@
     }
     m_numDirectRefLayers[ iNuhLId ] = d;
-#if H_3D
+#if NH_3D
     m_numRefListLayers[ iNuhLId ] = l; 
 #endif
@@ -2185,7 +2144,6 @@
 {
   m_numViews = 1; 
-#if H_3D
-  AOF( m_viewOIdxList.size() == 0 ); 
-  
+#if NH_3D
+  AOF( m_viewOIdxList.size() == 0 );   
   m_viewOIdxList.push_back( 0 );        
 #endif
@@ -2207,5 +2165,5 @@
       {
         m_numViews++;
-#if H_3D
+#if NH_3D
         m_viewOIdxList.push_back( getViewOrderIdx( lId ) );        
 #endif
@@ -2216,11 +2174,11 @@
 
 
-Int TComVPS::getScalabilityId( Int layerIdInVps, ScalabilityType scalType )
+Int TComVPS::getScalabilityId( Int layerIdInVps, ScalabilityType scalType ) const
 {
   return getScalabilityMaskFlag( scalType ) ? getDimensionId( layerIdInVps, scalTypeToScalIdx( scalType ) ) : 0;
 }
 
-#if H_3D
-Int TComVPS::getLayerIdInNuh( Int viewIndex, Bool depthFlag )
+#if NH_3D
+Int TComVPS::getLayerIdInNuh( Int viewIndex, Bool depthFlag ) const
 {
   Int foundLayerIdinNuh = -1; 
@@ -2240,37 +2198,34 @@
 Void TComVPS::createCamPars(Int iNumViews)
 {
-  Int i = 0, j = 0;
-
-  m_numCp    = new Int [ iNumViews ];
-  m_cpRefVoi = new Int*[ iNumViews ];
-  m_cpInSliceSegmentHeaderFlag = new Bool[ iNumViews ];
-
-  m_cpPresentFlag  = new Bool*[ iNumViews ]; 
-  
-
-  m_aaaiCodedScale = new Int**[ iNumViews ];
-  m_aaaiCodedOffset = new Int**[ iNumViews ];
-  for ( i = 0; i < iNumViews ; i++ )
-  {
-    m_cpInSliceSegmentHeaderFlag[i] = false;     
-    
-    m_aaaiCodedScale[i] = new Int*[ 2 ];
-    m_aaaiCodedOffset[i] = new Int*[ 2 ];
-
-    m_numCp   [i] = 0; 
-    m_cpRefVoi[i] = new Int[ iNumViews ];
-    m_cpPresentFlag[i] = new Bool[ iNumViews ]; 
-    for ( j = 0; j < iNumViews; j++)
-    {
-      m_cpRefVoi[i][j] = 0; 
-      m_cpPresentFlag[i][j] = false; 
-    }
-    for ( j = 0; j < 2; j++ )
-    {
-      m_aaaiCodedScale[i][j] = new Int[ MAX_NUM_LAYERS ];
-      m_aaaiCodedOffset[i][j] = new Int[ MAX_NUM_LAYERS ];
+  m_numCp                     .resize( iNumViews );
+  m_cpRefVoi                  .resize( iNumViews );
+  m_cpInSliceSegmentHeaderFlag.resize( iNumViews );
+  m_cpPresentFlag             .resize( iNumViews ); 
+  m_aaaiCodedScale            .resize( iNumViews ); 
+  m_aaaiCodedOffset           .resize( iNumViews ); 
+
+  for ( Int i = 0; i < iNumViews ; i++ )
+  {
+    m_numCp                     [i] = 0; 
+    m_cpRefVoi                  [i].resize( iNumViews );
+    m_cpInSliceSegmentHeaderFlag[i] = false;         
+    m_aaaiCodedScale            [i].resize( 2 );
+    m_aaaiCodedOffset           [i].resize( 2 );        
+    m_cpPresentFlag             [i].resize( iNumViews ); 
+
+    for ( Int j = 0; j < iNumViews; j++)
+    {
+      m_cpRefVoi             [i][j] = 0; 
+      m_cpPresentFlag        [i][j] = false; 
+    }
+
+    for ( Int j = 0; j < 2; j++ )
+    {
+      m_aaaiCodedScale       [i][j].resize( MAX_NUM_LAYERS );
+      m_aaaiCodedOffset      [i][j].resize( MAX_NUM_LAYERS );
+
       for ( Int k = 0; k < MAX_NUM_LAYERS; k++ )
       {
-        m_aaaiCodedScale[i][j][k] = 0;
+        m_aaaiCodedScale [i][j][k] = 0;
         m_aaaiCodedOffset[i][j][k] = 0;
       }
@@ -2278,73 +2233,8 @@
   }
 }
-
-Void TComVPS::deleteCamPars()
-{
-  Int iNumViews = getNumViews();
-  Int i = 0, j = 0;
-
-  if ( m_numCp != NULL )
-  {
-    delete [] m_numCp;
-  }
-
-  if ( m_cpRefVoi != NULL )
-  {
-    for ( i = 0; i < iNumViews ; i++ )
-    {
-      delete [] m_cpRefVoi[i];
-    }
-    delete[] m_cpRefVoi; 
-  }
-
-  if ( m_cpPresentFlag != NULL )
-  {
-    for ( i = 0; i < iNumViews ; i++ )
-    {
-      delete [] m_cpPresentFlag[i];
-    }
-    delete[] m_cpPresentFlag; 
-  }
-
-
-  if ( m_cpInSliceSegmentHeaderFlag != NULL )
-  {
-    delete [] m_cpInSliceSegmentHeaderFlag;
-  }
-
-
-  if ( m_aaaiCodedScale != NULL )
-  {
-    for ( i = 0; i < iNumViews ; i++ )
-    {
-      for ( j = 0; j < 2; j++ )
-      {
-        delete [] m_aaaiCodedScale[i][j];
-      }
-      delete [] m_aaaiCodedScale[i];
-    }
-    delete [] m_aaaiCodedScale;
-  }
-
-  if ( m_aaaiCodedOffset != NULL )
-  {
-    for ( i = 0; i < iNumViews ; i++ )
-    {
-      for ( j = 0; j < 2; j++ )
-      {
-        delete [] m_aaaiCodedOffset[i][j];
-      }
-      delete [] m_aaaiCodedOffset[i];
-    }
-    delete [] m_aaaiCodedOffset;
-  }
-}
-
-
-
 #endif // H_3D
 
 
-Int TComVPS::xGetDimBitOffset( Int j )
+Int TComVPS::xGetDimBitOffset( Int j ) const
 {
   Int dimBitOffset = 0; 
@@ -2363,15 +2253,15 @@
 }
 
-Int TComVPS::inferDimensionId( Int i, Int j )
+Int TComVPS::inferDimensionId( Int i, Int j ) const
 {
     return ( ( getLayerIdInNuh( i ) & ( (1 << xGetDimBitOffset( j + 1 ) ) - 1) ) >> xGetDimBitOffset( j ) ); 
 }
 
-Int TComVPS::inferLastDimsionIdLenMinus1()
+Int TComVPS::inferLastDimsionIdLenMinus1() const
 {
   return ( 5 - xGetDimBitOffset( getNumScalabilityTypes() - 1 ) ); 
 }
 
-Int TComVPS::getNumLayersInIdList( Int lsIdx )
+Int TComVPS::getNumLayersInIdList( Int lsIdx ) const
 {
   assert( lsIdx >= 0 ); 
@@ -2380,5 +2270,5 @@
 }
 
-Int    TComVPS::getNumOutputLayerSets() 
+Int    TComVPS::getNumOutputLayerSets() const
 {
   return getNumAddOlss() + getNumLayerSets(); 
@@ -2427,5 +2317,5 @@
 }
 
-Bool TComVPS::inferOutputLayerFlag( Int i, Int j )
+Bool TComVPS::inferOutputLayerFlag( Int i, Int j ) const
 {
   Bool outputLayerFlag; 
@@ -2455,5 +2345,5 @@
 }
 
-Int TComVPS::getMaxSubLayersInLayerSetMinus1( Int i )
+Int TComVPS::getMaxSubLayersInLayerSetMinus1( Int i ) const
 {
   Int maxSLMinus1 = 0; 
@@ -2466,5 +2356,5 @@
 }
 
-Bool TComVPS::getAltOutputLayerFlagVar( Int i )
+Bool TComVPS::getAltOutputLayerFlagVar( Int i ) const
 {
   // Semantics variable not syntax element !
@@ -2481,5 +2371,5 @@
 
 
-Int TComVPS::inferProfileTierLevelIdx(Int i, Int j)
+Int TComVPS::inferProfileTierLevelIdx(Int i, Int j) const
 {
   Bool inferZero        = ( i == 0 && j == 0 &&  getVpsBaseLayerInternalFlag() );
@@ -2555,9 +2445,9 @@
 }
 
-Void TComVPS::printPTL()
+Void TComVPS::printPTL() const
 {
   std::vector<Int> idx; 
   std::vector<Int> num; 
-  std::vector< std::vector<Int> > ptlInfo; 
+  IntAry2d ptlInfo; 
 
   std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "PTLI" << std::endl; 
@@ -2566,5 +2456,5 @@
   {
     std::vector<Int> curPtlInfo;
-    ProfileTierLevel* ptl = getPTL( i )->getGeneralPTL(); 
+    const ProfileTierLevel* ptl = getPTL( i )->getGeneralPTL(); 
     curPtlInfo.push_back( (Int) ptl->getProfileIdc()  );
     curPtlInfo.push_back( (Int) ptl->getTierFlag()    );
@@ -2591,10 +2481,10 @@
 }
 
-Void TComVPS::printLayerDependencies()
+Void TComVPS::printLayerDependencies() const
 {
   vector<Int> fullArray;
   vector<Int> range; 
 
-#if H_3D
+#if NH_3D
   vector<Int> depthId; 
 #endif
@@ -2623,5 +2513,5 @@
   xPrintArray( "IdRefLayer"      , getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numRefLayers, m_idRefLayer, true );
   xPrintArray( "IdDirectRefLayer", getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numDirectRefLayers, m_idDirectRefLayer, true );
-#if H_3D
+#if NH_3D
   xPrintArray( "IdRefListLayer", getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numRefListLayers, m_idRefListLayer, true );
 #endif
@@ -2630,12 +2520,10 @@
 }
 
-Void TComVPS::printScalabilityId()
+Void TComVPS::printScalabilityId() const
 {
   vector<Int> layerIdxInVps; 
 
-#if H_3D
+
   vector<Int> depthId; 
-#endif
-
   vector<Int> viewOrderIndex;
   vector<Int> auxId;
@@ -2647,11 +2535,10 @@
     Int layerIdInNuh = getLayerIdInNuh( i );
     layerIdxInVps  .push_back( i ); 
+    depthId       .push_back( getDepthId     ( layerIdInNuh ) );
     viewOrderIndex.push_back( getViewIndex   ( layerIdInNuh ) );
     dependencyId  .push_back( getDependencyId( layerIdInNuh ) );
     auxId         .push_back( getAuxId       ( layerIdInNuh ) );      
     viewId        .push_back( getViewId      ( layerIdInNuh ) );
-#if H_3D  
-    depthId       .push_back( getDepthId     ( layerIdInNuh ) );
-#endif
+
   }
 
@@ -2660,13 +2547,14 @@
   xPrintArray( "layer_id_in_nuh", getMaxLayersMinus1()+1, m_layerIdInNuh, false );     
 
-  xPrintArray( "ViewOrderIndex", getMaxLayersMinus1()+1, viewOrderIndex, false );     
+  xPrintArray( "DepthLayerFlag", getMaxLayersMinus1()+1, depthId       , false );     
+  xPrintArray( "ViewOrderIdx"  , getMaxLayersMinus1()+1, viewOrderIndex, false );     
   xPrintArray( "DependencyId"  , getMaxLayersMinus1()+1, dependencyId  , false );     
   xPrintArray( "AuxId"         , getMaxLayersMinus1()+1, auxId         , false );     
-  xPrintArray( "ViewId"        , getMaxLayersMinus1()+1, viewId        , false );     
+  xPrintArray( "ViewIdVal"     , getMaxLayersMinus1()+1, viewId        , false );     
 
   std::cout << std::endl;
 }
 
-Void TComVPS::printLayerSets()
+Void TComVPS::printLayerSets() const
 {
   vector<Int> fullArray;
@@ -2721,5 +2609,5 @@
 }
 
-#if H_3D
+#if NH_3D
 Void TComVPS::initViewCompLayer()
 {
@@ -2749,5 +2637,5 @@
 }
 
-Int TComVPS::getVoiInVps(Int viewOIdx)
+Int TComVPS::getVoiInVps(Int viewOIdx) const
 {
   for ( Int i = 0; i < m_viewOIdxList.size(); i++ )
@@ -2783,9 +2671,25 @@
 #endif
 
-#endif // H_MV
+#endif // NH_MV
 
 // ------------------------------------------------------------------------------------------------
 // Sequence parameter set (SPS)
 // ------------------------------------------------------------------------------------------------
+
+TComSPSRExt::TComSPSRExt()
+ : m_transformSkipRotationEnabledFlag   (false)
+ , m_transformSkipContextEnabledFlag    (false)
+// m_rdpcmEnabledFlag initialized below
+ , m_extendedPrecisionProcessingFlag    (false)
+ , m_intraSmoothingDisabledFlag         (false)
+ , m_highPrecisionOffsetsEnabledFlag    (false)
+ , m_persistentRiceAdaptationEnabledFlag(false)
+ , m_cabacBypassAlignmentEnabledFlag    (false)
+{
+  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
+  {
+    m_rdpcmEnabledFlag[signallingModeIndex] = false;
+  }
+}
 
 TComSPS::TComSPS()
@@ -2798,8 +2702,8 @@
 , m_picHeightInLumaSamples    (288)
 , m_log2MinCodingBlockSize    (  0)
-, m_log2DiffMaxMinCodingBlockSize (0)
+, m_log2DiffMaxMinCodingBlockSize(0)
 , m_uiMaxCUWidth              ( 32)
 , m_uiMaxCUHeight             ( 32)
-, m_uiMaxCUDepth              (  3)
+, m_uiMaxTotalCUDepth         (  3)
 , m_bLongTermRefsPresent      (false)
 , m_uiQuadtreeTULog2MaxSize   (  0)
@@ -2808,18 +2712,12 @@
 , m_uiQuadtreeTUMaxDepthIntra (  0)
 // Tool list
-, m_usePCM                   (false)
+, m_usePCM                    (false)
 , m_pcmLog2MaxSize            (  5)
 , m_uiPCMLog2MinSize          (  7)
-, m_bitDepthY                 (  8)
-, m_bitDepthC                 (  8)
-, m_qpBDOffsetY               (  0)
-, m_qpBDOffsetC               (  0)
-, m_uiPCMBitDepthLuma         (  8)
-, m_uiPCMBitDepthChroma       (  8)
 , m_bPCMFilterDisableFlag     (false)
 , m_uiBitsForPOC              (  8)
-, m_numLongTermRefPicSPS    (  0)  
+, m_numLongTermRefPicSPS      (  0)
 , m_uiMaxTrSize               ( 32)
-, m_bUseSAO                   (false) 
+, m_bUseSAO                   (false)
 , m_bTemporalIdNestingFlag    (false)
 , m_scalingListEnabledFlag    (false)
@@ -2827,5 +2725,5 @@
 , m_vuiParametersPresentFlag  (false)
 , m_vuiParameters             ()
-#if H_MV
+#if NH_MV
 , m_pcVPS                     ( NULL )
 , m_spsInferScalingListFlag   ( false )
@@ -2836,5 +2734,17 @@
 , m_interViewMvVertConstraintFlag (false)
 #endif
-{
+
+{
+  for(Int ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_bitDepths.recon[ch] = 8;
+#if O0043_BEST_EFFORT_DECODING
+    m_bitDepths.stream[ch] = 8;
+#endif
+    m_pcmBitDepths[ch] = 8;
+    m_qpBDOffset   [ch] = 0;
+  }
+
+
   for ( Int i = 0; i < MAX_TLAYER; i++ )
   {
@@ -2843,194 +2753,95 @@
     m_numReorderPics[i]       = 0;
   }
-  m_scalingList = new TComScalingList;
+
   ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
   ::memset(m_usedByCurrPicLtSPSFlag, 0, sizeof(m_usedByCurrPicLtSPSFlag));
-#if H_MV
+#if NH_MV
   m_spsRangeExtensionsFlag     = false;
   m_spsMultilayerExtensionFlag = false;
-#if H_3D
   m_spsExtension5bits          = 0;
   m_sps3dExtensionFlag         = false; 
-#else
-  m_spsExtension6bits          = 0;
-#endif
-
-#endif
+
+#endif
+
 }
 
 TComSPS::~TComSPS()
 {
-  delete m_scalingList;
   m_RPSList.destroy();
 }
 
 Void  TComSPS::createRPSList( Int numRPS )
-{ 
+{
   m_RPSList.destroy();
   m_RPSList.create(numRPS);
 }
 
-Void TComSPS::setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess )
-{
-  if( !getVuiParametersPresentFlag() )
-  {
-    return;
-  }
-
-  TComVUI *vui = getVuiParameters();
-  TComHRD *hrd = vui->getHrdParameters();
-
-  TimingInfo *timingInfo = vui->getTimingInfo();
-  timingInfo->setTimingInfoPresentFlag( true );
-  switch( frameRate )
-  {
-  case 24:
-    timingInfo->setNumUnitsInTick( 1125000 );    timingInfo->setTimeScale    ( 27000000 );
-    break;
-  case 25:
-    timingInfo->setNumUnitsInTick( 1080000 );    timingInfo->setTimeScale    ( 27000000 );
-    break;
-  case 30:
-    timingInfo->setNumUnitsInTick( 900900 );     timingInfo->setTimeScale    ( 27000000 );
-    break;
-  case 50:
-    timingInfo->setNumUnitsInTick( 540000 );     timingInfo->setTimeScale    ( 27000000 );
-    break;
-  case 60:
-    timingInfo->setNumUnitsInTick( 450450 );     timingInfo->setTimeScale    ( 27000000 );
-    break;
-  default:
-    timingInfo->setNumUnitsInTick( 1001 );       timingInfo->setTimeScale    ( 60000 );
-    break;
-  }
-
-  Bool rateCnt = ( bitRate > 0 );
-  hrd->setNalHrdParametersPresentFlag( rateCnt );
-  hrd->setVclHrdParametersPresentFlag( rateCnt );
-
-  hrd->setSubPicCpbParamsPresentFlag( ( numDU > 1 ) );
-
-  if( hrd->getSubPicCpbParamsPresentFlag() )
-  {
-    hrd->setTickDivisorMinus2( 100 - 2 );                          // 
-    hrd->setDuCpbRemovalDelayLengthMinus1( 7 );                    // 8-bit precision ( plus 1 for last DU in AU )
-    hrd->setSubPicCpbParamsInPicTimingSEIFlag( true );
-    hrd->setDpbOutputDelayDuLengthMinus1( 5 + 7 );                 // With sub-clock tick factor of 100, at least 7 bits to have the same value as AU dpb delay
-  }
-  else
-  {
-    hrd->setSubPicCpbParamsInPicTimingSEIFlag( false );  
-  }
-
-  hrd->setBitRateScale( 4 );                                       // in units of 2~( 6 + 4 ) = 1,024 bps
-  hrd->setCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
-  hrd->setDuCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
-  
-  hrd->setInitialCpbRemovalDelayLengthMinus1(15);                  // assuming 0.5 sec, log2( 90,000 * 0.5 ) = 16-bit
-  if( randomAccess )
-  {
-    hrd->setCpbRemovalDelayLengthMinus1(5);                        // 32 = 2^5 (plus 1)
-    hrd->setDpbOutputDelayLengthMinus1 (5);                        // 32 + 3 = 2^6
-  }
-  else
-  {
-    hrd->setCpbRemovalDelayLengthMinus1(9);                        // max. 2^10
-    hrd->setDpbOutputDelayLengthMinus1 (9);                        // max. 2^10
-  }
-
-/*
-   Note: only the case of "vps_max_temporal_layers_minus1 = 0" is supported.
-*/
-  Int i, j;
-  UInt birateValue, cpbSizeValue;
-  UInt ducpbSizeValue;
-  UInt duBitRateValue = 0;
-
-  for( i = 0; i < MAX_TLAYER; i ++ )
-  {
-    hrd->setFixedPicRateFlag( i, 1 );
-    hrd->setPicDurationInTcMinus1( i, 0 );
-    hrd->setLowDelayHrdFlag( i, 0 );
-    hrd->setCpbCntMinus1( i, 0 );
-
-    birateValue  = bitRate;
-    cpbSizeValue = bitRate;                                     // 1 second
-    ducpbSizeValue = bitRate/numDU;
-    duBitRateValue = bitRate;
-    for( j = 0; j < ( hrd->getCpbCntMinus1( i ) + 1 ); j ++ )
-    {
-      hrd->setBitRateValueMinus1( i, j, 0, ( birateValue  - 1 ) );
-      hrd->setCpbSizeValueMinus1( i, j, 0, ( cpbSizeValue - 1 ) );
-      hrd->setDuCpbSizeValueMinus1( i, j, 0, ( ducpbSizeValue - 1 ) );
-      hrd->setCbrFlag( i, j, 0, ( j == 0 ) );
-
-      hrd->setBitRateValueMinus1( i, j, 1, ( birateValue  - 1) );
-      hrd->setCpbSizeValueMinus1( i, j, 1, ( cpbSizeValue - 1 ) );
-      hrd->setDuCpbSizeValueMinus1( i, j, 1, ( ducpbSizeValue - 1 ) );
-      hrd->setDuBitRateValueMinus1( i, j, 1, ( duBitRateValue - 1 ) );
-      hrd->setCbrFlag( i, j, 1, ( j == 0 ) );
-    }
-  }
-}
 const Int TComSPS::m_winUnitX[]={1,2,2,1};
 const Int TComSPS::m_winUnitY[]={1,2,1,1};
 
+TComPPSRExt::TComPPSRExt()
+: m_log2MaxTransformSkipBlockSize      (2)
+, m_crossComponentPredictionEnabledFlag(false)
+, m_diffCuChromaQpOffsetDepth          (0)
+, m_chromaQpOffsetListLen              (0)
+// m_ChromaQpAdjTableIncludingNullEntry initialized below
+// m_log2SaoOffsetScale initialized below
+{
+  m_ChromaQpAdjTableIncludingNullEntry[0].u.comp.CbOffset = 0; // Array includes entry [0] for the null offset used when cu_chroma_qp_offset_flag=0. This is initialised here and never subsequently changed.
+  m_ChromaQpAdjTableIncludingNullEntry[0].u.comp.CrOffset = 0;
+  for(Int ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_log2SaoOffsetScale[ch] = 0;
+  }
+}
+
 TComPPS::TComPPS()
-: m_PPSId                       (0)
-, m_SPSId                       (0)
-, m_picInitQPMinus26            (0)
-, m_useDQP                      (false)
-, m_bConstrainedIntraPred       (false)
-, m_bSliceChromaQpFlag          (false)
-, m_pcSPS                       (NULL)
-, m_uiMaxCuDQPDepth             (0)
-, m_uiMinCuDQPSize              (0)
-, m_chromaCbQpOffset            (0)
-, m_chromaCrQpOffset            (0)
-, m_numRefIdxL0DefaultActive    (1)
-, m_numRefIdxL1DefaultActive    (1)
-, m_TransquantBypassEnableFlag  (false)
-, m_useTransformSkip             (false)
-, m_dependentSliceSegmentsEnabledFlag    (false)
-, m_tilesEnabledFlag               (false)
-, m_entropyCodingSyncEnabledFlag   (false)
-, m_loopFilterAcrossTilesEnabledFlag  (true)
-, m_uniformSpacingFlag           (false)
-, m_numTileColumnsMinus1         (0)
-, m_numTileRowsMinus1            (0)
-, m_numSubstreams               (1)
-, m_signHideFlag(0)
-, m_cabacInitPresentFlag        (false)
-, m_encCABACTableIdx            (I_SLICE)
-, m_sliceHeaderExtensionPresentFlag    (false)
-, m_loopFilterAcrossSlicesEnabledFlag (false)
-, m_listsModificationPresentFlag(  0)
-, m_numExtraSliceHeaderBits(0)
-#if H_MV
-, m_ppsInferScalingListFlag(false)
-, m_ppsScalingListRefLayerId(0)
-, m_pocResetInfoPresentFlag(false)
+: m_PPSId                            (0)
+, m_SPSId                            (0)
+, m_picInitQPMinus26                 (0)
+, m_useDQP                           (false)
+, m_bConstrainedIntraPred            (false)
+, m_bSliceChromaQpFlag               (false)
+, m_uiMaxCuDQPDepth                  (0)
+, m_chromaCbQpOffset                 (0)
+, m_chromaCrQpOffset                 (0)
+, m_numRefIdxL0DefaultActive         (1)
+, m_numRefIdxL1DefaultActive         (1)
+, m_TransquantBypassEnableFlag       (false)
+, m_useTransformSkip                 (false)
+, m_dependentSliceSegmentsEnabledFlag(false)
+, m_tilesEnabledFlag                 (false)
+, m_entropyCodingSyncEnabledFlag     (false)
+, m_loopFilterAcrossTilesEnabledFlag (true)
+, m_uniformSpacingFlag               (false)
+, m_numTileColumnsMinus1             (0)
+, m_numTileRowsMinus1                (0)
+, m_signHideFlag                     (false)
+, m_cabacInitPresentFlag             (false)
+, m_sliceHeaderExtensionPresentFlag  (false)
+, m_loopFilterAcrossSlicesEnabledFlag(false)
+, m_listsModificationPresentFlag     (0)
+, m_numExtraSliceHeaderBits          (0)
+#if NH_MV
+, m_ppsInferScalingListFlag          (false)
+, m_ppsScalingListRefLayerId         (0)
+, m_pocResetInfoPresentFlag          (false)
 #if H_3D
 , m_pcDLT(NULL)
 #endif
 #endif
-{
-  m_scalingList = new TComScalingList;
-
-#if H_MV
+
+{
+#if NH_MV
   m_ppsRangeExtensionsFlag     = false;
   m_ppsMultilayerExtensionFlag = false;
-#if !H_3D
-  m_ppsExtension6bits          = 0;
-#else
   m_pps3dExtensionFlag         = false;
   m_ppsExtension5bits          = 0;
 #endif
-#endif
+
 }
 
 TComPPS::~TComPPS()
 {
-  delete m_scalingList;
 }
 
@@ -3192,31 +3003,50 @@
 #endif
 
-#if H_MV
-Void TComSPS::inferRepFormat( TComVPS* vps, Int layerIdCurr )
+#if NH_MV
+Void TComSPS::inferRepFormat( TComVPS* vps, Int layerIdCurr, Bool encoder )
 {
   if ( getMultiLayerExtSpsFlag() )
-  { 
+  {    
     Int            repFormatIdx = getUpdateRepFormatFlag() ?  getSpsRepFormatIdx() : vps->getVpsRepFormatIdx( vps->getLayerIdInVps( layerIdCurr ) ) ;
-    TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
-    setChromaFormatIdc( repFormat->getChromaFormatVpsIdc() );         
-    //// ToDo: add when supported: 
-    // setSeperateColourPlaneFlag( repFormat->getSeparateColourPlaneVpsFlag() ) ; 
-
-    setPicWidthInLumaSamples ( repFormat->getPicWidthVpsInLumaSamples()  ); 
-    setPicHeightInLumaSamples( repFormat->getPicHeightVpsInLumaSamples() ); 
-
-    setBitDepthY             ( repFormat->getBitDepthVpsLumaMinus8()   + 8 ); 
-    setQpBDOffsetY           ( (Int) (6*( getBitDepthY() - 8 )) );
-
-    setBitDepthC             ( repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
-    setQpBDOffsetC           ( (Int) (6* ( getBitDepthC() -8 ) ) );
-    Window &spsConf    = getConformanceWindow();    
-
-    // Scaled later
-    spsConf.setScaledFlag( false ); 
-    spsConf.setWindowLeftOffset  ( repFormat->getConfWinVpsLeftOffset()    );
-    spsConf.setWindowRightOffset ( repFormat->getConfWinVpsRightOffset()   );
-    spsConf.setWindowTopOffset   ( repFormat->getConfWinVpsTopOffset()     );
-    spsConf.setWindowBottomOffset( repFormat->getConfWinVpsBottomOffset()  );    
+    const TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
+
+    if ( encoder )
+    {
+      assert( getChromaFormatIdc() ==  (ChromaFormat) repFormat->getChromaFormatVpsIdc() );         
+      //// ToDo: add when supported: 
+      // assert( getSeperateColourPlaneFlag( repFormat->getSeparateColourPlaneVpsFlag() ) ; 
+
+      assert( getPicWidthInLumaSamples()  ==  repFormat->getPicWidthVpsInLumaSamples()  ); 
+      assert( getPicHeightInLumaSamples() == repFormat->getPicHeightVpsInLumaSamples() ); 
+
+      assert( getBitDepth              ( CHANNEL_TYPE_LUMA ) == repFormat->getBitDepthVpsLumaMinus8()   + 8 ); 
+      assert( getQpBDOffset            ( CHANNEL_TYPE_LUMA ) == (Int) (6*( getBitDepth( CHANNEL_TYPE_LUMA ) - 8 )) );
+
+      assert( getBitDepth              ( CHANNEL_TYPE_CHROMA ) == repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
+      assert( getQpBDOffset            ( CHANNEL_TYPE_CHROMA ) == (Int) (6* ( getBitDepth( CHANNEL_TYPE_CHROMA ) -8 ) ) );
+    }
+    else
+    {
+      setChromaFormatIdc( (ChromaFormat) repFormat->getChromaFormatVpsIdc() );         
+      //// ToDo: add when supported: 
+      // setSeperateColourPlaneFlag( repFormat->getSeparateColourPlaneVpsFlag() ) ; 
+
+      setPicWidthInLumaSamples ( repFormat->getPicWidthVpsInLumaSamples()  ); 
+      setPicHeightInLumaSamples( repFormat->getPicHeightVpsInLumaSamples() ); 
+
+      setBitDepth              ( CHANNEL_TYPE_LUMA, repFormat->getBitDepthVpsLumaMinus8()   + 8 ); 
+      setQpBDOffset            ( CHANNEL_TYPE_LUMA, (Int) (6*( getBitDepth( CHANNEL_TYPE_LUMA ) - 8 )) );
+
+      setBitDepth              ( CHANNEL_TYPE_CHROMA, repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
+      setQpBDOffset            ( CHANNEL_TYPE_CHROMA, (Int) (6* ( getBitDepth( CHANNEL_TYPE_CHROMA ) -8 ) ) );
+      Window &spsConf    = getConformanceWindow();    
+
+      // Scaled later
+      spsConf.setScaledFlag( false ); 
+      spsConf.setWindowLeftOffset  ( repFormat->getConfWinVpsLeftOffset()    );
+      spsConf.setWindowRightOffset ( repFormat->getConfWinVpsRightOffset()   );
+      spsConf.setWindowTopOffset   ( repFormat->getConfWinVpsTopOffset()     );
+      spsConf.setWindowBottomOffset( repFormat->getConfWinVpsBottomOffset()  );            
+    }
 
    if ( getMultiLayerExtSpsFlag() && getUpdateRepFormatFlag() )
@@ -3229,6 +3059,6 @@
       assert( getPicHeightInLumaSamples() <= repFormat->getPicHeightVpsInLumaSamples()   ); 
 
-      assert( getBitDepthY()              <= repFormat->getBitDepthVpsLumaMinus8()   + 8 );         
-      assert( getBitDepthC()              <= repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
+      assert( getBitDepth( CHANNEL_TYPE_LUMA   )  <= repFormat->getBitDepthVpsLumaMinus8()   + 8 );         
+      assert( getBitDepth( CHANNEL_TYPE_CHROMA )  <= repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
     }
   }
@@ -3238,7 +3068,19 @@
   getConformanceWindow().scaleOffsets( scal );
   getVuiParameters()->getDefaultDisplayWindow().scaleOffsets( scal );
-}
-
-Void TComSPS::inferScalingList( TComSPS* spsSrc )
+
+  if (encoder && getMultiLayerExtSpsFlag() )
+  { 
+    Int            repFormatIdx = getUpdateRepFormatFlag() ?  getSpsRepFormatIdx() : vps->getVpsRepFormatIdx( vps->getLayerIdInVps( layerIdCurr ) ) ;
+    const TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
+
+    Window &spsConf    = getConformanceWindow();    
+    assert( spsConf.getWindowLeftOffset  () == repFormat->getConfWinVpsLeftOffset()    );
+    assert( spsConf.getWindowRightOffset () == repFormat->getConfWinVpsRightOffset()   );
+    assert( spsConf.getWindowTopOffset   () == repFormat->getConfWinVpsTopOffset()     );
+    assert( spsConf.getWindowBottomOffset() == repFormat->getConfWinVpsBottomOffset()  );            
+  }
+}
+
+Void TComSPS::inferScalingList( const TComSPS* spsSrc )
 {
   if ( getSpsInferScalingListFlag() ) 
@@ -3246,5 +3088,5 @@
     assert( spsSrc != NULL ); 
     assert( !spsSrc->getSpsInferScalingListFlag() );             
-    getScalingList()->inferFrom( spsSrc->getScalingList() ); 
+    getScalingList().inferFrom( (spsSrc->getScalingList()) ); 
   }
 }
@@ -3294,9 +3136,9 @@
 }
 
-Void TComSPS::checkRpsMaxNumPics( TComVPS* vps, Int currLayerId )
+Void TComSPS::checkRpsMaxNumPics( const TComVPS* vps, Int currLayerId ) const
 {
   for (Int i = 0; i < getRPSList()->getNumberOfReferencePictureSets(); i++ )
   {
-    TComReferencePictureSet* rps = getRPSList()->getReferencePictureSet( i ); 
+    const TComReferencePictureSet* rps = getRPSList()->getReferencePictureSet( i ); 
     if ( !rps->getInterRPSPrediction() )
     {
@@ -3327,4 +3169,5 @@
 }
 #endif
+
 
 TComReferencePictureSet::TComReferencePictureSet()
@@ -3333,8 +3176,8 @@
 , m_numberOfPositivePictures (0)
 , m_numberOfLongtermPictures (0)
-, m_interRPSPrediction (0) 
-, m_deltaRIdxMinus1 (0)   
-, m_deltaRPS (0) 
-, m_numRefIdc (0) 
+, m_interRPSPrediction (0)
+, m_deltaRIdxMinus1 (0)
+, m_deltaRPS (0)
+, m_numRefIdc (0)
 {
   ::memset( m_deltaPOC, 0, sizeof(m_deltaPOC) );
@@ -3342,4 +3185,8 @@
   ::memset( m_used, 0, sizeof(m_used) );
   ::memset( m_refIdc, 0, sizeof(m_refIdc) );
+  ::memset( m_bCheckLTMSB, 0, sizeof(m_bCheckLTMSB) );
+  ::memset( m_pocLSBLT, 0, sizeof(m_pocLSBLT) );
+  ::memset( m_deltaPOCMSBCycleLT, 0, sizeof(m_deltaPOCMSBCycleLT) );
+  ::memset( m_deltaPocMSBPresentFlag, 0, sizeof(m_deltaPocMSBPresentFlag) );
 }
 
@@ -3363,20 +3210,20 @@
 }
 
-Int TComReferencePictureSet::getUsed(Int bufferNum)
+Int TComReferencePictureSet::getUsed(Int bufferNum) const
 {
   return m_used[bufferNum];
 }
 
-Int TComReferencePictureSet::getDeltaPOC(Int bufferNum)
+Int TComReferencePictureSet::getDeltaPOC(Int bufferNum) const
 {
   return m_deltaPOC[bufferNum];
 }
 
-Int TComReferencePictureSet::getNumberOfPictures()
+Int TComReferencePictureSet::getNumberOfPictures() const
 {
   return m_numberOfPictures;
 }
 
-Int TComReferencePictureSet::getPOC(Int bufferNum)
+Int TComReferencePictureSet::getPOC(Int bufferNum) const
 {
   return m_POC[bufferNum];
@@ -3388,5 +3235,5 @@
 }
 
-Bool TComReferencePictureSet::getCheckLTMSBPresent(Int bufferNum)
+Bool TComReferencePictureSet::getCheckLTMSBPresent(Int bufferNum) const
 {
   return m_bCheckLTMSB[bufferNum];
@@ -3398,9 +3245,5 @@
 }
 
-/** set the reference idc value at uiBufferNum entry to the value of iRefIdc
- * \param uiBufferNum
- * \param iRefIdc
- * \returns Void
- */
+//! set the reference idc value at uiBufferNum entry to the value of iRefIdc
 Void TComReferencePictureSet::setRefIdc(Int bufferNum, Int refIdc)
 {
@@ -3408,9 +3251,6 @@
 }
 
-/** get the reference idc value at uiBufferNum
- * \param uiBufferNum
- * \returns Int
- */
-Int  TComReferencePictureSet::getRefIdc(Int bufferNum)
+//! get the reference idc value at uiBufferNum
+Int  TComReferencePictureSet::getRefIdc(Int bufferNum) const
 {
   return m_refIdc[bufferNum];
@@ -3426,5 +3266,5 @@
   // sort in increasing order (smallest first)
   for(Int j=1; j < getNumberOfPictures(); j++)
-  { 
+  {
     Int deltaPOC = getDeltaPOC(j);
     Bool used = getUsed(j);
@@ -3444,5 +3284,5 @@
   Int numNegPics = getNumberOfNegativePictures();
   for(Int j=0, k=numNegPics-1; j < numNegPics>>1; j++, k--)
-  { 
+  {
     Int deltaPOC = getDeltaPOC(j);
     Bool used = getUsed(j);
@@ -3458,5 +3298,5 @@
  * \returns Void
  */
-Void TComReferencePictureSet::printDeltaPOC()
+Void TComReferencePictureSet::printDeltaPOC() const
 {
   printf("DeltaPOC = { ");
@@ -3464,6 +3304,6 @@
   {
     printf("%d%s ", getDeltaPOC(j), (getUsed(j)==1)?"*":"");
-  } 
-  if (getInterRPSPrediction()) 
+  }
+  if (getInterRPSPrediction())
   {
     printf("}, RefIdc = { ");
@@ -3471,10 +3311,11 @@
     {
       printf("%d ", getRefIdc(j));
-    } 
+    }
   }
   printf("}\n");
 }
-#if H_MV
-Void TComReferencePictureSet::checkMaxNumPics( Bool vpsExtensionFlag, Int maxNumPics, Int nuhLayerId, Int spsMaxDecPicBufferingMinus1 )
+
+#if NH_MV
+Void TComReferencePictureSet::checkMaxNumPics( Bool vpsExtensionFlag, Int maxNumPics, Int nuhLayerId, Int spsMaxDecPicBufferingMinus1 ) const
 {
   assert( getNumberOfPictures() >= 0 ); 
@@ -3491,49 +3332,10 @@
 #endif
 
-TComRPSList::TComRPSList()
-:m_referencePictureSets (NULL)
-{
-}
-
-TComRPSList::~TComRPSList()
-{
-}
-
-Void TComRPSList::create( Int numberOfReferencePictureSets)
-{
-  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
-  m_referencePictureSets = new TComReferencePictureSet[numberOfReferencePictureSets];
-}
-
-Void TComRPSList::destroy()
-{
-  if (m_referencePictureSets)
-  {
-    delete [] m_referencePictureSets;
-  }
-  m_numberOfReferencePictureSets = 0;
-  m_referencePictureSets = NULL;
-}
-
-
-
-TComReferencePictureSet* TComRPSList::getReferencePictureSet(Int referencePictureSetNum)
-{
-  return &m_referencePictureSets[referencePictureSetNum];
-}
-
-Int TComRPSList::getNumberOfReferencePictureSets()
-{
-  return m_numberOfReferencePictureSets;
-}
-
-Void TComRPSList::setNumberOfReferencePictureSets(Int numberOfReferencePictureSets)
-{
-  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
-}
+
+
 
 TComRefPicListModification::TComRefPicListModification()
-: m_bRefPicListModificationFlagL0 (false)
-, m_bRefPicListModificationFlagL1 (false)
+: m_refPicListModificationFlagL0 (false)
+, m_refPicListModificationFlagL1 (false)
 {
   ::memset( m_RefPicSetIdxL0, 0, sizeof(m_RefPicSetIdxL0) );
@@ -3547,20 +3349,22 @@
 TComScalingList::TComScalingList()
 {
-  init();
-}
-TComScalingList::~TComScalingList()
-{
-  destroy();
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
+    {
+      m_scalingListCoef[sizeId][listId].resize(min<Int>(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+    }
+  }
 }
 
 /** set default quantization matrix to array
 */
-Void TComSlice::setDefaultScalingList()
+Void TComScalingList::setDefaultScalingList()
 {
   for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
   {
-    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
-    {
-      getScalingList()->processDefaultMatrix(sizeId, listId);
+    for(UInt listId=0;listId<SCALING_LIST_NUM;listId++)
+    {
+      processDefaultMatrix(sizeId, listId);
     }
   }
@@ -3569,5 +3373,5 @@
  * \returns true if use default quantization matrix in all size
 */
-Bool TComSlice::checkDefaultScalingList()
+Bool TComScalingList::checkDefaultScalingList()
 {
   UInt defaultCounter=0;
@@ -3575,8 +3379,8 @@
   for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
   {
-    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
-    {
-      if( !memcmp(getScalingList()->getScalingListAddress(sizeId,listId), getScalingList()->getScalingListDefaultAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
-     && ((sizeId < SCALING_LIST_16x16) || (getScalingList()->getScalingListDC(sizeId,listId) == 16))) // check DC value
+    for(UInt listId=0;listId<SCALING_LIST_NUM;listId++)
+    {
+      if( !memcmp(getScalingListAddress(sizeId,listId), getScalingListDefaultAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
+     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == 16))) // check DC value
       {
         defaultCounter++;
@@ -3584,8 +3388,9 @@
     }
   }
-  return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM - 4)) ? false : true; // -4 for 32x32
-}
-
-#if H_MV
+
+  return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM )) ? false : true;
+}
+
+#if NH_MV
 Void TComSlice::createInterLayerReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1 )
 {
@@ -3665,5 +3470,5 @@
 }
 
-TComPic* TComSlice::getPicFromRefPicSetInterLayer(Int setIdc, Int layerId )
+TComPic* TComSlice::getPicFromRefPicSetInterLayer(Int setIdc, Int layerId ) const
 {
   assert ( setIdc == 0 || setIdc == 1);   
@@ -3685,8 +3490,8 @@
 
 
-Int  TComSlice::getRefLayerPicFlag( Int i ) 
-{
-  TComVPS* vps = getVPS(); 
-#if H_3D
+Int  TComSlice::getRefLayerPicFlag( Int i ) const
+{
+  const TComVPS* vps = getVPS(); 
+#if NH_3D
   Int refLayerIdx = vps->getLayerIdInVps( vps->getIdRefListLayer( getLayerId(), i ) ); 
 #else
@@ -3699,9 +3504,9 @@
 }    
 
-Int TComSlice::getRefLayerPicIdc( Int j ) 
+Int TComSlice::getRefLayerPicIdc( Int j ) const
 {  
   Int refLayerPicIdc = -1; 
   Int curj = 0; 
-#if H_3D
+#if NH_3D
   for( Int i = 0;  i < getVPS()->getNumRefListLayers( getLayerId()) ; i++ )
 #else
@@ -3725,8 +3530,8 @@
 }
 
-Int  TComSlice::getNumRefLayerPics( )
+Int  TComSlice::getNumRefLayerPics( ) const
 {  
   Int numRefLayerPics = 0; 
-#if H_3D
+#if NH_3D
   for( Int i = 0;  i < getVPS()->getNumRefListLayers( getLayerId()) ; i++ )
 #else
@@ -3741,5 +3546,5 @@
 
 
-Int TComSlice::getNumActiveRefLayerPics()
+Int TComSlice::getNumActiveRefLayerPics() const
 {
   Int numActiveRefLayerPics; 
@@ -3757,5 +3562,5 @@
     numActiveRefLayerPics = 0; 
   }
-#if H_3D
+#if NH_3D
   else if( getVPS()->getMaxOneActiveRefLayerFlag() || getVPS()->getNumRefListLayers( getLayerId() ) == 1 )
 #else
@@ -3772,7 +3577,7 @@
 }
 
-Int TComSlice::getRefPicLayerId( Int i )
-{
-#if H_3D
+Int TComSlice::getRefPicLayerId( Int i ) const
+{
+#if NH_3D
   return getVPS()->getIdRefListLayer( getLayerId(), getInterLayerPredLayerIdc( i ) );
 #else
@@ -3861,5 +3666,5 @@
         TComPic* picV = getIvPic( getIsDepth(), getVPS()->getViewIndex( layerIdInNuh ) );
         assert( picV != NULL ); 
-        std::vector<Int> pocsInCurrRPSsPicV = picV->getSlice(0)->getPocsInCurrRPSs(); 
+        IntAry1d pocsInCurrRPSsPicV = picV->getSlice(0)->getPocsInCurrRPSs(); 
         Bool refRpRefAvailFlag = false; 
         for (Int idx = 0; idx < pocsInCurrRPSsPicV.size(); idx++)
@@ -4025,5 +3830,5 @@
 }
 #endif
-#if H_3D
+#if NH_3D
 Void TComSlice::setIvPicLists( TComPicLists* m_ivPicLists )
 {
@@ -4050,7 +3855,10 @@
 #endif
 
+  Int bitDepthY = getSPS()->getBitDepth(CHANNEL_TYPE_LUMA);
 
   if( !setupLUT )
+  {
     return; 
+  }
 
   m_numViews = getVPS()->getNumViews(); 
@@ -4061,5 +3869,5 @@
     for ( Int i = 0; i < getVPS()->getNumViews(); i++ )
     {
-      m_depthToDisparityB[ i ] = new Int[ Int(1 << g_bitDepthY) ]; 
+      m_depthToDisparityB[ i ] = new Int[ Int(1 << bitDepthY) ]; 
     }
   }
@@ -4071,5 +3879,5 @@
     for ( Int i = 0; i < m_numViews; i++ )
     {
-      m_depthToDisparityF[ i ] = new Int[ Int(1 << g_bitDepthY) ]; 
+      m_depthToDisparityF[ i ] = new Int[ Int(1 << bitDepthY) ]; 
     }
   }
@@ -4078,14 +3886,14 @@
   assert( m_depthToDisparityF != NULL ); 
 
-  TComVPS* vps = getVPS(); 
-
-  Int log2Div = g_bitDepthY - 1 + vps->getCpPrecision();
+  const TComVPS* vps = getVPS(); 
+
+  Int log2Div = bitDepthY - 1 + vps->getCpPrecision();
   Int voiInVps = vps->getVoiInVps( getViewIndex() ); 
   Bool camParaSH = vps->getCpInSliceSegmentHeaderFlag( voiInVps );  
 
-  Int* codScale     = camParaSH ? m_aaiCodedScale [ 0 ] : vps->getCodedScale    ( voiInVps ); 
-  Int* codOffset    = camParaSH ? m_aaiCodedOffset[ 0 ] : vps->getCodedOffset   ( voiInVps ); 
-  Int* invCodScale  = camParaSH ? m_aaiCodedScale [ 1 ] : vps->getInvCodedScale ( voiInVps ); 
-  Int* invCodOffset = camParaSH ? m_aaiCodedOffset[ 1 ] : vps->getInvCodedOffset( voiInVps ); 
+  const IntAry1d codScale     = camParaSH ? m_aaiCodedScale [ 0 ] : vps->getCodedScale    ( voiInVps ); 
+  const IntAry1d codOffset    = camParaSH ? m_aaiCodedOffset[ 0 ] : vps->getCodedOffset   ( voiInVps ); 
+  const IntAry1d invCodScale  = camParaSH ? m_aaiCodedScale [ 1 ] : vps->getInvCodedScale ( voiInVps ); 
+  const IntAry1d invCodOffset = camParaSH ? m_aaiCodedOffset[ 1 ] : vps->getInvCodedOffset( voiInVps ); 
 
 
@@ -4100,10 +3908,10 @@
     }
 #endif
-    for ( Int d = 0; d <= ( ( 1 << g_bitDepthY ) - 1 ); d++ )
+    for ( Int d = 0; d <= ( ( 1 << bitDepthY ) - 1 ); d++ )
     {      
-      Int offset =    ( codOffset  [ iInVoi ] << g_bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
+      Int offset =    ( codOffset  [ iInVoi ] << bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
       m_depthToDisparityB[ iInVoi ][ d ] = ( codScale [ iInVoi ] * d + offset ) >> log2Div; 
 
-      Int invOffset = ( invCodOffset[ iInVoi ] << g_bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
+      Int invOffset = ( invCodOffset[ iInVoi ] << bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
       m_depthToDisparityF[ iInVoi ][ d ] = ( invCodScale[ iInVoi ] * d + invOffset ) >> log2Div; 
     }
@@ -4114,6 +3922,6 @@
 
 
-#if H_MV
-Void TComSlice::checkCrossLayerBlaFlag()
+#if NH_MV
+Void TComSlice::checkCrossLayerBlaFlag() const
 {
   // cross_layer_bla_flag shall be equal to 0 for pictures with nal_unit_type not equal to IDR_W_RADL or IDR_N_LP or with nuh_layer_id not equal to 0.
@@ -4147,5 +3955,5 @@
 
 
-#if H_3D
+#if NH_3D
 Void TComSlice::init3dToolParameters()
 {
@@ -4154,5 +3962,5 @@
   Bool nRLLG0 =  ( getVPS()->getNumRefListLayers( getLayerId() ) > 0 );     
 
-  TComSps3dExtension* sps3dExt = getSPS()->getSps3dExtension();
+  const TComSps3dExtension* sps3dExt = getSPS()->getSps3dExtension();
 
   m_ivMvPredFlag           = sps3dExt->getIvMvPredFlag         ( depthFlag ) && nRLLG0                       ;                             
@@ -4197,5 +4005,5 @@
 }
 
-Void TComSlice::deriveInCmpPredAndCpAvailFlag()
+Void TComSlice::deriveInCmpPredAndCpAvailFlag( )
 {
   Int numCurCmpLIds = getIsDepth() ? 1 : getNumActiveRefLayerPics(); 
@@ -4248,5 +4056,5 @@
   else 
   {
-    TComSps3dExtension* sps3dExt = getSPS()->getSps3dExtension();
+    const TComSps3dExtension* sps3dExt = getSPS()->getSps3dExtension();
     if( !getIsDepth() )
     {
@@ -4280,9 +4088,8 @@
 #endif
 
-
 /** get scaling matrix from RefMatrixID
- * \param sizeId size index
- * \param Index of input matrix
- * \param Index of reference matrix
+ * \param sizeId    size index
+ * \param listId    index of input matrix
+ * \param refListId index of reference matrix
  */
 Void TComScalingList::processRefMatrix( UInt sizeId, UInt listId , UInt refListId )
@@ -4291,132 +4098,228 @@
 }
 
-/** parse syntax infomation 
- *  \param pchFile syntax infomation
- *  \returns false if successful
- */
+Void TComScalingList::checkPredMode(UInt sizeId, UInt listId)
+{
+  Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
+
+  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx-=predListStep)
+  {
+    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
+      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
+     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
+    {
+      setRefMatrixId(sizeId, listId, predListIdx);
+      setScalingListPredModeFlag(sizeId, listId, false);
+      return;
+    }
+  }
+  setScalingListPredModeFlag(sizeId, listId, true);
+}
+
+static Void outputScalingListHelp(std::ostream &os)
+{
+  os << "The scaling list file specifies all matrices and their DC values; none can be missing,\n"
+         "but their order is arbitrary.\n\n"
+         "The matrices are specified by:\n"
+         "<matrix name><unchecked data>\n"
+         "  <value>,<value>,<value>,....\n\n"
+         "  Line-feeds can be added arbitrarily between values, and the number of values needs to be\n"
+         "  at least the number of entries for the matrix (superfluous entries are ignored).\n"
+         "  The <unchecked data> is text on the same line as the matrix that is not checked\n"
+         "  except to ensure that the matrix name token is unique. It is recommended that it is ' ='\n"
+         "  The values in the matrices are the absolute values (0-255), not the delta values as\n"
+         "  exchanged between the encoder and decoder\n\n"
+         "The DC values (for matrix sizes larger than 8x8) are specified by:\n"
+         "<matrix name>_DC<unchecked data>\n"
+         "  <value>\n";
+
+  os << "The permitted matrix names are:\n";
+  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
+  {
+    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
+    {
+      if ((sizeIdc!=SCALING_LIST_32x32) || (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) == 0))
+      {
+        os << "  " << MatrixType[sizeIdc][listIdc] << '\n';
+      }
+    }
+  }
+}
+
+Void TComScalingList::outputScalingLists(std::ostream &os) const
+{
+  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
+  {
+    const UInt size = min(8,4<<(sizeIdc));
+    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
+    {
+      if ((sizeIdc!=SCALING_LIST_32x32) || (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) == 0))
+      {
+        const Int *src = getScalingListAddress(sizeIdc, listIdc);
+        os << (MatrixType[sizeIdc][listIdc]) << " =\n  ";
+        for(UInt y=0; y<size; y++)
+        {
+          for(UInt x=0; x<size; x++, src++)
+          {
+            os << std::setw(3) << (*src) << ", ";
+          }
+          os << (y+1<size?"\n  ":"\n");
+        }
+        if(sizeIdc > SCALING_LIST_8x8)
+        {
+          os << MatrixType_DC[sizeIdc][listIdc] << " = \n  " << std::setw(3) << getScalingListDC(sizeIdc, listIdc) << "\n";
+        }
+        os << "\n";
+      }
+    }
+  }
+}
+
 Bool TComScalingList::xParseScalingList(Char* pchFile)
 {
-  FILE *fp;
-  Char line[1024];
-  UInt sizeIdc,listIdc;
-  UInt i,size = 0;
-  Int *src=0,data;
-  Char *ret;
-  UInt  retval;
-
-  if((fp = fopen(pchFile,"r")) == (FILE*)NULL)
-  {
-    printf("can't open file %s :: set Default Matrix\n",pchFile);
+  static const Int LINE_SIZE=1024;
+  FILE *fp = NULL;
+  Char line[LINE_SIZE];
+
+  if (pchFile == NULL)
+  {
+    fprintf(stderr, "Error: no scaling list file specified. Help on scaling lists being output\n");
+    outputScalingListHelp(std::cout);
+    std::cout << "\n\nExample scaling list file using default values:\n\n";
+    outputScalingLists(std::cout);
+    exit (1);
     return true;
   }
-
-  for(sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
-  {
-    size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeIdc]);
-    for(listIdc = 0; listIdc < g_scalingListNum[sizeIdc]; listIdc++)
-    {
-      src = getScalingListAddress(sizeIdc, listIdc);
-
-      fseek(fp,0,0);
-      do 
-      {
-        ret = fgets(line, 1024, fp);
-        if ((ret==NULL)||(strstr(line, MatrixType[sizeIdc][listIdc])==NULL && feof(fp)))
-        {
-          printf("Error: can't read Matrix :: set Default Matrix\n");
-          return true;
-        }
-      }
-      while (strstr(line, MatrixType[sizeIdc][listIdc]) == NULL);
-      for (i=0; i<size; i++)
-      {
-        retval = fscanf(fp, "%d,", &data);
-        if (retval!=1)
-        {
-          printf("Error: can't read Matrix :: set Default Matrix\n");
-          return true;
-        }
-        src[i] = data;
-      }
-      //set DC value for default matrix check
-      setScalingListDC(sizeIdc,listIdc,src[0]);
-
-      if(sizeIdc > SCALING_LIST_8x8)
-      {
-        fseek(fp,0,0);
-        do 
-        {
-          ret = fgets(line, 1024, fp);
-          if ((ret==NULL)||(strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL && feof(fp)))
+  else if ((fp = fopen(pchFile,"r")) == (FILE*)NULL)
+  {
+    fprintf(stderr, "Error: cannot open scaling list file %s for reading\n",pchFile);
+    return true;
+  }
+
+  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
+  {
+    const UInt size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeIdc]);
+
+    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
+    {
+      Int * const src = getScalingListAddress(sizeIdc, listIdc);
+
+      if ((sizeIdc==SCALING_LIST_32x32) && (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) != 0)) // derive chroma32x32 from chroma16x16
+      {
+        const Int *srcNextSmallerSize = getScalingListAddress(sizeIdc-1, listIdc);
+        for(UInt i=0; i<size; i++)
+        {
+          src[i] = srcNextSmallerSize[i];
+        }
+        setScalingListDC(sizeIdc,listIdc,(sizeIdc > SCALING_LIST_8x8) ? getScalingListDC(sizeIdc-1, listIdc) : src[0]);
+      }
+      else
+      {
+        {
+          fseek(fp, 0, SEEK_SET);
+          Bool bFound=false;
+          while ((!feof(fp)) && (!bFound))
           {
-            printf("Error: can't read DC :: set Default Matrix\n");
+            Char *ret = fgets(line, LINE_SIZE, fp);
+            Char *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType[sizeIdc][listIdc]);
+            // This could be a match against the DC string as well, so verify it isn't
+            if (findNamePosition!= NULL && (MatrixType_DC[sizeIdc][listIdc]==NULL || strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL))
+            {
+              bFound=true;
+            }
+          }
+          if (!bFound)
+          {
+            fprintf(stderr, "Error: cannot find Matrix %s from scaling list file %s\n", MatrixType[sizeIdc][listIdc], pchFile);
             return true;
           }
         }
-        while (strstr(line, MatrixType_DC[sizeIdc][listIdc]) == NULL);
-        retval = fscanf(fp, "%d,", &data);
-        if (retval!=1)
-        {
-          printf("Error: can't read Matrix :: set Default Matrix\n");
-          return true;
-        }
-        //overwrite DC value when size of matrix is larger than 16x16
-        setScalingListDC(sizeIdc,listIdc,data);
-      }
-    }
-  }
+        for (UInt i=0; i<size; i++)
+        {
+          Int data;
+          if (fscanf(fp, "%d,", &data)!=1)
+          {
+            fprintf(stderr, "Error: cannot read value #%d for Matrix %s from scaling list file %s at file position %ld\n", i, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            return true;
+          }
+          if (data<0 || data>255)
+          {
+            fprintf(stderr, "Error: QMatrix entry #%d of value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", i, data, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            return true;
+          }
+          src[i] = data;
+        }
+
+        //set DC value for default matrix check
+        setScalingListDC(sizeIdc,listIdc,src[0]);
+
+        if(sizeIdc > SCALING_LIST_8x8)
+        {
+          {
+            fseek(fp, 0, SEEK_SET);
+            Bool bFound=false;
+            while ((!feof(fp)) && (!bFound))
+            {
+              Char *ret = fgets(line, LINE_SIZE, fp);
+              Char *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType_DC[sizeIdc][listIdc]);
+              if (findNamePosition!= NULL)
+              {
+                // This won't be a match against the non-DC string.
+                bFound=true;
+              }
+            }
+            if (!bFound)
+            {
+              fprintf(stderr, "Error: cannot find DC Matrix %s from scaling list file %s\n", MatrixType_DC[sizeIdc][listIdc], pchFile);
+              return true;
+            }
+          }
+          Int data;
+          if (fscanf(fp, "%d,", &data)!=1)
+          {
+            fprintf(stderr, "Error: cannot read DC %s from scaling list file %s at file position %ld\n", MatrixType_DC[sizeIdc][listIdc], pchFile, ftell(fp));
+            return true;
+          }
+          if (data<0 || data>255)
+          {
+            fprintf(stderr, "Error: DC value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", data, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            return true;
+          }
+          //overwrite DC value when size of matrix is larger than 16x16
+          setScalingListDC(sizeIdc,listIdc,data);
+        }
+      }
+    }
+  }
+//  std::cout << "\n\nRead scaling lists of:\n\n";
+//  outputScalingLists(std::cout);
+
   fclose(fp);
   return false;
 }
 
-#if H_MV
-Void TComScalingList::inferFrom( TComScalingList* srcScLi )
+#if NH_MV
+Void TComScalingList::inferFrom( const TComScalingList& srcScLi )
 {
   for(Int sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
   {
-    for(Int listId = 0; listId <  g_scalingListNum[sizeId]; listId++)
-    {
-      setRefMatrixId  (sizeId,listId, srcScLi->getRefMatrixId  (sizeId,listId));
-      setScalingListDC(sizeId,listId, srcScLi->getScalingListDC(sizeId,listId));          
-      ::memcpy(getScalingListAddress(sizeId, listId),srcScLi->getScalingListAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
-    }
-  }
-}
-#endif
-/** initialization process of quantization matrix array
- */
-Void TComScalingList::init()
-{
-  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
-  {
-    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
-    {
-      m_scalingListCoef[sizeId][listId] = new Int [min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])];
-    }
-  }
-  m_scalingListCoef[SCALING_LIST_32x32][3] = m_scalingListCoef[SCALING_LIST_32x32][1]; // copy address for 32x32
-}
-
-/** destroy quantization matrix array
- */
-Void TComScalingList::destroy()
-{
-  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
-  {
-    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
-    {
-      if(m_scalingListCoef[sizeId][listId]) delete [] m_scalingListCoef[sizeId][listId];
-    }
-  }
-}
-
-/** get default address of quantization matrix 
+    for(Int listId = 0; listId <  SCALING_LIST_NUM; listId++)
+    {
+      setRefMatrixId  (sizeId,listId, srcScLi.getRefMatrixId  (sizeId,listId));
+      setScalingListDC(sizeId,listId, srcScLi.getScalingListDC(sizeId,listId));          
+      ::memcpy(getScalingListAddress(sizeId, listId),srcScLi.getScalingListAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+    }
+  }
+}
+#endif
+
+
+/** get default address of quantization matrix
  * \param sizeId size index
  * \param listId list index
  * \returns pointer of quantization matrix
  */
-Int* TComScalingList::getScalingListDefaultAddress(UInt sizeId, UInt listId)
-{
-  Int *src = 0;
+const Int* TComScalingList::getScalingListDefaultAddress(UInt sizeId, UInt listId)
+{
+  const Int *src = 0;
   switch(sizeId)
   {
@@ -4425,11 +4328,7 @@
       break;
     case SCALING_LIST_8x8:
-      src = (listId<3) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
-      break;
     case SCALING_LIST_16x16:
-      src = (listId<3) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
-      break;
     case SCALING_LIST_32x32:
-      src = (listId<1) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
+      src = (listId < (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) ) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
       break;
     default:
@@ -4443,5 +4342,5 @@
 /** process of default matrix
  * \param sizeId size index
- * \param Index of input matrix
+ * \param listId index of input matrix
  */
 Void TComScalingList::processDefaultMatrix(UInt sizeId, UInt listId)
@@ -4457,5 +4356,5 @@
   for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
   {
-    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
     {
       //check default matrix?
@@ -4473,14 +4372,12 @@
 , m_ppsMap(MAX_NUM_PPS)
 , m_activeVPSId(-1)
-#if !H_MV
+#if !NH_MV
 , m_activeSPSId(-1)
-, m_activePPSId(-1)
-{
-#else
-{
+#endif
+{
+#if NH_MV  
   for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
-  {
-    m_activeSPSId[ i ] = -1; 
-    m_activePPSId[ i ] = -1; 
+  {    
+    m_activeSPSId[i] = -1; 
   }
 #endif
@@ -4494,39 +4391,41 @@
 //! activate a SPS from a active parameter sets SEI message
 //! \returns true, if activation is successful
-#if H_MV
-Bool ParameterSetManager::activateSPSWithSEI(Int spsId, Int layerId )
+#if NH_MV
+//Bool ParameterSetManager::activateSPSWithSEI(Int spsId, Int layerId )
 #else
-Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
-#endif
-{
-  TComSPS *sps = m_spsMap.getPS(spsId);
-  if (sps)
-  {
-    Int vpsId = sps->getVPSId();
-    if (m_vpsMap.getPS(vpsId))
-    {
-      m_activeVPSId = vpsId;
-#if H_MV
-      m_activeSPSId[ layerId ] = spsId;
+//Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
+#endif
+//{
+//TComSPS *sps = m_spsMap.getPS(spsId);
+//  if (sps)
+//  {
+//    Int vpsId = sps->getVPSId();
+//    TComVPS *vps = m_vpsMap.getPS(vpsId);
+//    if (vps)
+//    {
+#if NH_MV
+//      m_activeVPS = *(vps);
+//      m_activeSPS[ layerId ] = *(sps);
 #else
-      m_activeSPSId = spsId;
-#endif
-      return true;
-    }
-    else
-    {
-      printf("Warning: tried to activate SPS using an Active parameter sets SEI message. Referenced VPS does not exist.");
-    }
-  }
-  else
-  {
-    printf("Warning: tried to activate non-existing SPS using an Active parameter sets SEI message.");
-  }
-  return false;
-}
+//      m_activeVPS = *(vps);
+//      m_activeSPS = *(sps);
+#endif
+//      return true;
+//    }
+//    else
+//    {
+//      printf("Warning: tried to activate SPS using an Active parameter sets SEI message. Referenced VPS does not exist.");
+//    }
+//  }
+//  else
+//  {
+//    printf("Warning: tried to activate non-existing SPS using an Active parameter sets SEI message.");
+//  }
+//  return false;
+//}
 
 //! activate a PPS and depending on isIDR parameter also SPS and VPS
 //! \returns true, if activation is successful
-#if H_MV
+#if NH_MV
 Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP, Int layerId )
 #else
@@ -4538,44 +4437,45 @@
   {
     Int spsId = pps->getSPSId();
-#if H_MV
-    if (!isIRAP && (spsId != m_activeSPSId[ layerId ]))
+#if NH_MV
+    if (!isIRAP && (spsId != m_activeSPSId[ layerId ] ))
 #else
-    if (!isIRAP && (spsId != m_activeSPSId))
-#endif
-    {
-      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IRAP.");
-      return false;
-    }
-
-    TComSPS *sps = m_spsMap.getPS(spsId);
-    if (sps)
-    {
-      Int vpsId = sps->getVPSId();
-      if (!isIRAP && (vpsId != m_activeVPSId))
-      {
-        printf("Warning: tried to activate PPS referring to a inactive VPS at non-IRAP.");
-        return false;
-      }
-      if (m_vpsMap.getPS(vpsId))
-      {
-#if H_MV
-        m_activePPSId[ layerId ] = ppsId;
-        m_activeVPSId = vpsId;
-        m_activeSPSId[ layerId ] = spsId;
+    if (!isIRAP && (spsId != m_activeSPSId ))
+#endif
+    {
+      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IDR.");
+    }
+    else
+    {
+      TComSPS *sps = m_spsMap.getPS(spsId);
+      if (sps)
+      {
+        Int vpsId = sps->getVPSId();
+        if (!isIRAP && (vpsId != m_activeVPSId ))
+        {
+          printf("Warning: tried to activate PPS referring to a inactive VPS at non-IDR.");
+        }
+        else
+        {
+          TComVPS *vps =m_vpsMap.getPS(vpsId);
+          if (vps)
+          {
+            m_activeVPSId = vpsId;
+#if NH_MV
+            m_activeSPSId[layerId] = spsId;
 #else
-        m_activePPSId = ppsId;
-        m_activeVPSId = vpsId;
-        m_activeSPSId = spsId;
-#endif
-        return true;
+            m_activeSPSId = spsId;
+#endif
+            return true;
+          }
+          else
+          {
+            printf("Warning: tried to activate PPS that refers to a non-existing VPS.");
+          }
+        }
       }
       else
       {
-        printf("Warning: tried to activate PPS that refers to a non-existing VPS.");
-      }
-    }
-    else
-    {
-      printf("Warning: tried to activate a PPS that refers to a non-existing SPS.");
+       printf("Warning: tried to activate a PPS that refers to a non-existing SPS.");
+      }
     }
   }
@@ -4584,4 +4484,13 @@
     printf("Warning: tried to activate non-existing PPS.");
   }
+
+  // Failed to activate if reach here.
+#if NH_MV
+  m_activeSPSId[layerId]=-1;
+#else
+  m_activeSPSId=-1;
+#endif
+  m_activeVPSId=-1;
+
   return false;
 }
@@ -4589,12 +4498,15 @@
 ProfileTierLevel::ProfileTierLevel()
   : m_profileSpace    (0)
-  , m_tierFlag        (false)
-  , m_profileIdc      (0)
-  , m_levelIdc        (0)
-, m_progressiveSourceFlag  (false)
-, m_interlacedSourceFlag   (false)
-, m_nonPackedConstraintFlag(false)
-, m_frameOnlyConstraintFlag(false)
-#if H_MV
+  , m_tierFlag        (Level::MAIN)
+  , m_profileIdc      (Profile::NONE)
+  , m_levelIdc        (Level::NONE)
+  , m_progressiveSourceFlag  (false)
+  , m_interlacedSourceFlag   (false)
+  , m_nonPackedConstraintFlag(false)
+  , m_frameOnlyConstraintFlag(false)
+#if NH_MV
+  , m_intraConstraintFlag         ( false )
+  , m_onePictureOnlyConstraintFlag( false )
+  , m_lowerBitRateConstraintFlag  ( false )
   , m_max12bitConstraintFlag      ( false )
   , m_max10bitConstraintFlag      ( false )
@@ -4602,8 +4514,5 @@
   , m_max422chromaConstraintFlag  ( false )
   , m_max420chromaConstraintFlag  ( false )
-  , m_maxMonochromeConstraintFlag ( false )
-  , m_intraConstraintFlag         ( false )
-  , m_onePictureOnlyConstraintFlag( false )
-  , m_lowerBitRateConstraintFlag  ( false )
+  , m_maxMonochromeConstraintFlag ( false )  
   , m_inbldFlag                   ( false )
 #endif
@@ -4612,6 +4521,6 @@
 }
 
-#if H_MV
-Bool ProfileTierLevel::getV2ConstraintsPresentFlag()
+#if NH_MV
+Bool ProfileTierLevel::getV2ConstraintsPresentFlag() const
 {
   return ( 
@@ -4621,5 +4530,5 @@
 }
 
-Bool ProfileTierLevel::getInbldPresentFlag()
+Bool ProfileTierLevel::getInbldPresentFlag() const
 {
   return ( 
@@ -4665,5 +4574,32 @@
 }
 
-#if H_MV
+Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> &newData)
+{
+  if (!bChanged)
+  {
+    if ((pOldData==0 && pOldData!=0) || (pOldData!=0 && pOldData==0))
+    {
+      bChanged=true;
+    }
+    else if (pOldData!=0 && pOldData!=0)
+    {
+      // compare the two
+      if (pOldData->size() != pOldData->size())
+      {
+        bChanged=true;
+      }
+      else
+      {
+        const UChar *pNewDataArray=&(newData)[0];
+        const UChar *pOldDataArray=&(*pOldData)[0];
+        if (memcmp(pOldDataArray, pNewDataArray, pOldData->size()))
+        {
+          bChanged=true;
+        }
+      }
+    }
+  }
+}
+#if NH_MV
 Void TComPTL::inferGeneralValues(Bool profilePresentFlag, Int k, TComPTL* refPTL)
 {
@@ -4754,16 +4690,31 @@
 
 #endif
+
 //! \}
 
-#if H_MV
-TComVPSVUI::TComVPSVUI()
+#if NH_MV
+Void TComVPSVUI::init( Int numLayerSets, Int maxNumSubLayers, Int maxNumLayers )
 {
   m_crossLayerIrapAlignedFlag = true; 
   m_allLayersIdrAlignedFlag   = false; 
-  m_bitRatePresentVpsFlag = false;
-  m_picRatePresentVpsFlag = false;
-  for ( Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++)
-  {    
-    for ( Int j = 0; j < MAX_TLAYER; j++)
+  m_bitRatePresentVpsFlag     = false;
+  m_picRatePresentVpsFlag     = false;
+
+  m_bitRatePresentFlag          .resize(numLayerSets); 
+  m_picRatePresentFlag          .resize(numLayerSets); 
+  m_avgBitRate                  .resize(numLayerSets); 
+  m_maxBitRate                  .resize(numLayerSets); 
+  m_constantPicRateIdc          .resize(numLayerSets); 
+  m_avgPicRate                  .resize(numLayerSets); 
+
+  for ( Int i = 0; i < numLayerSets; i++)
+  { 
+    m_bitRatePresentFlag          [i].resize( maxNumSubLayers); 
+    m_picRatePresentFlag          [i].resize( maxNumSubLayers); 
+    m_avgBitRate                  [i].resize( maxNumSubLayers); 
+    m_maxBitRate                  [i].resize( maxNumSubLayers); 
+    m_constantPicRateIdc          [i].resize( maxNumSubLayers); 
+    m_avgPicRate                  [i].resize( maxNumSubLayers); 
+    for ( Int j = 0; j < maxNumSubLayers; j++)
     {    
       m_bitRatePresentFlag          [i][j] = false;
@@ -4778,7 +4729,17 @@
   m_ilpRestrictedRefLayersFlag = false;
 
-  for ( Int i = 0; i < MAX_NUM_LAYERS; i++)
+  m_tileBoundariesAlignedFlag             .resize( maxNumLayers );
+  m_minSpatialSegmentOffsetPlus1          .resize( maxNumLayers );
+  m_ctuBasedOffsetEnabledFlag             .resize( maxNumLayers );
+  m_minHorizontalCtuOffsetPlus1           .resize( maxNumLayers );
+  m_baseLayerParameterSetCompatibilityFlag.resize( maxNumLayers );
+
+  for ( Int i = 0; i < maxNumLayers; i++)
   {          
-    for ( Int j = 0; j < MAX_NUM_LAYERS; j++)
+    m_tileBoundariesAlignedFlag   [i].resize( maxNumLayers );
+    m_minSpatialSegmentOffsetPlus1[i].resize( maxNumLayers );
+    m_ctuBasedOffsetEnabledFlag   [i].resize( maxNumLayers );
+    m_minHorizontalCtuOffsetPlus1 [i].resize( maxNumLayers );
+    for ( Int j = 0; j < maxNumLayers; j++)
     {    
       m_tileBoundariesAlignedFlag   [i][j] = false;
@@ -4789,156 +4750,82 @@
     m_baseLayerParameterSetCompatibilityFlag[i] = false;
   }
-  for ( Int i = 0; i < MAX_NUM_VIDEO_SIGNAL_INFO; i++ )
-  {
-    m_videoSignalInfo          [i] = NULL;     
-  }
-
   m_vpsVuiBspHrdPresentFlag = false; 
-  m_vpsVuiBspHrdParameters  = NULL;
-}
-
-TComVPSVUI::~TComVPSVUI()
-{
-  for ( Int i = 0; i < MAX_NUM_VIDEO_SIGNAL_INFO; i++ )
-  {
-    if (m_videoSignalInfo[ i ] != NULL )      delete m_videoSignalInfo[ i ];    
-    m_videoSignalInfo    [ i ] = NULL; 
-  }
-
-  if ( m_vpsVuiBspHrdParameters ) delete m_vpsVuiBspHrdParameters;
-  m_vpsVuiBspHrdParameters = NULL; 
-}
-
-Void TComVPSVUI::inferVpsVui( Bool encoderFlag )
-{
-  // inference of syntax elements that differ from default inference (as done in constructor), when VPS VUI is not present
-  if (!encoderFlag )
-  {
-    setCrossLayerIrapAlignedFlag( false ); 
-  }
-  else
-  {
-    assert( !getCrossLayerIrapAlignedFlag() ); 
-  }
-}
-
-Void TComRepFormat::inferChromaAndBitDepth( TComRepFormat* prevRepFormat, Bool encoderFlag )
-{
-  if ( !encoderFlag )
-  {
+}
+
+Void TComRepFormat::inferChromaAndBitDepth( const TComRepFormat* prevRepFormat )
+{
     setChromaAndBitDepthVpsPresentFlag( prevRepFormat->getChromaAndBitDepthVpsPresentFlag() );
     setSeparateColourPlaneVpsFlag     ( prevRepFormat->getSeparateColourPlaneVpsFlag     () );
     setBitDepthVpsLumaMinus8          ( prevRepFormat->getBitDepthVpsLumaMinus8          () );
     setBitDepthVpsChromaMinus8        ( prevRepFormat->getBitDepthVpsChromaMinus8        () );
-  }
-  else
-  {
+}
+
+Void TComRepFormat::checkInferChromaAndBitDepth( const TComRepFormat* prevRepFormat ) const 
+{
     assert( getChromaAndBitDepthVpsPresentFlag() == prevRepFormat->getChromaAndBitDepthVpsPresentFlag() );
     assert( getSeparateColourPlaneVpsFlag     () == prevRepFormat->getSeparateColourPlaneVpsFlag     () );
     assert( getBitDepthVpsLumaMinus8          () == prevRepFormat->getBitDepthVpsLumaMinus8          () );
     assert( getBitDepthVpsChromaMinus8        () == prevRepFormat->getBitDepthVpsChromaMinus8        () );
-  }
-}
-
-
-
-TComVpsVuiBspHrdParameters::~TComVpsVuiBspHrdParameters()
-{
-  delete[] m_cprmsAddPresentFlag; 
-  delete[] m_numSubLayerHrdMinus1; 
-  delete[] m_hrdParameters; 
-
-  for (Int h = 0; h < m_numOls; h++)
-  {
-    if ( h > 0 )
-    {    
-      for (Int i = 0; i < getNumSignalledPartitioningSchemes(h)+1; i++)
-      {
-        for (Int t = 0; t < m_vps->getMaxSubLayersInLayerSetMinus1( m_vps->olsIdxToLsIdx(h) ) + 1; t++)
-        {        
-          for ( Int j = 0; j <= getNumBspSchedulesMinus1(h,i,j);j++ )
-          {
-            delete[] m_bspHrdIdx  [h][i][t][j]; 
-            delete[] m_bspSchedIdx[h][i][t][j];
-          }
-        }
-        delete[] m_numBspSchedulesMinus1[h][i];
-      }
-    }
-
-    for (Int j = 0; j <= getNumSignalledPartitioningSchemes(h ) + 1; j++ )
-    {
-      for (Int k = 0; k <= getNumPartitionsInSchemeMinus1(h,j); k++ )
-      {
-        delete[] m_layerIncludedInPartitionFlag[h][j][k];
-      }        
-    }
-    delete[] m_numPartitionsInSchemeMinus1[h];       
-  }
-  delete[] m_numSignalledPartitioningSchemes;
-}
-
-
-Int TComVpsVuiBspHrdParameters::getBspHrdIdxLen(TComVPS* vps)
+}
+
+Int TComVpsVuiBspHrdParameters::getBspHrdIdxLen( const TComVPS* vps) const
 {
   return gCeilLog2( vps->getNumHrdParameters() + getVpsNumAddHrdParams() );
 }
 
-Void TComVpsVuiBspHrdParameters::createAfterVpsNumAddHrdParams( TComVPS* vps )
-{
-  assert( vps == NULL ); 
-  m_vps = vps; 
+Void TComVpsVuiBspHrdParameters::createAfterVpsNumAddHrdParams( const TComVPS* vps )
+{
   m_offsetHrdParamIdx = vps->getNumHrdParameters(); 
   m_numHrdParam       = vps->getNumHrdParameters() + getVpsNumAddHrdParams() - m_offsetHrdParamIdx;
   m_numOls            = vps->getNumOutputLayerSets(); 
 
-  m_cprmsAddPresentFlag   = new Bool    [ m_numHrdParam ];
-  m_numSubLayerHrdMinus1  = new Int     [ m_numHrdParam ];
-  m_hrdParameters         = new TComHRD [ m_numHrdParam ];
-
-  m_numSignalledPartitioningSchemes = new Int    [ m_numOls ]; 
-  m_numPartitionsInSchemeMinus1     = new Int*   [ m_numOls ];
-  m_numBspSchedulesMinus1           = new Int**  [ m_numOls ]; 
-  m_bspHrdIdx                       = new Int****[ m_numOls ];
-  m_bspSchedIdx                     = new Int****[ m_numOls ];
-}
-
-Void TComVpsVuiBspHrdParameters::createAfterNumSignalledPartitioningSchemes( Int h )
-{
-  m_numPartitionsInSchemeMinus1 [h]    = new Int    [ getNumSignalledPartitioningSchemes(h) ];
-  m_layerIncludedInPartitionFlag[h]    = new Bool** [ getNumSignalledPartitioningSchemes(h) ];    
-
-  m_numBspSchedulesMinus1[h]           = new Int*   [ getNumSignalledPartitioningSchemes(h) + 1 ];
+  m_cprmsAddPresentFlag .resize( m_numHrdParam );
+  m_numSubLayerHrdMinus1.resize( m_numHrdParam );
+  m_hrdParameters       .resize( m_numHrdParam );
+
+  m_numSignalledPartitioningSchemes .resize( m_numOls ); 
+  m_numPartitionsInSchemeMinus1     .resize( m_numOls );
+  m_numBspSchedulesMinus1           .resize( m_numOls ); 
+  m_bspHrdIdx                       .resize( m_numOls );
+  m_bspSchedIdx                     .resize( m_numOls );
+}
+
+Void TComVpsVuiBspHrdParameters::createAfterNumSignalledPartitioningSchemes( const TComVPS* vps, Int h )
+{
+  m_numPartitionsInSchemeMinus1 [h].resize( getNumSignalledPartitioningSchemes(h) );
+  m_layerIncludedInPartitionFlag[h].resize( getNumSignalledPartitioningSchemes(h) );    
+
+  m_numBspSchedulesMinus1       [h].resize( getNumSignalledPartitioningSchemes(h) + 1 );
   for (Int i = 0; i < getNumSignalledPartitioningSchemes(h) + 1; i++)
   {
-    Int tMax = m_vps->getMaxSubLayersInLayerSetMinus1( m_vps->olsIdxToLsIdx(h) ) + 1;
-    m_numBspSchedulesMinus1[h][i] = new Int  [ tMax ];
-    m_bspHrdIdx            [h][i] = new Int**[ tMax ];
-    m_bspSchedIdx          [h][i] = new Int**[ tMax ];
-  }
-}
-
-Void TComVpsVuiBspHrdParameters::createAfterNumPartitionsInSchemeMinus1( Int h, Int j )
-{
-  m_layerIncludedInPartitionFlag[h][j] = new Bool*[ getNumPartitionsInSchemeMinus1(h,j)];
+    Int tMax = vps->getMaxSubLayersInLayerSetMinus1( m_vps->olsIdxToLsIdx(h) ) + 1;
+    m_numBspSchedulesMinus1[h][i].resize( tMax );
+    m_bspHrdIdx            [h][i].resize( tMax );
+    m_bspSchedIdx          [h][i].resize( tMax );
+  }
+}
+
+Void TComVpsVuiBspHrdParameters::createAfterNumPartitionsInSchemeMinus1( const TComVPS* vps, Int h, Int j )
+{
+  m_layerIncludedInPartitionFlag[h][j].resize( getNumPartitionsInSchemeMinus1(h,j));
   for( Int k = 0; k < getNumPartitionsInSchemeMinus1(h,j); k++ )
   {
-    m_layerIncludedInPartitionFlag[h][j][k] = new Bool[ m_vps->getNumLayersInIdList( m_vps->olsIdxToLsIdx(h))];
-  }
-}
-
-Void TComVpsVuiBspHrdParameters::createAfterNumBspSchedulesMinus1( Int h, Int i, Int t )
-{
-  m_bspSchedIdx[h][i][t] = new Int* [ getNumBspSchedulesMinus1( h, i, t ) + 1 ];
-  m_bspHrdIdx  [h][i][t] = new Int* [ getNumBspSchedulesMinus1( h, i, t ) + 1 ];
+    m_layerIncludedInPartitionFlag[h][j][k].resize( m_vps->getNumLayersInIdList( vps->olsIdxToLsIdx(h)));
+  }
+}
+
+Void TComVpsVuiBspHrdParameters::createAfterNumBspSchedulesMinus1( const TComVPS* vps, Int h, Int i, Int t )
+{
+  m_bspSchedIdx[h][i][t].resize( getNumBspSchedulesMinus1( h, i, t ) + 1 );
+  m_bspHrdIdx  [h][i][t].resize( getNumBspSchedulesMinus1( h, i, t ) + 1 );
   for( Int j = 0; j < getNumBspSchedulesMinus1( h, i, t ) + 1; j++ )
   {
-    m_bspSchedIdx[h][i][t][j] = new Int[ getNumPartitionsInSchemeMinus1( h, i ) ];
-    m_bspHrdIdx  [h][i][t][j] = new Int[ getNumPartitionsInSchemeMinus1( h, i ) ];
-  }
-}
-
-
-Void TComVUI::inferVideoSignalInfo( TComVPS* vps, Int layerIdCurr )
+    m_bspSchedIdx[h][i][t][j].resize( getNumPartitionsInSchemeMinus1( h, i ) );
+    m_bspHrdIdx  [h][i][t][j].resize( getNumPartitionsInSchemeMinus1( h, i ) );
+  }
+}
+
+
+Void TComVUI::inferVideoSignalInfo( const TComVPS* vps, Int layerIdCurr )
 {
   if ( layerIdCurr == 0 || !vps->getVpsVuiPresentFlag() ) 
@@ -4947,8 +4834,8 @@
   }
 
-  TComVPSVUI* vpsVUI = vps->getVPSVUI(); 
-  assert( vpsVUI != NULL );  
-
-  TComVideoSignalInfo* videoSignalInfo = vpsVUI->getVideoSignalInfo( vpsVUI->getVpsVideoSignalInfoIdx( vps->getLayerIdInVps( layerIdCurr ) ) ); 
+  const TComVPSVUI* vpsVui = vps->getVPSVUI(); 
+  assert( vpsVui != NULL );  
+
+  const TComVideoSignalInfo* videoSignalInfo = vpsVui->getVideoSignalInfo( vpsVui->getVpsVideoSignalInfoIdx( vps->getLayerIdInVps( layerIdCurr ) ) ); 
   assert( videoSignalInfo != NULL );
 
@@ -4960,18 +4847,33 @@
 }
 
-TComDpbSize::TComDpbSize()
-{
-  for (Int i = 0; i < MAX_VPS_OUTPUTLAYER_SETS; i++ )
+Void TComDpbSize::init( Int numOutputLayerSets, Int maxNumLayerIds, Int maxNumSubLayers )  
+{
+  m_subLayerFlagInfoPresentFlag.resize( numOutputLayerSets );
+  m_subLayerDpbInfoPresentFlag .resize( numOutputLayerSets );
+  m_maxVpsDecPicBufferingMinus1.resize( numOutputLayerSets ); 
+  m_maxVpsNumReorderPics       .resize( numOutputLayerSets );
+  m_maxVpsLatencyIncreasePlus1 .resize( numOutputLayerSets );
+
+  for (Int i = 0; i < numOutputLayerSets; i++ )
   {      
     m_subLayerFlagInfoPresentFlag[i]  = false;
 
-    for (Int j = 0; j < MAX_TLAYER; j++  )
+    m_subLayerDpbInfoPresentFlag [i].resize( maxNumSubLayers );
+    m_maxVpsDecPicBufferingMinus1[i].resize( maxNumLayerIds ); 
+    m_maxVpsNumReorderPics       [i].resize( maxNumSubLayers );
+    m_maxVpsLatencyIncreasePlus1 [i].resize( maxNumSubLayers );    
+
+    for (Int j = 0; j < maxNumSubLayers; j++  )
     {        
       m_subLayerDpbInfoPresentFlag [i][j] = ( j == 0) ;
       m_maxVpsNumReorderPics       [i][j] = 0;
       m_maxVpsLatencyIncreasePlus1 [i][j] = 0;
-
-      for (Int k = 0; k < MAX_NUM_LAYER_IDS; k++ )
-      {
+    }
+
+    for (Int k = 0; k < maxNumLayerIds; k++ )
+    {
+      m_maxVpsDecPicBufferingMinus1[i][k].resize( maxNumSubLayers );
+      for (Int j = 0; j < maxNumSubLayers; j++  )
+      {        
         m_maxVpsDecPicBufferingMinus1[i][k][j] = MIN_INT; 
       }
@@ -4992,3 +4894,2 @@
 }
 #endif
-
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSlice.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComSlice.h	(revision 1200)
@@ -1,8 +1,8 @@
-﻿/* The copyright in this software is being made available under the BSD
+/* The copyright in this software is being made available under the 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,9 +45,6 @@
 #include "TComRom.h"
 #include "TComList.h"
-#if H_MV
-#include <ios>
-#include <iostream>
-#include <iomanip>
-#endif
+#include "TComChromaFormat.h"
+
 //! \ingroup TLibCommon
 //! \{
@@ -55,5 +52,5 @@
 class TComPic;
 class TComTrQuant;
-#if H_MV
+#if NH_MV
 class TComPicLists; 
 class TComVPS; 
@@ -63,4 +60,6 @@
 // Constants
 // ====================================================================================================================
+
+static const UInt REF_PIC_LIST_NUM_IDX=32;
 
 // ====================================================================================================================
@@ -80,7 +79,7 @@
   Bool m_used[MAX_NUM_REF_PICS];
   Bool m_interRPSPrediction;
-  Int  m_deltaRIdxMinus1;   
-  Int  m_deltaRPS; 
-  Int  m_numRefIdc; 
+  Int  m_deltaRIdxMinus1;
+  Int  m_deltaRPS;
+  Int  m_numRefIdc;
   Int  m_refIdc[MAX_NUM_REF_PICS+1];
   Bool m_bCheckLTMSB[MAX_NUM_REF_PICS];
@@ -90,49 +89,50 @@
 
 public:
-  TComReferencePictureSet();
+          TComReferencePictureSet();
   virtual ~TComReferencePictureSet();
-  Int   getPocLSBLT(Int i)                       { return m_pocLSBLT[i]; }
-  Void  setPocLSBLT(Int i, Int x)                { m_pocLSBLT[i] = x; }
-  Int   getDeltaPocMSBCycleLT(Int i)             { return m_deltaPOCMSBCycleLT[i]; }
-  Void  setDeltaPocMSBCycleLT(Int i, Int x)      { m_deltaPOCMSBCycleLT[i] = x; }
-  Bool  getDeltaPocMSBPresentFlag(Int i)         { return m_deltaPocMSBPresentFlag[i]; }
-  Void  setDeltaPocMSBPresentFlag(Int i, Bool x) { m_deltaPocMSBPresentFlag[i] = x;    }
-  Void setUsed(Int bufferNum, Bool used);
-  Void setDeltaPOC(Int bufferNum, Int deltaPOC);
-  Void setPOC(Int bufferNum, Int deltaPOC);
-  Void setNumberOfPictures(Int numberOfPictures);
-  Void setCheckLTMSBPresent(Int bufferNum, Bool b );
-  Bool getCheckLTMSBPresent(Int bufferNum);
-
-  Int  getUsed(Int bufferNum);
-  Int  getDeltaPOC(Int bufferNum);
-  Int  getPOC(Int bufferNum);
-  Int  getNumberOfPictures();
-
-  Void setNumberOfNegativePictures(Int number)  { m_numberOfNegativePictures = number; }
-  Int  getNumberOfNegativePictures()            { return m_numberOfNegativePictures; }
-  Void setNumberOfPositivePictures(Int number)  { m_numberOfPositivePictures = number; }
-  Int  getNumberOfPositivePictures()            { return m_numberOfPositivePictures; }
-  Void setNumberOfLongtermPictures(Int number)  { m_numberOfLongtermPictures = number; }
-  Int  getNumberOfLongtermPictures()            { return m_numberOfLongtermPictures; }
-
-  Void setInterRPSPrediction(Bool flag)         { m_interRPSPrediction = flag; }
-  Bool getInterRPSPrediction()                  { return m_interRPSPrediction; }
-  Void setDeltaRIdxMinus1(Int x)                { m_deltaRIdxMinus1 = x; }
-  Int  getDeltaRIdxMinus1()                     { return m_deltaRIdxMinus1; }
-  Void setDeltaRPS(Int x)                       { m_deltaRPS = x; }
-  Int  getDeltaRPS()                            { return m_deltaRPS; }
-  Void setNumRefIdc(Int x)                      { m_numRefIdc = x; }
-  Int  getNumRefIdc()                           { return m_numRefIdc; }
-
-  Void setRefIdc(Int bufferNum, Int refIdc);
-  Int  getRefIdc(Int bufferNum);
-
-  Void sortDeltaPOC();
-  Void printDeltaPOC();
-
-#if H_MV
-  Void checkMaxNumPics( Bool vpsExtensionFlag, Int maxNumPics, Int nuhLayerId, Int spsMaxDecPicBufferingMinus1 );
-#endif
+  Int     getPocLSBLT(Int i) const                     { return m_pocLSBLT[i];               }
+  Void    setPocLSBLT(Int i, Int x)                    { m_pocLSBLT[i] = x;                  }
+  Int     getDeltaPocMSBCycleLT(Int i) const           { return m_deltaPOCMSBCycleLT[i];     }
+  Void    setDeltaPocMSBCycleLT(Int i, Int x)          { m_deltaPOCMSBCycleLT[i] = x;        }
+  Bool    getDeltaPocMSBPresentFlag(Int i) const       { return m_deltaPocMSBPresentFlag[i]; }
+  Void    setDeltaPocMSBPresentFlag(Int i, Bool x)     { m_deltaPocMSBPresentFlag[i] = x;    }
+  Void    setUsed(Int bufferNum, Bool used);
+  Void    setDeltaPOC(Int bufferNum, Int deltaPOC);
+  Void    setPOC(Int bufferNum, Int deltaPOC);
+  Void    setNumberOfPictures(Int numberOfPictures);
+  Void    setCheckLTMSBPresent(Int bufferNum, Bool b );
+  Bool    getCheckLTMSBPresent(Int bufferNum) const;
+
+  Int     getUsed(Int bufferNum) const;
+  Int     getDeltaPOC(Int bufferNum) const;
+  Int     getPOC(Int bufferNum) const;
+  Int     getNumberOfPictures() const;
+
+  Void    setNumberOfNegativePictures(Int number)      { m_numberOfNegativePictures = number; }
+  Int     getNumberOfNegativePictures() const          { return m_numberOfNegativePictures;   }
+  Void    setNumberOfPositivePictures(Int number)      { m_numberOfPositivePictures = number; }
+  Int     getNumberOfPositivePictures() const          { return m_numberOfPositivePictures;   }
+  Void    setNumberOfLongtermPictures(Int number)      { m_numberOfLongtermPictures = number; }
+  Int     getNumberOfLongtermPictures() const          { return m_numberOfLongtermPictures;   }
+
+  Void    setInterRPSPrediction(Bool flag)             { m_interRPSPrediction = flag;         }
+  Bool    getInterRPSPrediction() const                { return m_interRPSPrediction;         }
+  Void    setDeltaRIdxMinus1(Int x)                    { m_deltaRIdxMinus1 = x;               }
+  Int     getDeltaRIdxMinus1() const                   { return m_deltaRIdxMinus1;            }
+  Void    setDeltaRPS(Int x)                           { m_deltaRPS = x;                      }
+  Int     getDeltaRPS() const                          { return m_deltaRPS;                   }
+  Void    setNumRefIdc(Int x)                          { m_numRefIdc = x;                     }
+  Int     getNumRefIdc() const                         { return m_numRefIdc;                  }
+
+  Void    setRefIdc(Int bufferNum, Int refIdc);
+  Int     getRefIdc(Int bufferNum) const ;
+
+  Void    sortDeltaPOC();
+  Void    printDeltaPOC() const;
+
+#if NH_MV
+  Void checkMaxNumPics( Bool vpsExtensionFlag, Int maxNumPics, Int nuhLayerId, Int spsMaxDecPicBufferingMinus1 ) const;
+#endif
+
 };
 
@@ -141,18 +141,18 @@
 {
 private:
-  Int  m_numberOfReferencePictureSets;
-  TComReferencePictureSet* m_referencePictureSets;
-  
+  std::vector<TComReferencePictureSet> m_referencePictureSets;
+
 public:
-  TComRPSList();
-  virtual ~TComRPSList();
-  
-  Void  create  (Int numberOfEntries);
-  Void  destroy ();
-
-
-  TComReferencePictureSet* getReferencePictureSet(Int referencePictureSetNum);
-  Int getNumberOfReferencePictureSets();
-  Void setNumberOfReferencePictureSets(Int numberOfReferencePictureSets);
+                                 TComRPSList()                                            { }
+  virtual                        ~TComRPSList()                                           { }
+
+  Void                           create  (Int numberOfEntries)                            { m_referencePictureSets.resize(numberOfEntries);         }
+  Void                           destroy ()                                               { }
+
+
+  TComReferencePictureSet*       getReferencePictureSet(Int referencePictureSetNum)       { return &m_referencePictureSets[referencePictureSetNum]; }
+  const TComReferencePictureSet* getReferencePictureSet(Int referencePictureSetNum) const { return &m_referencePictureSets[referencePictureSetNum]; }
+
+  Int                            getNumberOfReferencePictureSets() const                  { return Int(m_referencePictureSets.size());              }
 };
 
@@ -161,124 +161,139 @@
 {
 public:
-  TComScalingList();
-  virtual ~TComScalingList();
-  Void     setScalingListPresentFlag    (Bool b)                               { m_scalingListPresentFlag = b;    }
-  Bool     getScalingListPresentFlag    ()                                     { return m_scalingListPresentFlag; }
-  Int*     getScalingListAddress          (UInt sizeId, UInt listId)           { return m_scalingListCoef[sizeId][listId]; } //!< get matrix coefficient
-  Bool     checkPredMode                  (UInt sizeId, UInt listId);
-  Void     setRefMatrixId                 (UInt sizeId, UInt listId, UInt u)   { m_refMatrixId[sizeId][listId] = u;    }     //!< set reference matrix ID
-  UInt     getRefMatrixId                 (UInt sizeId, UInt listId)           { return m_refMatrixId[sizeId][listId]; }     //!< get reference matrix ID
-  Int*     getScalingListDefaultAddress   (UInt sizeId, UInt listId);                                                        //!< get default matrix coefficient
-  Void     processDefaultMatrix            (UInt sizeId, UInt listId);
-  Void     setScalingListDC               (UInt sizeId, UInt listId, UInt u)   { m_scalingListDC[sizeId][listId] = u; }      //!< set DC value
-
-  Int      getScalingListDC               (UInt sizeId, UInt listId)           { return m_scalingListDC[sizeId][listId]; }   //!< get DC value
-  Void     checkDcOfMatrix                ();
-  Void     processRefMatrix               (UInt sizeId, UInt listId , UInt refListId );
-  Bool     xParseScalingList              (Char* pchFile);
-#if H_MV
-  Void     inferFrom                      ( TComScalingList* srcScLi );
-#endif
+             TComScalingList();
+  virtual    ~TComScalingList()                                                 { }
+  Int*       getScalingListAddress(UInt sizeId, UInt listId)                    { return &(m_scalingListCoef[sizeId][listId][0]);            } //!< get matrix coefficient
+  const Int* getScalingListAddress(UInt sizeId, UInt listId) const              { return &(m_scalingListCoef[sizeId][listId][0]);            } //!< get matrix coefficient
+  Void       checkPredMode(UInt sizeId, UInt listId);
+
+  Void       setRefMatrixId(UInt sizeId, UInt listId, UInt u)                   { m_refMatrixId[sizeId][listId] = u;                         } //!< set reference matrix ID
+  UInt       getRefMatrixId(UInt sizeId, UInt listId) const                     { return m_refMatrixId[sizeId][listId];                      } //!< get reference matrix ID
+
+  const Int* getScalingListDefaultAddress(UInt sizeId, UInt listId);                                                                           //!< get default matrix coefficient
+  Void       processDefaultMatrix(UInt sizeId, UInt listId);
+
+  Void       setScalingListDC(UInt sizeId, UInt listId, UInt u)                 { m_scalingListDC[sizeId][listId] = u;                       } //!< set DC value
+  Int        getScalingListDC(UInt sizeId, UInt listId) const                   { return m_scalingListDC[sizeId][listId];                    } //!< get DC value
+
+  Void       setScalingListPredModeFlag(UInt sizeId, UInt listId, Bool bIsDPCM) { m_scalingListPredModeFlagIsDPCM[sizeId][listId] = bIsDPCM; }
+  Bool       getScalingListPredModeFlag(UInt sizeId, UInt listId) const         { return m_scalingListPredModeFlagIsDPCM[sizeId][listId];    }
+
+  Void       checkDcOfMatrix();
+  Void       processRefMatrix(UInt sizeId, UInt listId , UInt refListId );
+  Bool       xParseScalingList(Char* pchFile);
+#if NH_MV
+  Void       inferFrom                      ( const TComScalingList& srcScLi );
+#endif
+  Void       setDefaultScalingList();
+  Bool       checkDefaultScalingList();
 
 private:
-  Void     init                    ();
-  Void     destroy                 ();
-  Int      m_scalingListDC               [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< the DC value of the matrix coefficient for 16x16
-  Bool     m_useDefaultScalingMatrixFlag [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< UseDefaultScalingMatrixFlag
-  UInt     m_refMatrixId                 [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< RefMatrixID
-  Bool     m_scalingListPresentFlag;                                                //!< flag for using default matrix
-  UInt     m_predMatrixId                [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< reference list index
-  Int      *m_scalingListCoef            [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< quantization matrix
+  Void       outputScalingLists(std::ostream &os) const;
+  Bool             m_scalingListPredModeFlagIsDPCM [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< reference list index
+  Int              m_scalingListDC                 [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< the DC value of the matrix coefficient for 16x16
+  UInt             m_refMatrixId                   [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< RefMatrixID
+  std::vector<Int> m_scalingListCoef               [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< quantization matrix
 };
 
 class ProfileTierLevel
 {
-  Int     m_profileSpace;
-  Bool    m_tierFlag;
-  Int     m_profileIdc;
-  Bool    m_profileCompatibilityFlag[32];
-  Int     m_levelIdc;
-
-  Bool m_progressiveSourceFlag;
-  Bool m_interlacedSourceFlag;
-  Bool m_nonPackedConstraintFlag;
-  Bool m_frameOnlyConstraintFlag;
-  
-#if H_MV
-  Bool m_max12bitConstraintFlag;
-  Bool m_max10bitConstraintFlag;
-  Bool m_max8bitConstraintFlag;
-  Bool m_max422chromaConstraintFlag;
-  Bool m_max420chromaConstraintFlag;
-  Bool m_maxMonochromeConstraintFlag;
-  Bool m_intraConstraintFlag;
-  Bool m_onePictureOnlyConstraintFlag;
-  Bool m_lowerBitRateConstraintFlag;
-  Bool m_inbldFlag;
+  Int               m_profileSpace;
+  Level::Tier       m_tierFlag;
+  Profile::Name     m_profileIdc;
+  Bool              m_profileCompatibilityFlag[32];
+  Level::Name       m_levelIdc;
+
+  Bool              m_progressiveSourceFlag;
+  Bool              m_interlacedSourceFlag;
+  Bool              m_nonPackedConstraintFlag;
+  Bool              m_frameOnlyConstraintFlag;
+  UInt              m_bitDepthConstraintValue;
+  ChromaFormat      m_chromaFormatConstraintValue;
+  Bool              m_intraConstraintFlag;
+  Bool              m_onePictureOnlyConstraintFlag;
+  Bool              m_lowerBitRateConstraintFlag;
+#if NH_MV
+  Bool              m_max12bitConstraintFlag;
+  Bool              m_max10bitConstraintFlag;
+  Bool              m_max8bitConstraintFlag;
+  Bool              m_max422chromaConstraintFlag;
+  Bool              m_max420chromaConstraintFlag;
+  Bool              m_maxMonochromeConstraintFlag;
+  Bool              m_inbldFlag;
 #endif
 public:
-  ProfileTierLevel();
-
-  Int   getProfileSpace() const   { return m_profileSpace; }
-  Void  setProfileSpace(Int x)    { m_profileSpace = x; }
-
-  Bool  getTierFlag()     const   { return m_tierFlag; }
-  Void  setTierFlag(Bool x)       { m_tierFlag = x; }
-
-  Int   getProfileIdc()   const   { return m_profileIdc; }
-  Void  setProfileIdc(Int x)      { m_profileIdc = x; }
-
-  Bool  getProfileCompatibilityFlag(Int i) const    { return m_profileCompatibilityFlag[i]; }
-  Void  setProfileCompatibilityFlag(Int i, Bool x)  { m_profileCompatibilityFlag[i] = x; }
-
-  Int   getLevelIdc()   const   { return m_levelIdc; }
-  Void  setLevelIdc(Int x)      { m_levelIdc = x; }
-  
-  Bool getProgressiveSourceFlag() const { return m_progressiveSourceFlag; }
-  Void setProgressiveSourceFlag(Bool b) { m_progressiveSourceFlag = b; }
-  
-  Bool getInterlacedSourceFlag() const { return m_interlacedSourceFlag; }
-  Void setInterlacedSourceFlag(Bool b) { m_interlacedSourceFlag = b; }
-  
-  Bool getNonPackedConstraintFlag() const { return m_nonPackedConstraintFlag; }
-  Void setNonPackedConstraintFlag(Bool b) { m_nonPackedConstraintFlag = b; }
-  
-  Bool getFrameOnlyConstraintFlag() const { return m_frameOnlyConstraintFlag; }
-  Void setFrameOnlyConstraintFlag(Bool b) { m_frameOnlyConstraintFlag = b; }
-
-#if H_MV
-  Void setMax12bitConstraintFlag( Bool flag ) { m_max12bitConstraintFlag = flag; } 
-  Bool getMax12bitConstraintFlag(  ) { return m_max12bitConstraintFlag; } 
-  
-  Void setMax10bitConstraintFlag( Bool flag ) { m_max10bitConstraintFlag = flag; } 
-  Bool getMax10bitConstraintFlag(  ) { return m_max10bitConstraintFlag; } 
-  
-  Void setMax8bitConstraintFlag( Bool flag ) { m_max8bitConstraintFlag = flag; } 
-  Bool getMax8bitConstraintFlag(  ) { return m_max8bitConstraintFlag; } 
-  
-  Void setMax422chromaConstraintFlag( Bool flag ) { m_max422chromaConstraintFlag = flag; } 
-  Bool getMax422chromaConstraintFlag(  ) { return m_max422chromaConstraintFlag; } 
-  
-  Void setMax420chromaConstraintFlag( Bool flag ) { m_max420chromaConstraintFlag = flag; } 
-  Bool getMax420chromaConstraintFlag(  ) { return m_max420chromaConstraintFlag; } 
-  
-  Void setMaxMonochromeConstraintFlag( Bool flag ) { m_maxMonochromeConstraintFlag = flag; } 
-  Bool getMaxMonochromeConstraintFlag(  ) { return m_maxMonochromeConstraintFlag; } 
-  Void setIntraConstraintFlag( Bool flag ) { m_intraConstraintFlag = flag; } 
-  Bool getIntraConstraintFlag(  ) { return m_intraConstraintFlag; } 
-  
-  Void setOnePictureOnlyConstraintFlag( Bool flag ) { m_onePictureOnlyConstraintFlag = flag; } 
-  Bool getOnePictureOnlyConstraintFlag(  ) { return m_onePictureOnlyConstraintFlag; } 
-  
-  Void setLowerBitRateConstraintFlag( Bool flag ) { m_lowerBitRateConstraintFlag = flag; } 
-  Bool getLowerBitRateConstraintFlag(  ) { return m_lowerBitRateConstraintFlag; } 
-  
-  Void setInbldFlag( Bool flag ) { m_inbldFlag = flag; } 
-  Bool getInbldFlag(  ) { return m_inbldFlag; } 
-  Bool getV2ConstraintsPresentFlag();  
-  Bool getInbldPresentFlag();
-  Void copyV2ConstraintFlags( ProfileTierLevel* ptlRef );
-  Void copyProfile( ProfileTierLevel* ptlRef );
-#endif
+                ProfileTierLevel();
+
+  Int           getProfileSpace() const                     { return m_profileSpace;                }
+  Void          setProfileSpace(Int x)                      { m_profileSpace = x;                   }
+
+  Level::Tier   getTierFlag() const                         { return m_tierFlag;                    }
+  Void          setTierFlag(Level::Tier x)                  { m_tierFlag = x;                       }
+
+  Profile::Name getProfileIdc() const                       { return m_profileIdc;                  }
+  Void          setProfileIdc(Profile::Name x)              { m_profileIdc = x;                     }
+
+  Bool          getProfileCompatibilityFlag(Int i) const    { return m_profileCompatibilityFlag[i]; }
+  Void          setProfileCompatibilityFlag(Int i, Bool x)  { m_profileCompatibilityFlag[i] = x;    }
+
+  Level::Name   getLevelIdc() const                         { return m_levelIdc;                    }
+  Void          setLevelIdc(Level::Name x)                  { m_levelIdc = x;                       }
+
+  Bool          getProgressiveSourceFlag() const            { return m_progressiveSourceFlag;       }
+  Void          setProgressiveSourceFlag(Bool b)            { m_progressiveSourceFlag = b;          }
+
+  Bool          getInterlacedSourceFlag() const             { return m_interlacedSourceFlag;        }
+  Void          setInterlacedSourceFlag(Bool b)             { m_interlacedSourceFlag = b;           }
+
+  Bool          getNonPackedConstraintFlag() const          { return m_nonPackedConstraintFlag;     }
+  Void          setNonPackedConstraintFlag(Bool b)          { m_nonPackedConstraintFlag = b;        }
+
+  Bool          getFrameOnlyConstraintFlag() const          { return m_frameOnlyConstraintFlag;     }
+  Void          setFrameOnlyConstraintFlag(Bool b)          { m_frameOnlyConstraintFlag = b;        }
+
+  UInt          getBitDepthConstraint() const               { return m_bitDepthConstraintValue;     }
+  Void          setBitDepthConstraint(UInt bitDepth)        { m_bitDepthConstraintValue=bitDepth;   }
+
+  ChromaFormat  getChromaFormatConstraint() const           { return m_chromaFormatConstraintValue; }
+  Void          setChromaFormatConstraint(ChromaFormat fmt) { m_chromaFormatConstraintValue=fmt;    }
+
+  Bool          getIntraConstraintFlag() const              { return m_intraConstraintFlag;         }
+  Void          setIntraConstraintFlag(Bool b)              { m_intraConstraintFlag = b;            }
+
+  Bool          getOnePictureOnlyConstraintFlag() const     { return m_onePictureOnlyConstraintFlag;}
+  Void          setOnePictureOnlyConstraintFlag(Bool b)     { m_onePictureOnlyConstraintFlag = b;   }
+
+  Bool          getLowerBitRateConstraintFlag() const       { return m_lowerBitRateConstraintFlag;  }
+  Void          setLowerBitRateConstraintFlag(Bool b)       { m_lowerBitRateConstraintFlag = b;     }
+
+#if NH_MV
+  Void          setMax12bitConstraintFlag( Bool flag )      { m_max12bitConstraintFlag = flag;      }
+  Bool          getMax12bitConstraintFlag(  ) const         { return m_max12bitConstraintFlag;      }
+
+  Void          setMax10bitConstraintFlag( Bool flag )      { m_max10bitConstraintFlag = flag;      }
+  Bool          getMax10bitConstraintFlag(  ) const         { return m_max10bitConstraintFlag;      }
+
+  Void          setMax8bitConstraintFlag( Bool flag )       { m_max8bitConstraintFlag = flag;       }
+  Bool          getMax8bitConstraintFlag(  ) const          { return m_max8bitConstraintFlag;       }
+
+  Void          setMax422chromaConstraintFlag( Bool flag )  { m_max422chromaConstraintFlag = flag;  }
+  Bool          getMax422chromaConstraintFlag(  ) const     { return m_max422chromaConstraintFlag;  }
+
+  Void          setMax420chromaConstraintFlag( Bool flag )  { m_max420chromaConstraintFlag = flag;  }
+  Bool          getMax420chromaConstraintFlag(  ) const     { return m_max420chromaConstraintFlag;  }
+
+  Void          setMaxMonochromeConstraintFlag( Bool flag ) { m_maxMonochromeConstraintFlag = flag; }
+  Bool          getMaxMonochromeConstraintFlag(  ) const    { return m_maxMonochromeConstraintFlag; }
+
+  Void          setInbldFlag( Bool flag )                   { m_inbldFlag = flag;                   }
+  Bool          getInbldFlag(  ) const                      { return m_inbldFlag;                   }
+
+  Bool          getV2ConstraintsPresentFlag() const;
+  Bool          getInbldPresentFlag() const;
+
+  Void          copyV2ConstraintFlags( ProfileTierLevel* ptlRef );
+  Void          copyProfile( ProfileTierLevel* ptlRef );
+#endif
+
 };
 
@@ -292,18 +307,23 @@
 
 public:
-  TComPTL();
-  Bool getSubLayerProfilePresentFlag(Int i) const { return m_subLayerProfilePresentFlag[i]; }
-  Void setSubLayerProfilePresentFlag(Int i, Bool x) { m_subLayerProfilePresentFlag[i] = x; }
-  
-  Bool getSubLayerLevelPresentFlag(Int i) const { return m_subLayerLevelPresentFlag[i]; }
-  Void setSubLayerLevelPresentFlag(Int i, Bool x) { m_subLayerLevelPresentFlag[i] = x; }
-
-  ProfileTierLevel* getGeneralPTL()  { return &m_generalPTL; }
-  ProfileTierLevel* getSubLayerPTL(Int i)  { return &m_subLayerPTL[i]; }
-#if H_MV
-  Void inferGeneralValues ( Bool profilePresentFlag  , Int k, TComPTL* refPTL );; 
-  Void inferSubLayerValues( Int maxNumSubLayersMinus1, Int k, TComPTL* refPTL );; 
-#endif
+                          TComPTL();
+  Bool                    getSubLayerProfilePresentFlag(Int i) const   { return m_subLayerProfilePresentFlag[i]; }
+  Void                    setSubLayerProfilePresentFlag(Int i, Bool x) { m_subLayerProfilePresentFlag[i] = x;    }
+
+  Bool                    getSubLayerLevelPresentFlag(Int i) const     { return m_subLayerLevelPresentFlag[i];   }
+  Void                    setSubLayerLevelPresentFlag(Int i, Bool x)   { m_subLayerLevelPresentFlag[i] = x;      }
+
+  ProfileTierLevel*       getGeneralPTL()                              { return &m_generalPTL;                   }
+  const ProfileTierLevel* getGeneralPTL() const                        { return &m_generalPTL;                   }
+  ProfileTierLevel*       getSubLayerPTL(Int i)                        { return &m_subLayerPTL[i];               }
+  const ProfileTierLevel* getSubLayerPTL(Int i) const                  { return &m_subLayerPTL[i];               }
+
+#if NH_MV
+  Void                    inferGeneralValues ( Bool profilePresentFlag  , Int k, TComPTL* refPTL );; 
+  Void                    inferSubLayerValues( Int maxNumSubLayersMinus1, Int k, TComPTL* refPTL );; 
+#endif
+
 };
+
 /// VPS class
 
@@ -318,5 +338,5 @@
   UInt cpbSizeValue      [MAX_CPB_CNT][2];
   UInt ducpbSizeValue    [MAX_CPB_CNT][2];
-  UInt cbrFlag           [MAX_CPB_CNT][2];
+  Bool cbrFlag           [MAX_CPB_CNT][2];
   UInt duBitRateValue    [MAX_CPB_CNT][2];
 };
@@ -338,93 +358,90 @@
   UInt m_cpbRemovalDelayLengthMinus1;
   UInt m_dpbOutputDelayLengthMinus1;
-  UInt m_numDU;
   HrdSubLayerInfo m_HRD[MAX_TLAYER];
 
 public:
   TComHRD()
-  :m_nalHrdParametersPresentFlag(0)
-  ,m_vclHrdParametersPresentFlag(0)
-  ,m_subPicCpbParamsPresentFlag(false)
-  ,m_tickDivisorMinus2(0)
-  ,m_duCpbRemovalDelayLengthMinus1(0)
-  ,m_subPicCpbParamsInPicTimingSEIFlag(false)
-  ,m_dpbOutputDelayDuLengthMinus1(0)
-  ,m_bitRateScale(0)
-  ,m_cpbSizeScale(0)
-  ,m_initialCpbRemovalDelayLengthMinus1(0)
-  ,m_cpbRemovalDelayLengthMinus1(0)
-  ,m_dpbOutputDelayLengthMinus1(0)
+  :m_nalHrdParametersPresentFlag       (0)
+  ,m_vclHrdParametersPresentFlag       (0)
+  ,m_subPicCpbParamsPresentFlag        (false)
+  ,m_tickDivisorMinus2                 (0)
+  ,m_duCpbRemovalDelayLengthMinus1     (0)
+  ,m_subPicCpbParamsInPicTimingSEIFlag (false)
+  ,m_dpbOutputDelayDuLengthMinus1      (0)
+  ,m_bitRateScale                      (0)
+  ,m_cpbSizeScale                      (0)
+  ,m_initialCpbRemovalDelayLengthMinus1(23)
+  ,m_cpbRemovalDelayLengthMinus1       (23)
+  ,m_dpbOutputDelayLengthMinus1        (23)
   {}
 
   virtual ~TComHRD() {}
 
-  Void setNalHrdParametersPresentFlag       ( Bool flag )  { m_nalHrdParametersPresentFlag = flag;         }
-  Bool getNalHrdParametersPresentFlag       ( )            { return m_nalHrdParametersPresentFlag;         }
-
-  Void setVclHrdParametersPresentFlag       ( Bool flag )  { m_vclHrdParametersPresentFlag = flag;         }
-  Bool getVclHrdParametersPresentFlag       ( )            { return m_vclHrdParametersPresentFlag;         }
-
-  Void setSubPicCpbParamsPresentFlag        ( Bool flag )  { m_subPicCpbParamsPresentFlag = flag;          }
-  Bool getSubPicCpbParamsPresentFlag        ( )            { return m_subPicCpbParamsPresentFlag;          }
-  
-  Void setTickDivisorMinus2                 ( UInt value ) { m_tickDivisorMinus2 = value;                  }
-  UInt getTickDivisorMinus2                 ( )            { return m_tickDivisorMinus2;                   }
-
-  Void setDuCpbRemovalDelayLengthMinus1     ( UInt value ) { m_duCpbRemovalDelayLengthMinus1 = value;      }
-  UInt getDuCpbRemovalDelayLengthMinus1     ( )            { return m_duCpbRemovalDelayLengthMinus1;       }
-
-  Void setSubPicCpbParamsInPicTimingSEIFlag ( Bool flag)   { m_subPicCpbParamsInPicTimingSEIFlag = flag;   }
-  Bool getSubPicCpbParamsInPicTimingSEIFlag ()             { return m_subPicCpbParamsInPicTimingSEIFlag;   }
-
-  Void setDpbOutputDelayDuLengthMinus1      (UInt value )  { m_dpbOutputDelayDuLengthMinus1 = value;       }
-  UInt getDpbOutputDelayDuLengthMinus1      ()             { return m_dpbOutputDelayDuLengthMinus1;        }
-
-  Void setBitRateScale                      ( UInt value ) { m_bitRateScale = value;                       }
-  UInt getBitRateScale                      ( )            { return m_bitRateScale;                        }
-
-  Void setCpbSizeScale                      ( UInt value ) { m_cpbSizeScale = value;                       }
-  UInt getCpbSizeScale                      ( )            { return m_cpbSizeScale;                        }
-  Void setDuCpbSizeScale                    ( UInt value ) { m_ducpbSizeScale = value;                     }
-  UInt getDuCpbSizeScale                    ( )            { return m_ducpbSizeScale;                      }
-
-  Void setInitialCpbRemovalDelayLengthMinus1( UInt value ) { m_initialCpbRemovalDelayLengthMinus1 = value; }
-  UInt getInitialCpbRemovalDelayLengthMinus1( )            { return m_initialCpbRemovalDelayLengthMinus1;  }
-
-  Void setCpbRemovalDelayLengthMinus1       ( UInt value ) { m_cpbRemovalDelayLengthMinus1 = value;        }
-  UInt getCpbRemovalDelayLengthMinus1       ( )            { return m_cpbRemovalDelayLengthMinus1;         }
-
-  Void setDpbOutputDelayLengthMinus1        ( UInt value ) { m_dpbOutputDelayLengthMinus1 = value;         }
-  UInt getDpbOutputDelayLengthMinus1        ( )            { return m_dpbOutputDelayLengthMinus1;          }
-
-  Void setFixedPicRateFlag       ( Int layer, Bool flag )  { m_HRD[layer].fixedPicRateFlag = flag;         }
-  Bool getFixedPicRateFlag       ( Int layer            )  { return m_HRD[layer].fixedPicRateFlag;         }
-
-  Void setFixedPicRateWithinCvsFlag       ( Int layer, Bool flag )  { m_HRD[layer].fixedPicRateWithinCvsFlag = flag;         }
-  Bool getFixedPicRateWithinCvsFlag       ( Int layer            )  { return m_HRD[layer].fixedPicRateWithinCvsFlag;         }
-
-  Void setPicDurationInTcMinus1  ( Int layer, UInt value ) { m_HRD[layer].picDurationInTcMinus1 = value;   }
-  UInt getPicDurationInTcMinus1  ( Int layer             ) { return m_HRD[layer].picDurationInTcMinus1;    }
-
-  Void setLowDelayHrdFlag        ( Int layer, Bool flag )  { m_HRD[layer].lowDelayHrdFlag = flag;          }
-  Bool getLowDelayHrdFlag        ( Int layer            )  { return m_HRD[layer].lowDelayHrdFlag;          }
-
-  Void setCpbCntMinus1           ( Int layer, UInt value ) { m_HRD[layer].cpbCntMinus1 = value; }
-  UInt getCpbCntMinus1           ( Int layer            )  { return m_HRD[layer].cpbCntMinus1; }
-  
-  Void setBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].bitRateValueMinus1[cpbcnt][nalOrVcl] = value; }
-  UInt getBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl             ) { return m_HRD[layer].bitRateValueMinus1[cpbcnt][nalOrVcl];  }
-
-  Void setCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].cpbSizeValue[cpbcnt][nalOrVcl] = value;       }
-  UInt getCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl            )  { return m_HRD[layer].cpbSizeValue[cpbcnt][nalOrVcl];        }
-  Void setDuCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].ducpbSizeValue[cpbcnt][nalOrVcl] = value;       }
-  UInt getDuCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl            )  { return m_HRD[layer].ducpbSizeValue[cpbcnt][nalOrVcl];        }
-  Void setDuBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].duBitRateValue[cpbcnt][nalOrVcl] = value;       }
-  UInt getDuBitRateValueMinus1     (Int layer, Int cpbcnt, Int nalOrVcl )              { return m_HRD[layer].duBitRateValue[cpbcnt][nalOrVcl];        }
-  Void setCbrFlag                ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl] = value;            }
-  Bool getCbrFlag                ( Int layer, Int cpbcnt, Int nalOrVcl             ) { return m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl];             }
-
-  Void setNumDU                              ( UInt value ) { m_numDU = value;                            }
-  UInt getNumDU                              ( )            { return m_numDU;          }
-  Bool getCpbDpbDelaysPresentFlag() { return getNalHrdParametersPresentFlag() || getVclHrdParametersPresentFlag(); }
+  Void    setNalHrdParametersPresentFlag( Bool flag )                                { m_nalHrdParametersPresentFlag = flag;                      }
+  Bool    getNalHrdParametersPresentFlag( ) const                                    { return m_nalHrdParametersPresentFlag;                      }
+
+  Void    setVclHrdParametersPresentFlag( Bool flag )                                { m_vclHrdParametersPresentFlag = flag;                      }
+  Bool    getVclHrdParametersPresentFlag( ) const                                    { return m_vclHrdParametersPresentFlag;                      }
+
+  Void    setSubPicCpbParamsPresentFlag( Bool flag )                                 { m_subPicCpbParamsPresentFlag = flag;                       }
+  Bool    getSubPicCpbParamsPresentFlag( ) const                                     { return m_subPicCpbParamsPresentFlag;                       }
+
+  Void    setTickDivisorMinus2( UInt value )                                         { m_tickDivisorMinus2 = value;                               }
+  UInt    getTickDivisorMinus2( ) const                                              { return m_tickDivisorMinus2;                                }
+
+  Void    setDuCpbRemovalDelayLengthMinus1( UInt value )                             { m_duCpbRemovalDelayLengthMinus1 = value;                   }
+  UInt    getDuCpbRemovalDelayLengthMinus1( ) const                                  { return m_duCpbRemovalDelayLengthMinus1;                    }
+
+  Void    setSubPicCpbParamsInPicTimingSEIFlag( Bool flag)                           { m_subPicCpbParamsInPicTimingSEIFlag = flag;                }
+  Bool    getSubPicCpbParamsInPicTimingSEIFlag( ) const                              { return m_subPicCpbParamsInPicTimingSEIFlag;                }
+
+  Void    setDpbOutputDelayDuLengthMinus1(UInt value )                               { m_dpbOutputDelayDuLengthMinus1 = value;                    }
+  UInt    getDpbOutputDelayDuLengthMinus1( ) const                                   { return m_dpbOutputDelayDuLengthMinus1;                     }
+
+  Void    setBitRateScale( UInt value )                                              { m_bitRateScale = value;                                    }
+  UInt    getBitRateScale( ) const                                                   { return m_bitRateScale;                                     }
+
+  Void    setCpbSizeScale( UInt value )                                              { m_cpbSizeScale = value;                                    }
+  UInt    getCpbSizeScale( ) const                                                   { return m_cpbSizeScale;                                     }
+  Void    setDuCpbSizeScale( UInt value )                                            { m_ducpbSizeScale = value;                                  }
+  UInt    getDuCpbSizeScale( ) const                                                 { return m_ducpbSizeScale;                                   }
+
+  Void    setInitialCpbRemovalDelayLengthMinus1( UInt value )                        { m_initialCpbRemovalDelayLengthMinus1 = value;              }
+  UInt    getInitialCpbRemovalDelayLengthMinus1( ) const                             { return m_initialCpbRemovalDelayLengthMinus1;               }
+
+  Void    setCpbRemovalDelayLengthMinus1( UInt value )                               { m_cpbRemovalDelayLengthMinus1 = value;                     }
+  UInt    getCpbRemovalDelayLengthMinus1( ) const                                    { return m_cpbRemovalDelayLengthMinus1;                      }
+
+  Void    setDpbOutputDelayLengthMinus1( UInt value )                                { m_dpbOutputDelayLengthMinus1 = value;                      }
+  UInt    getDpbOutputDelayLengthMinus1( ) const                                     { return m_dpbOutputDelayLengthMinus1;                       }
+
+  Void    setFixedPicRateFlag( Int layer, Bool flag )                                { m_HRD[layer].fixedPicRateFlag = flag;                      }
+  Bool    getFixedPicRateFlag( Int layer ) const                                     { return m_HRD[layer].fixedPicRateFlag;                      }
+
+  Void    setFixedPicRateWithinCvsFlag( Int layer, Bool flag )                       { m_HRD[layer].fixedPicRateWithinCvsFlag = flag;             }
+  Bool    getFixedPicRateWithinCvsFlag( Int layer ) const                            { return m_HRD[layer].fixedPicRateWithinCvsFlag;             }
+
+  Void    setPicDurationInTcMinus1( Int layer, UInt value )                          { m_HRD[layer].picDurationInTcMinus1 = value;                }
+  UInt    getPicDurationInTcMinus1( Int layer ) const                                { return m_HRD[layer].picDurationInTcMinus1;                 }
+
+  Void    setLowDelayHrdFlag( Int layer, Bool flag )                                 { m_HRD[layer].lowDelayHrdFlag = flag;                       }
+  Bool    getLowDelayHrdFlag( Int layer ) const                                      { return m_HRD[layer].lowDelayHrdFlag;                       }
+
+  Void    setCpbCntMinus1( Int layer, UInt value )                                   { m_HRD[layer].cpbCntMinus1 = value;                         }
+  UInt    getCpbCntMinus1( Int layer ) const                                         { return m_HRD[layer].cpbCntMinus1;                          }
+
+  Void    setBitRateValueMinus1( Int layer, Int cpbcnt, Int nalOrVcl, UInt value )   { m_HRD[layer].bitRateValueMinus1[cpbcnt][nalOrVcl] = value; }
+  UInt    getBitRateValueMinus1( Int layer, Int cpbcnt, Int nalOrVcl ) const         { return m_HRD[layer].bitRateValueMinus1[cpbcnt][nalOrVcl];  }
+
+  Void    setCpbSizeValueMinus1( Int layer, Int cpbcnt, Int nalOrVcl, UInt value )   { m_HRD[layer].cpbSizeValue[cpbcnt][nalOrVcl] = value;       }
+  UInt    getCpbSizeValueMinus1( Int layer, Int cpbcnt, Int nalOrVcl ) const         { return m_HRD[layer].cpbSizeValue[cpbcnt][nalOrVcl];        }
+  Void    setDuCpbSizeValueMinus1( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].ducpbSizeValue[cpbcnt][nalOrVcl] = value;     }
+  UInt    getDuCpbSizeValueMinus1( Int layer, Int cpbcnt, Int nalOrVcl ) const       { return m_HRD[layer].ducpbSizeValue[cpbcnt][nalOrVcl];      }
+  Void    setDuBitRateValueMinus1( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].duBitRateValue[cpbcnt][nalOrVcl] = value;     }
+  UInt    getDuBitRateValueMinus1(Int layer, Int cpbcnt, Int nalOrVcl ) const        { return m_HRD[layer].duBitRateValue[cpbcnt][nalOrVcl];      }
+  Void    setCbrFlag( Int layer, Int cpbcnt, Int nalOrVcl, Bool value )              { m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl] = value;            }
+  Bool    getCbrFlag( Int layer, Int cpbcnt, Int nalOrVcl ) const                    { return m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl];             }
+
+  Bool    getCpbDpbDelaysPresentFlag( ) const                      { return getNalHrdParametersPresentFlag() || getVclHrdParametersPresentFlag(); }
 };
 
@@ -438,27 +455,40 @@
 public:
   TimingInfo()
-  : m_timingInfoPresentFlag(false)
-  , m_numUnitsInTick(1001)
-  , m_timeScale(60000)
+  : m_timingInfoPresentFlag      (false)
+  , m_numUnitsInTick             (1001)
+  , m_timeScale                  (60000)
   , m_pocProportionalToTimingFlag(false)
-  , m_numTicksPocDiffOneMinus1(0) {}
-
-  Void setTimingInfoPresentFlag             ( Bool flag )  { m_timingInfoPresentFlag = flag;               }
-  Bool getTimingInfoPresentFlag             ( )            { return m_timingInfoPresentFlag;               }
-
-  Void setNumUnitsInTick                    ( UInt value ) { m_numUnitsInTick = value;                     }
-  UInt getNumUnitsInTick                    ( )            { return m_numUnitsInTick;                      }
-
-  Void setTimeScale                         ( UInt value ) { m_timeScale = value;                          }
-  UInt getTimeScale                         ( )            { return m_timeScale;                           }
-  
-  Bool getPocProportionalToTimingFlag       ( )            { return m_pocProportionalToTimingFlag;         }
-  Void setPocProportionalToTimingFlag       (Bool x      ) { m_pocProportionalToTimingFlag = x;            }
-  
-  Int  getNumTicksPocDiffOneMinus1          ( )            { return m_numTicksPocDiffOneMinus1;            }
-  Void setNumTicksPocDiffOneMinus1          (Int x       ) { m_numTicksPocDiffOneMinus1 = x;               }
+  , m_numTicksPocDiffOneMinus1   (0)
+  {}
+
+  Void setTimingInfoPresentFlag( Bool flag )   { m_timingInfoPresentFlag = flag;       }
+  Bool getTimingInfoPresentFlag( ) const       { return m_timingInfoPresentFlag;       }
+
+  Void setNumUnitsInTick( UInt value )         { m_numUnitsInTick = value;             }
+  UInt getNumUnitsInTick( ) const              { return m_numUnitsInTick;              }
+
+  Void setTimeScale( UInt value )              { m_timeScale = value;                  }
+  UInt getTimeScale( ) const                   { return m_timeScale;                   }
+
+  Void setPocProportionalToTimingFlag(Bool x)  { m_pocProportionalToTimingFlag = x;    }
+  Bool getPocProportionalToTimingFlag( ) const { return m_pocProportionalToTimingFlag; }
+
+  Void setNumTicksPocDiffOneMinus1(Int x)      { m_numTicksPocDiffOneMinus1 = x;       }
+  Int  getNumTicksPocDiffOneMinus1( ) const    { return m_numTicksPocDiffOneMinus1;    }
 };
 
-#if H_MV
+struct ChromaQpAdj
+{
+  union
+  {
+    struct {
+      Int CbOffset;
+      Int CrOffset;
+    } comp;
+    Int offset[2]; /* two chroma components */
+  } u;
+};
+
+#if NH_MV
 
 class TComVideoSignalInfo
@@ -471,37 +501,36 @@
   Int  m_matrixCoeffsVps;
 public: 
-  Void setVideoVpsFormat( Int  val ) { m_videoVpsFormat = val; } 
-  Int  getVideoVpsFormat(  ) { return m_videoVpsFormat; } 
-
-  Void setVideoFullRangeVpsFlag( Bool flag ) { m_videoFullRangeVpsFlag = flag; } 
-  Bool getVideoFullRangeVpsFlag(  ) { return m_videoFullRangeVpsFlag; } 
-
-  Void setColourPrimariesVps( Int  val ) { m_colourPrimariesVps = val; } 
-  Int  getColourPrimariesVps(  ) { return m_colourPrimariesVps; } 
-
-  Void setTransferCharacteristicsVps( Int  val ) { m_transferCharacteristicsVps = val; } 
-  Int  getTransferCharacteristicsVps(  ) { return m_transferCharacteristicsVps; } 
-
-  Void setMatrixCoeffsVps( Int  val ) { m_matrixCoeffsVps = val; } 
-  Int  getMatrixCoeffsVps(  ) { return m_matrixCoeffsVps; } 
+  Void    setVideoVpsFormat( Int  val )                                              { m_videoVpsFormat = val;                                    }
+  Int     getVideoVpsFormat(  ) const                                                { return m_videoVpsFormat;                                   }
+
+  Void    setVideoFullRangeVpsFlag( Bool flag )                                      { m_videoFullRangeVpsFlag = flag;                            }
+  Bool    getVideoFullRangeVpsFlag(  ) const                                         { return m_videoFullRangeVpsFlag;                            }
+
+  Void    setColourPrimariesVps( Int  val )                                          { m_colourPrimariesVps = val;                                }
+  Int     getColourPrimariesVps(  ) const                                            { return m_colourPrimariesVps;                               }
+
+  Void    setTransferCharacteristicsVps( Int  val )                                  { m_transferCharacteristicsVps = val;                        }
+  Int     getTransferCharacteristicsVps(  ) const                                    { return m_transferCharacteristicsVps;                       }
+
+  Void    setMatrixCoeffsVps( Int  val )                                             { m_matrixCoeffsVps = val;                                   }
+  Int     getMatrixCoeffsVps(  ) const                                               { return m_matrixCoeffsVps;                                  }
 };
 
 class TComVpsVuiBspHrdParameters
 {
-
   /* Not yet tested */
 private: 
 
-  Int   m_vpsNumAddHrdParams;
-  Bool* m_cprmsAddPresentFlag;
-  TComHRD* m_hrdParameters; 
-  Int*  m_numSubLayerHrdMinus1;
-  Int*  m_numSignalledPartitioningSchemes;
-  Int** m_numPartitionsInSchemeMinus1;
-
-  Bool****  m_layerIncludedInPartitionFlag;
-  Int***    m_numBspSchedulesMinus1;
-  Int*****  m_bspHrdIdx;
-  Int*****  m_bspSchedIdx;
+  Int       m_vpsNumAddHrdParams;
+  BoolAry1d m_cprmsAddPresentFlag;
+  std::vector<TComHRD> m_hrdParameters; 
+  IntAry1d  m_numSubLayerHrdMinus1;
+  IntAry1d  m_numSignalledPartitioningSchemes;
+  IntAry2d  m_numPartitionsInSchemeMinus1;
+
+  BoolAry4d m_layerIncludedInPartitionFlag;
+  IntAry3d  m_numBspSchedulesMinus1;
+  IntAry5d  m_bspHrdIdx;
+  IntAry5d  m_bspSchedIdx;
     
   // Array sizes
@@ -510,44 +539,42 @@
   Int      m_numOls; 
   TComVPS* m_vps; 
-public:   
-
-  ~TComVpsVuiBspHrdParameters();
+public:     
   
-  Void createAfterVpsNumAddHrdParams( TComVPS* vps );
-  Void createAfterNumSignalledPartitioningSchemes(Int h );
-  Void createAfterNumPartitionsInSchemeMinus1(Int h, Int j);
-  Void createAfterNumBspSchedulesMinus1( Int h, Int i, Int t);
-
-  Void setVpsNumAddHrdParams( Int  val ) { m_vpsNumAddHrdParams = val; } 
-  Int  getVpsNumAddHrdParams(  ) { return m_vpsNumAddHrdParams; } 
-  
-  Void setCprmsAddPresentFlag( Int i, Bool flag ) { m_cprmsAddPresentFlag[i - m_offsetHrdParamIdx] = flag; } 
-  Bool getCprmsAddPresentFlag( Int i ) { return m_cprmsAddPresentFlag[i  - m_offsetHrdParamIdx]; } 
-  
-  Void setNumSubLayerHrdMinus1( Int i, Int  val ) { m_numSubLayerHrdMinus1[i  - m_offsetHrdParamIdx] = val; } 
-  Int  getNumSubLayerHrdMinus1( Int i ) { return m_numSubLayerHrdMinus1[i  - m_offsetHrdParamIdx]; } 
-  
-  Void setNumSignalledPartitioningSchemes( Int h, Int  val ) { m_numSignalledPartitioningSchemes[h] = val; } 
-  Int  getNumSignalledPartitioningSchemes( Int h ) { return m_numSignalledPartitioningSchemes[h]; } 
-  
-  Void setNumPartitionsInSchemeMinus1( Int h, Int j, Int  val ) { m_numPartitionsInSchemeMinus1[h][j] = val; } 
-  Int  getNumPartitionsInSchemeMinus1( Int h, Int j ) { return m_numPartitionsInSchemeMinus1[h][j]; } 
-  
-  Void setLayerIncludedInPartitionFlag( Int h, Int j, Int k, Int r, Bool flag ) { m_layerIncludedInPartitionFlag[h][j][k][r] = flag; } 
-  Bool getLayerIncludedInPartitionFlag( Int h, Int j, Int k, Int r ) { return m_layerIncludedInPartitionFlag[h][j][k][r]; } 
-  
-  Void setNumBspSchedulesMinus1( Int h, Int i, Int t, Int  val ) { m_numBspSchedulesMinus1[h][i][t] = val; } 
-  Int  getNumBspSchedulesMinus1( Int h, Int i, Int t ) { return m_numBspSchedulesMinus1[h][i][t]; } 
-  
-  Void setBspHrdIdx( Int h, Int i, Int t, Int j, Int k, Int  val ) { m_bspHrdIdx[h][i  - m_offsetHrdParamIdx][t][j][k] = val; } 
-  Int  getBspHrdIdx( Int h, Int i, Int t, Int j, Int k ) { return m_bspHrdIdx[h][i  - m_offsetHrdParamIdx][t][j][k]; } 
-  
-  Int  getBspHrdIdxLen( TComVPS* vps );
-
-  Void setBspSchedIdx( Int h, Int i, Int t, Int j, Int k, Int  val ) { m_bspSchedIdx[h][i - m_offsetHrdParamIdx][t][j][k] = val; } 
-  Int  getBspSchedIdx( Int h, Int i, Int t, Int j, Int k ) { return m_bspSchedIdx[h][i - m_offsetHrdParamIdx][t][j][k]; } 
-
-  Void setHrdParametermeters( Int k, TComHRD* val  ) {  *(m_hrdParameters + k ) = *val; }; 
-  TComHRD* getHrdParametermeters( Int k ) {  return m_hrdParameters + k; }; 
+  Void    createAfterVpsNumAddHrdParams( const TComVPS* vps );
+  Void    createAfterNumSignalledPartitioningSchemes(const TComVPS* vps, Int h );
+  Void    createAfterNumPartitionsInSchemeMinus1(const TComVPS* vps, Int h, Int j);
+  Void    createAfterNumBspSchedulesMinus1(const TComVPS* vps, Int h, Int i, Int t);
+
+  Void    setVpsNumAddHrdParams( Int  val )                                          { m_vpsNumAddHrdParams = val;                                }
+  Int     getVpsNumAddHrdParams(  ) const                                            { return m_vpsNumAddHrdParams;                               }
+
+  Void    setCprmsAddPresentFlag( Int i, Bool flag )                                 { m_cprmsAddPresentFlag[i - m_offsetHrdParamIdx] = flag;     }
+  Bool    getCprmsAddPresentFlag( Int i ) const                                      { return m_cprmsAddPresentFlag[i  - m_offsetHrdParamIdx];    }
+
+  Void    setNumSubLayerHrdMinus1( Int i, Int  val )                                 { m_numSubLayerHrdMinus1[i  - m_offsetHrdParamIdx] = val;    }
+  Int     getNumSubLayerHrdMinus1( Int i ) const                                     { return m_numSubLayerHrdMinus1[i  - m_offsetHrdParamIdx];   }
+
+  Void    setNumSignalledPartitioningSchemes( Int h, Int  val )                      { m_numSignalledPartitioningSchemes[h] = val;                }
+  Int     getNumSignalledPartitioningSchemes( Int h ) const                          { return m_numSignalledPartitioningSchemes[h];               }
+
+  Void    setNumPartitionsInSchemeMinus1( Int h, Int j, Int  val )                   { m_numPartitionsInSchemeMinus1[h][j] = val;                 }
+  Int     getNumPartitionsInSchemeMinus1( Int h, Int j ) const                       { return m_numPartitionsInSchemeMinus1[h][j];                }
+
+  Void    setLayerIncludedInPartitionFlag( Int h, Int j, Int k, Int r, Bool flag )   { m_layerIncludedInPartitionFlag[h][j][k][r] = flag;         }
+  Bool    getLayerIncludedInPartitionFlag( Int h, Int j, Int k, Int r ) const        { return m_layerIncludedInPartitionFlag[h][j][k][r];         }
+
+  Void    setNumBspSchedulesMinus1( Int h, Int i, Int t, Int  val )                  { m_numBspSchedulesMinus1[h][i][t] = val;                    }
+  Int     getNumBspSchedulesMinus1( Int h, Int i, Int t ) const                      { return m_numBspSchedulesMinus1[h][i][t];                   }
+
+  Void    setBspHrdIdx( Int h, Int i, Int t, Int j, Int k, Int  val )                { m_bspHrdIdx[h][i  - m_offsetHrdParamIdx][t][j][k] = val;   }
+  Int     getBspHrdIdx( Int h, Int i, Int t, Int j, Int k ) const                    { return m_bspHrdIdx[h][i  - m_offsetHrdParamIdx][t][j][k];  }
+
+  Int     getBspHrdIdxLen ( const TComVPS* vps ) const ;
+
+  Void    setBspSchedIdx( Int h, Int i, Int t, Int j, Int k, Int  val )              { m_bspSchedIdx[h][i - m_offsetHrdParamIdx][t][j][k] = val;  }
+  Int     getBspSchedIdx( Int h, Int i, Int t, Int j, Int k ) const                  { return m_bspSchedIdx[h][i - m_offsetHrdParamIdx][t][j][k]; }
+
+  Void    setHrdParametermeters( Int k, TComHRD val  )                               {  m_hrdParameters[k] = val;                                 }
+  const   TComHRD* getHrdParametermeters( Int k ) const                              {  return &m_hrdParameters[k];                               }
 };
 
@@ -555,129 +582,128 @@
 {
 private:
-  Bool m_crossLayerPicTypeAlignedFlag;
-  Bool m_crossLayerIrapAlignedFlag;
-  Bool m_allLayersIdrAlignedFlag;
-  Bool m_bitRatePresentVpsFlag;
-  Bool m_picRatePresentVpsFlag;
-  Bool m_bitRatePresentFlag          [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
-  Bool m_picRatePresentFlag          [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
-  Int  m_avgBitRate                  [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
-  Int  m_maxBitRate                  [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
-  Int  m_constantPicRateIdc          [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
-  Int  m_avgPicRate                  [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
-  Bool m_videoSignalInfoIdxPresentFlag;
-  Int  m_vpsNumVideoSignalInfoMinus1;
-  TComVideoSignalInfo* m_videoSignalInfo[MAX_NUM_VIDEO_SIGNAL_INFO];   
-  Int  m_vpsVideoSignalInfoIdx       [MAX_NUM_VIDEO_SIGNAL_INFO];
-  Bool m_tilesNotInUseFlag;
-  Bool m_tilesInUseFlag              [MAX_NUM_LAYERS];
-  Bool m_loopFilterNotAcrossTilesFlag[MAX_NUM_LAYERS];
-  Bool m_tileBoundariesAlignedFlag   [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
-  Bool m_wppNotInUseFlag;
-  Bool m_wppInUseFlag                [MAX_NUM_LAYERS];
-  Bool m_singleLayerForNonIrapFlag;
-  Bool m_higherLayerIrapSkipFlag;
-  Bool m_ilpRestrictedRefLayersFlag;
-  Int  m_minSpatialSegmentOffsetPlus1[MAX_NUM_LAYERS][MAX_NUM_LAYERS];
-  Bool m_ctuBasedOffsetEnabledFlag   [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
-  Int  m_minHorizontalCtuOffsetPlus1 [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
-  Bool m_vpsVuiBspHrdPresentFlag;
-  TComVpsVuiBspHrdParameters* m_vpsVuiBspHrdParameters; 
-  Bool m_baseLayerParameterSetCompatibilityFlag[MAX_NUM_LAYERS];
+  Bool                               m_crossLayerPicTypeAlignedFlag          ;
+  Bool                               m_crossLayerIrapAlignedFlag             ;
+  Bool                               m_allLayersIdrAlignedFlag               ;
+  Bool                               m_bitRatePresentVpsFlag                 ;
+  Bool                               m_picRatePresentVpsFlag                 ;                                     
+  BoolAry2d                          m_bitRatePresentFlag                    ;
+  BoolAry2d                          m_picRatePresentFlag                    ;
+  IntAry2d                           m_avgBitRate                            ;
+  IntAry2d                           m_maxBitRate                            ;
+  IntAry2d                           m_constantPicRateIdc                    ;
+  IntAry2d                           m_avgPicRate                            ;
+  Bool                               m_videoSignalInfoIdxPresentFlag         ;
+  Int                                m_vpsNumVideoSignalInfoMinus1           ;
+  std::vector< TComVideoSignalInfo > m_videoSignalInfo                       ;
+  IntAry1d                           m_vpsVideoSignalInfoIdx                 ;
+  Bool                               m_tilesNotInUseFlag;                    ;
+  BoolAry1d                          m_tilesInUseFlag                        ; 
+  BoolAry1d                          m_loopFilterNotAcrossTilesFlag          ; 
+  BoolAry2d                          m_tileBoundariesAlignedFlag             ;
+  Bool                               m_wppNotInUseFlag                       ;             
+  BoolAry1d                          m_wppInUseFlag                          ;                
+  Bool                               m_singleLayerForNonIrapFlag             ;
+  Bool                               m_higherLayerIrapSkipFlag               ;
+  Bool                               m_ilpRestrictedRefLayersFlag            ;
+  IntAry2d                           m_minSpatialSegmentOffsetPlus1          ;
+  BoolAry2d                          m_ctuBasedOffsetEnabledFlag             ;
+  IntAry2d                           m_minHorizontalCtuOffsetPlus1           ;
+  Bool                               m_vpsVuiBspHrdPresentFlag               ;
+  TComVpsVuiBspHrdParameters         m_vpsVuiBspHrdParameters                ; 
+  BoolAry1d                          m_baseLayerParameterSetCompatibilityFlag;
 
 public: 
-  TComVPSVUI();
-  ~TComVPSVUI(); 
-  Void setCrossLayerPicTypeAlignedFlag( Bool flag ) { m_crossLayerPicTypeAlignedFlag = flag; } 
-  Bool getCrossLayerPicTypeAlignedFlag(  ) { return m_crossLayerPicTypeAlignedFlag; } 
-
-  Void setCrossLayerIrapAlignedFlag( Bool flag ) { m_crossLayerIrapAlignedFlag = flag; } 
-  Bool getCrossLayerIrapAlignedFlag(  ) { return m_crossLayerIrapAlignedFlag; } 
-
-  Void setAllLayersIdrAlignedFlag( Bool flag ) { m_allLayersIdrAlignedFlag = flag; } 
-  Bool getAllLayersIdrAlignedFlag(  ) { return m_allLayersIdrAlignedFlag; } 
-
-  Void setBitRatePresentVpsFlag( Bool flag ) { m_bitRatePresentVpsFlag = flag; } 
-  Bool getBitRatePresentVpsFlag(  ) { return m_bitRatePresentVpsFlag; } 
-
-  Void setPicRatePresentVpsFlag( Bool flag ) { m_picRatePresentVpsFlag = flag; } 
-  Bool getPicRatePresentVpsFlag(  ) { return m_picRatePresentVpsFlag; } 
-
-  Void setBitRatePresentFlag( Int i, Int j, Bool flag ) { m_bitRatePresentFlag[i][j] = flag; } 
-  Bool getBitRatePresentFlag( Int i, Int j ) { return m_bitRatePresentFlag[i][j]; } 
-
-  Void setPicRatePresentFlag( Int i, Int j, Bool flag ) { m_picRatePresentFlag[i][j] = flag; } 
-  Bool getPicRatePresentFlag( Int i, Int j ) { return m_picRatePresentFlag[i][j]; } 
-
-  Void setAvgBitRate( Int i, Int j, Int  val ) { m_avgBitRate[i][j] = val; } 
-  Int  getAvgBitRate( Int i, Int j ) { return m_avgBitRate[i][j]; } 
-
-  Void setMaxBitRate( Int i, Int j, Int  val ) { m_maxBitRate[i][j] = val; } 
-  Int  getMaxBitRate( Int i, Int j ) { return m_maxBitRate[i][j]; } 
-
-  Void setConstantPicRateIdc( Int i, Int j, Int  val ) { m_constantPicRateIdc[i][j] = val; } 
-  Int  getConstantPicRateIdc( Int i, Int j ) { return m_constantPicRateIdc[i][j]; } 
-
-  Void setAvgPicRate( Int i, Int j, Int  val ) { m_avgPicRate[i][j] = val; } 
-  Int  getAvgPicRate( Int i, Int j ) { return m_avgPicRate[i][j]; } 
-
-  Void setVideoSignalInfoIdxPresentFlag( Bool flag ) { m_videoSignalInfoIdxPresentFlag = flag; } 
-  Bool getVideoSignalInfoIdxPresentFlag(  ) { return m_videoSignalInfoIdxPresentFlag; } 
-
-  Void    setVideoSignalInfo( Int i, TComVideoSignalInfo* val )                        { m_videoSignalInfo[i] = val;  }  
-  TComVideoSignalInfo* getVideoSignalInfo( Int i )                                     { return m_videoSignalInfo[i]; }
-
-  Void setVpsNumVideoSignalInfoMinus1( Int  val ) { m_vpsNumVideoSignalInfoMinus1 = val; } 
-  Int  getVpsNumVideoSignalInfoMinus1(  ) { return m_vpsNumVideoSignalInfoMinus1; } 
-
-  Void setVpsVideoSignalInfoIdx( Int i, Int  val ) { m_vpsVideoSignalInfoIdx[i] = val; } 
-  Int  getVpsVideoSignalInfoIdx( Int i ) { return m_vpsVideoSignalInfoIdx[i]; } 
-
-  Void setTilesNotInUseFlag( Bool flag ) { m_tilesNotInUseFlag = flag; } 
-  Bool getTilesNotInUseFlag(  ) { return m_tilesNotInUseFlag; } 
-
-  Void setTilesInUseFlag( Int i, Bool flag ) { m_tilesInUseFlag[i] = flag; } 
-  Bool getTilesInUseFlag( Int i ) { return m_tilesInUseFlag[i]; } 
-
-  Void setLoopFilterNotAcrossTilesFlag( Int i, Int  val ) { m_loopFilterNotAcrossTilesFlag[i] = val; } 
-  Bool getLoopFilterNotAcrossTilesFlag( Int i ) { return m_loopFilterNotAcrossTilesFlag[i]; } 
-
-  Void setTileBoundariesAlignedFlag( Int i, Int j, Bool flag ) { m_tileBoundariesAlignedFlag[i][j] = flag; } 
-  Bool getTileBoundariesAlignedFlag( Int i, Int j ) { return m_tileBoundariesAlignedFlag[i][j]; } 
-
-  Void setWppNotInUseFlag( Bool flag ) { m_wppNotInUseFlag = flag; } 
-  Bool getWppNotInUseFlag(  ) { return m_wppNotInUseFlag; } 
-
-  Void setWppInUseFlag( Int i, Bool flag ) { m_wppInUseFlag[i] = flag; } 
-  Bool getWppInUseFlag( Int i ) { return m_wppInUseFlag[i]; } 
-
-  Void setSingleLayerForNonIrapFlag( Bool flag ) { m_singleLayerForNonIrapFlag = flag; } 
-  Bool getSingleLayerForNonIrapFlag(  ) { return m_singleLayerForNonIrapFlag; } 
-
-  Void setHigherLayerIrapSkipFlag( Bool flag ) { m_higherLayerIrapSkipFlag = flag; } 
-  Bool getHigherLayerIrapSkipFlag(  ) { return m_higherLayerIrapSkipFlag; } 
-
-  Void setIlpRestrictedRefLayersFlag( Bool flag ) { m_ilpRestrictedRefLayersFlag = flag; } 
-  Bool getIlpRestrictedRefLayersFlag(  ) { return m_ilpRestrictedRefLayersFlag; } 
-
-  Void setMinSpatialSegmentOffsetPlus1( Int i, Int j, Int  val ) { m_minSpatialSegmentOffsetPlus1[i][j] = val; } 
-  Int  getMinSpatialSegmentOffsetPlus1( Int i, Int j ) { return m_minSpatialSegmentOffsetPlus1[i][j]; } 
-
-  Void setCtuBasedOffsetEnabledFlag( Int i, Int j, Bool flag ) { m_ctuBasedOffsetEnabledFlag[i][j] = flag; } 
-  Bool getCtuBasedOffsetEnabledFlag( Int i, Int j ) { return m_ctuBasedOffsetEnabledFlag[i][j]; } 
-
-  Void setMinHorizontalCtuOffsetPlus1( Int i, Int j, Int  val ) { m_minHorizontalCtuOffsetPlus1[i][j] = val; } 
-  Int  getMinHorizontalCtuOffsetPlus1( Int i, Int j ) { return m_minHorizontalCtuOffsetPlus1[i][j]; } 
-
-  Void setVpsVuiBspHrdPresentFlag( Bool flag ) { m_vpsVuiBspHrdPresentFlag = flag; } 
-  Bool getVpsVuiBspHrdPresentFlag(  ) { return m_vpsVuiBspHrdPresentFlag; }
-
-  Void setVpsVuiBspHrdParameters( TComVpsVuiBspHrdParameters* val) {  m_vpsVuiBspHrdParameters = val; } 
-  TComVpsVuiBspHrdParameters* getVpsVuiBspHrdParameters(  ) { return m_vpsVuiBspHrdParameters; }
-
-  Void setBaseLayerParameterSetCompatibilityFlag( Int i, Bool flag ) { m_baseLayerParameterSetCompatibilityFlag[i] = flag; } 
-  Bool getBaseLayerParameterSetCompatibilityFlag( Int i ) { return m_baseLayerParameterSetCompatibilityFlag[i]; } 
-
-  Void inferVpsVui( Bool encoderFlag );
+
+  Void    init( Int numLayerSets, Int maxNumSubLayers, Int maxNumLayers );
+
+  Void    setCrossLayerPicTypeAlignedFlag( Bool flag )                               { m_crossLayerPicTypeAlignedFlag = flag;                     }
+  Bool    getCrossLayerPicTypeAlignedFlag(  ) const                                  { return m_crossLayerPicTypeAlignedFlag;                     }
+
+  Void    setCrossLayerIrapAlignedFlag( Bool flag )                                  { m_crossLayerIrapAlignedFlag = flag;                        }
+  Bool    getCrossLayerIrapAlignedFlag(  ) const                                     { return m_crossLayerIrapAlignedFlag;                        }
+
+  Void    setAllLayersIdrAlignedFlag( Bool flag )                                    { m_allLayersIdrAlignedFlag = flag;                          }
+  Bool    getAllLayersIdrAlignedFlag(  ) const                                       { return m_allLayersIdrAlignedFlag;                          }
+
+  Void    setBitRatePresentVpsFlag( Bool flag )                                      { m_bitRatePresentVpsFlag = flag;                            }
+  Bool    getBitRatePresentVpsFlag(  ) const                                         { return m_bitRatePresentVpsFlag;                            }
+
+  Void    setPicRatePresentVpsFlag( Bool flag )                                      { m_picRatePresentVpsFlag = flag;                            }
+  Bool    getPicRatePresentVpsFlag(  ) const                                         { return m_picRatePresentVpsFlag;                            }
+
+  Void    setBitRatePresentFlag( Int i, Int j, Bool flag )                           { m_bitRatePresentFlag[i][j] = flag;                         }
+  Bool    getBitRatePresentFlag( Int i, Int j ) const                                { return m_bitRatePresentFlag[i][j];                         }
+
+  Void    setPicRatePresentFlag( Int i, Int j, Bool flag )                           { m_picRatePresentFlag[i][j] = flag;                         }
+  Bool    getPicRatePresentFlag( Int i, Int j ) const                                { return m_picRatePresentFlag[i][j];                         }
+
+  Void    setAvgBitRate( Int i, Int j, Int  val )                                    { m_avgBitRate[i][j] = val;                                  }
+  Int     getAvgBitRate( Int i, Int j ) const                                        { return m_avgBitRate[i][j];                                 }
+
+  Void    setMaxBitRate( Int i, Int j, Int  val )                                    { m_maxBitRate[i][j] = val;                                  }
+  Int     getMaxBitRate( Int i, Int j ) const                                        { return m_maxBitRate[i][j];                                 }
+
+  Void    setConstantPicRateIdc( Int i, Int j, Int  val )                            { m_constantPicRateIdc[i][j] = val;                          }
+  Int     getConstantPicRateIdc( Int i, Int j ) const                                { return m_constantPicRateIdc[i][j];                         }
+
+  Void    setAvgPicRate( Int i, Int j, Int  val )                                    { m_avgPicRate[i][j] = val;                                  }
+  Int     getAvgPicRate( Int i, Int j ) const                                        { return m_avgPicRate[i][j];                                 }
+
+  Void    setVideoSignalInfoIdxPresentFlag( Bool flag )                              { m_videoSignalInfoIdxPresentFlag = flag;                    }
+  Bool    getVideoSignalInfoIdxPresentFlag(  ) const                                 { return m_videoSignalInfoIdxPresentFlag;                    }
+
+  Void    setVideoSignalInfo( std::vector<TComVideoSignalInfo> val )                  { m_videoSignalInfo = val;                                  }
+  const   TComVideoSignalInfo* getVideoSignalInfo( Int i ) const                      { return &m_videoSignalInfo[i];                             }
+
+  Void    setVpsNumVideoSignalInfoMinus1( Int  val )                                 { m_vpsNumVideoSignalInfoMinus1 = val;                       }
+  Int     getVpsNumVideoSignalInfoMinus1(  ) const                                   { return m_vpsNumVideoSignalInfoMinus1;                      }
+
+  Void    setVpsVideoSignalInfoIdx( Int i, Int  val )                                { m_vpsVideoSignalInfoIdx[i] = val;                          }
+  Int     getVpsVideoSignalInfoIdx( Int i ) const                                    { return m_vpsVideoSignalInfoIdx[i];                         }
+
+  Void    setTilesNotInUseFlag( Bool flag )                                          { m_tilesNotInUseFlag = flag;                                }
+  Bool    getTilesNotInUseFlag(  ) const                                             { return m_tilesNotInUseFlag;                                }
+
+  Void    setTilesInUseFlag( Int i, Bool flag )                                      { m_tilesInUseFlag[i] = flag;                                }
+  Bool    getTilesInUseFlag( Int i ) const                                           { return m_tilesInUseFlag[i];                                }
+
+  Void    setLoopFilterNotAcrossTilesFlag( Int i, Int  val )                         { m_loopFilterNotAcrossTilesFlag[i] = val;                   }
+  Bool    getLoopFilterNotAcrossTilesFlag( Int i ) const                             { return m_loopFilterNotAcrossTilesFlag[i];                  }
+
+  Void    setTileBoundariesAlignedFlag( Int i, Int j, Bool flag )                    { m_tileBoundariesAlignedFlag[i][j] = flag;                  }
+  Bool    getTileBoundariesAlignedFlag( Int i, Int j ) const                         { return m_tileBoundariesAlignedFlag[i][j];                  }
+
+  Void    setWppNotInUseFlag( Bool flag )                                            { m_wppNotInUseFlag = flag;                                  }
+  Bool    getWppNotInUseFlag(  ) const                                               { return m_wppNotInUseFlag;                                  }
+
+  Void    setWppInUseFlag( Int i, Bool flag )                                        { m_wppInUseFlag[i] = flag;                                  }
+  Bool    getWppInUseFlag( Int i ) const                                             { return m_wppInUseFlag[i];                                  }
+
+  Void    setSingleLayerForNonIrapFlag( Bool flag )                                  { m_singleLayerForNonIrapFlag = flag;                        }
+  Bool    getSingleLayerForNonIrapFlag(  ) const                                     { return m_singleLayerForNonIrapFlag;                        }
+
+  Void    setHigherLayerIrapSkipFlag( Bool flag )                                    { m_higherLayerIrapSkipFlag = flag;                          }
+  Bool    getHigherLayerIrapSkipFlag(  ) const                                       { return m_higherLayerIrapSkipFlag;                          }
+
+  Void    setIlpRestrictedRefLayersFlag( Bool flag )                                 { m_ilpRestrictedRefLayersFlag = flag;                       }
+  Bool    getIlpRestrictedRefLayersFlag(  ) const                                    { return m_ilpRestrictedRefLayersFlag;                       }
+
+  Void    setMinSpatialSegmentOffsetPlus1( Int i, Int j, Int  val )                  { m_minSpatialSegmentOffsetPlus1[i][j] = val;                }
+  Int     getMinSpatialSegmentOffsetPlus1( Int i, Int j ) const                      { return m_minSpatialSegmentOffsetPlus1[i][j];               }
+
+  Void    setCtuBasedOffsetEnabledFlag( Int i, Int j, Bool flag )                    { m_ctuBasedOffsetEnabledFlag[i][j] = flag;                  }
+  Bool    getCtuBasedOffsetEnabledFlag( Int i, Int j ) const                         { return m_ctuBasedOffsetEnabledFlag[i][j];                  }
+
+  Void    setMinHorizontalCtuOffsetPlus1( Int i, Int j, Int  val )                   { m_minHorizontalCtuOffsetPlus1[i][j] = val;                 }
+  Int     getMinHorizontalCtuOffsetPlus1( Int i, Int j ) const                       { return m_minHorizontalCtuOffsetPlus1[i][j];                }
+
+  Void    setVpsVuiBspHrdPresentFlag( Bool flag )                                    { m_vpsVuiBspHrdPresentFlag = flag;                          }
+  Bool    getVpsVuiBspHrdPresentFlag(  ) const                                       { return m_vpsVuiBspHrdPresentFlag;                          }
+
+  Void    setVpsVuiBspHrdParameters( TComVpsVuiBspHrdParameters val)                 {  m_vpsVuiBspHrdParameters = val;                           }
+  const   TComVpsVuiBspHrdParameters* getVpsVuiBspHrdParameters(  ) const            { return &m_vpsVuiBspHrdParameters;                          }
+
+  Void    setBaseLayerParameterSetCompatibilityFlag( Int i, Bool flag )              { m_baseLayerParameterSetCompatibilityFlag[i] = flag;        }
+  Bool    getBaseLayerParameterSetCompatibilityFlag( Int i ) const                   { return m_baseLayerParameterSetCompatibilityFlag[i];        }
 };
 
@@ -702,48 +728,50 @@
   TComRepFormat()
   { 
-  m_conformanceWindowVpsFlag = 0;
-  m_confWinVpsLeftOffset     = 0;
-  m_confWinVpsRightOffset    = 0;
-  m_confWinVpsTopOffset      = 0;
-  m_confWinVpsBottomOffset   = 0;
+    m_conformanceWindowVpsFlag = 0;
+    m_confWinVpsLeftOffset     = 0;
+    m_confWinVpsRightOffset    = 0;
+    m_confWinVpsTopOffset      = 0;
+    m_confWinVpsBottomOffset   = 0;
   };  
 
-  Void setChromaAndBitDepthVpsPresentFlag( Bool flag ) { m_chromaAndBitDepthVpsPresentFlag = flag; } 
-  Bool getChromaAndBitDepthVpsPresentFlag(  ) { return m_chromaAndBitDepthVpsPresentFlag; } 
-  Void checkChromaAndBitDepthVpsPresentFlag( Int i ) { assert( i != 0 || m_chromaAndBitDepthVpsPresentFlag ); } // The value of chroma_and_bit_depth_vps_present_flag of the first rep_format( ) syntax structure in the VPS shall be equal to 1.  
-  Void inferChromaAndBitDepth( TComRepFormat* prevRepFormat, Bool encoderFlag );
-
-  Void setChromaFormatVpsIdc( Int  val ) { m_chromaFormatVpsIdc = val; } 
-  Int  getChromaFormatVpsIdc(  ) { return m_chromaFormatVpsIdc; } 
-
-  Void setSeparateColourPlaneVpsFlag( Bool flag ) { m_separateColourPlaneVpsFlag = flag; } 
-  Bool getSeparateColourPlaneVpsFlag(  ) { return m_separateColourPlaneVpsFlag; } 
-
-  Void setPicWidthVpsInLumaSamples( Int  val ) { m_picWidthVpsInLumaSamples = val; } 
-  Int  getPicWidthVpsInLumaSamples(  ) { return m_picWidthVpsInLumaSamples; } 
-
-  Void setPicHeightVpsInLumaSamples( Int  val ) { m_picHeightVpsInLumaSamples = val; } 
-  Int  getPicHeightVpsInLumaSamples(  ) { return m_picHeightVpsInLumaSamples; } 
-
-  Void setBitDepthVpsLumaMinus8( Int  val ) { m_bitDepthVpsLumaMinus8 = val; } 
-  Int  getBitDepthVpsLumaMinus8(  ) { return m_bitDepthVpsLumaMinus8; } 
-
-  Void setBitDepthVpsChromaMinus8( Int  val ) { m_bitDepthVpsChromaMinus8 = val; } 
-  Int  getBitDepthVpsChromaMinus8(  ) { return m_bitDepthVpsChromaMinus8; } 
-
-  Void setConformanceWindowVpsFlag( Bool flag ) { m_conformanceWindowVpsFlag = flag; } 
-  Bool getConformanceWindowVpsFlag(  ) { return m_conformanceWindowVpsFlag; } 
-
-  Void setConfWinVpsLeftOffset( Int  val ) { m_confWinVpsLeftOffset = val; } 
-  Int  getConfWinVpsLeftOffset(  ) { return m_confWinVpsLeftOffset; } 
-
-  Void setConfWinVpsRightOffset( Int  val ) { m_confWinVpsRightOffset = val; } 
-  Int  getConfWinVpsRightOffset(  ) { return m_confWinVpsRightOffset; } 
-
-  Void setConfWinVpsTopOffset( Int  val ) { m_confWinVpsTopOffset = val; } 
-  Int  getConfWinVpsTopOffset(  ) { return m_confWinVpsTopOffset; } 
-
-  Void setConfWinVpsBottomOffset( Int  val ) { m_confWinVpsBottomOffset = val; } 
-  Int  getConfWinVpsBottomOffset(  ) { return m_confWinVpsBottomOffset; } 
+  Void    setChromaAndBitDepthVpsPresentFlag( Bool flag )                            { m_chromaAndBitDepthVpsPresentFlag = flag;                  }
+  Bool    getChromaAndBitDepthVpsPresentFlag(  ) const                               { return m_chromaAndBitDepthVpsPresentFlag;                  }
+  Void    checkChromaAndBitDepthVpsPresentFlag( Int i ) const                        { assert( i != 0 || m_chromaAndBitDepthVpsPresentFlag );     } // The value of chroma_and_bit_depth_vps_present_flag of the first rep_format( ) syntax structure in the VPS shall be equal to 1.
+
+  Void    inferChromaAndBitDepth     ( const TComRepFormat* prevRepFormat );
+  Void    checkInferChromaAndBitDepth( const TComRepFormat* prevRepFormat ) const;
+
+  Void    setChromaFormatVpsIdc( Int  val )                                          { m_chromaFormatVpsIdc = val;                                }
+  Int     getChromaFormatVpsIdc(  ) const                                            { return m_chromaFormatVpsIdc;                               }
+
+  Void    setSeparateColourPlaneVpsFlag( Bool flag )                                 { m_separateColourPlaneVpsFlag = flag;                       }
+  Bool    getSeparateColourPlaneVpsFlag(  ) const                                    { return m_separateColourPlaneVpsFlag;                       }
+
+  Void    setPicWidthVpsInLumaSamples( Int  val )                                    { m_picWidthVpsInLumaSamples = val;                          }
+  Int     getPicWidthVpsInLumaSamples(  ) const                                      { return m_picWidthVpsInLumaSamples;                         }
+
+  Void    setPicHeightVpsInLumaSamples( Int  val )                                   { m_picHeightVpsInLumaSamples = val;                         }
+  Int     getPicHeightVpsInLumaSamples(  ) const                                     { return m_picHeightVpsInLumaSamples;                        }
+
+  Void    setBitDepthVpsLumaMinus8( Int  val )                                       { m_bitDepthVpsLumaMinus8 = val;                             }
+  Int     getBitDepthVpsLumaMinus8(  ) const                                         { return m_bitDepthVpsLumaMinus8;                            }
+
+  Void    setBitDepthVpsChromaMinus8( Int  val )                                     { m_bitDepthVpsChromaMinus8 = val;                           }
+  Int     getBitDepthVpsChromaMinus8(  ) const                                       { return m_bitDepthVpsChromaMinus8;                          }
+
+  Void    setConformanceWindowVpsFlag( Bool flag )                                   { m_conformanceWindowVpsFlag = flag;                         }
+  Bool    getConformanceWindowVpsFlag(  ) const                                      { return m_conformanceWindowVpsFlag;                         }
+
+  Void    setConfWinVpsLeftOffset( Int  val )                                        { m_confWinVpsLeftOffset = val;                              }
+  Int     getConfWinVpsLeftOffset(  ) const                                          { return m_confWinVpsLeftOffset;                             }
+
+  Void    setConfWinVpsRightOffset( Int  val )                                       { m_confWinVpsRightOffset = val;                             }
+  Int     getConfWinVpsRightOffset(  ) const                                         { return m_confWinVpsRightOffset;                            }
+
+  Void    setConfWinVpsTopOffset( Int  val )                                         { m_confWinVpsTopOffset = val;                               }
+  Int     getConfWinVpsTopOffset(  ) const                                           { return m_confWinVpsTopOffset;                              }
+
+  Void    setConfWinVpsBottomOffset( Int  val )                                      { m_confWinVpsBottomOffset = val;                            }
+  Int     getConfWinVpsBottomOffset(  ) const                                        { return m_confWinVpsBottomOffset;                           }
 };
 
@@ -752,76 +780,79 @@
 {
 private:
-  Bool  m_subLayerFlagInfoPresentFlag[MAX_VPS_OUTPUTLAYER_SETS];
-  Bool  m_subLayerDpbInfoPresentFlag [MAX_VPS_OUTPUTLAYER_SETS][MAX_TLAYER];
-  Int   m_maxVpsDecPicBufferingMinus1[MAX_VPS_OUTPUTLAYER_SETS][MAX_NUM_LAYER_IDS][MAX_TLAYER];; 
-  Int   m_maxVpsNumReorderPics       [MAX_VPS_OUTPUTLAYER_SETS][MAX_TLAYER];
-  Int   m_maxVpsLatencyIncreasePlus1 [MAX_VPS_OUTPUTLAYER_SETS][MAX_TLAYER];
+  BoolAry1d  m_subLayerFlagInfoPresentFlag;
+  BoolAry2d  m_subLayerDpbInfoPresentFlag ;
+  IntAry3d   m_maxVpsDecPicBufferingMinus1;
+  IntAry2d   m_maxVpsNumReorderPics       ;
+  IntAry2d   m_maxVpsLatencyIncreasePlus1 ;
 
 public: 
-  TComDpbSize( );  
-
-  Void setSubLayerFlagInfoPresentFlag( Int i, Bool flag ) { m_subLayerFlagInfoPresentFlag[i] = flag; } 
-  Bool getSubLayerFlagInfoPresentFlag( Int i ) { return m_subLayerFlagInfoPresentFlag[i]; } 
-
-  Void setSubLayerDpbInfoPresentFlag( Int i, Int j, Bool flag ) { m_subLayerDpbInfoPresentFlag[i][j] = flag; } 
-  Bool getSubLayerDpbInfoPresentFlag( Int i, Int j ) { return m_subLayerDpbInfoPresentFlag[i][j]; } 
-
-  Void setMaxVpsDecPicBufferingMinus1( Int i, Int k, Int j, Int  val ) { m_maxVpsDecPicBufferingMinus1[i][k][j] = val; } 
-  Int  getMaxVpsDecPicBufferingMinus1( Int i, Int k, Int j ) { assert( m_maxVpsDecPicBufferingMinus1[i][k][j] >= 0 ); return m_maxVpsDecPicBufferingMinus1[i][k][j]; }     
-
-  Void setMaxVpsNumReorderPics( Int i, Int j, Int  val ) { m_maxVpsNumReorderPics[i][j] = val; } 
-  Int  getMaxVpsNumReorderPics( Int i, Int j ) { return m_maxVpsNumReorderPics[i][j]; } 
-
-  Void setMaxVpsLatencyIncreasePlus1( Int i, Int j, Int  val ) { m_maxVpsLatencyIncreasePlus1[i][j] = val; } 
-  Int  getMaxVpsLatencyIncreasePlus1( Int i, Int j ) { return m_maxVpsLatencyIncreasePlus1[i][j]; } 
+  TComDpbSize() {}; 
+
+  Void          init( Int numOutputLayerSets, Int maxNumLayerIds, Int maxNumSubLayers );
+
+  Void          setSubLayerFlagInfoPresentFlag( Int i, Bool flag )                   { m_subLayerFlagInfoPresentFlag[i] = flag;                   }
+  Bool          getSubLayerFlagInfoPresentFlag( Int i ) const                        { return m_subLayerFlagInfoPresentFlag[i];                   }
+
+  Void          setSubLayerDpbInfoPresentFlag( Int i, Int j, Bool flag )             { m_subLayerDpbInfoPresentFlag[i][j] = flag;                 }
+  Bool          getSubLayerDpbInfoPresentFlag( Int i, Int j ) const                  { return m_subLayerDpbInfoPresentFlag[i][j];                 }
+
+  Void          setMaxVpsDecPicBufferingMinus1( Int i, Int k, Int j, Int  val )      { m_maxVpsDecPicBufferingMinus1[i][k][j] = val;              }
+  Int           getMaxVpsDecPicBufferingMinus1( Int i, Int k, Int j ) const          { assert( m_maxVpsDecPicBufferingMinus1[i][k][j] >= 0 ); return m_maxVpsDecPicBufferingMinus1[i][k][j]; }
+
+  Void          setMaxVpsNumReorderPics( Int i, Int j, Int  val )                    { m_maxVpsNumReorderPics[i][j] = val;                        }
+  Int           getMaxVpsNumReorderPics( Int i, Int j ) const                        { return m_maxVpsNumReorderPics[i][j];                       }
+
+  Void          setMaxVpsLatencyIncreasePlus1( Int i, Int j, Int  val )              { m_maxVpsLatencyIncreasePlus1[i][j] = val;                  }
+  Int           getMaxVpsLatencyIncreasePlus1( Int i, Int j ) const                  { return m_maxVpsLatencyIncreasePlus1[i][j];                 }
 };
 #endif
+
 class TComVPS
 {
 private:
-  Int         m_VPSId;
-#if H_MV
-  Bool        m_vpsBaseLayerInternalFlag;
-  Bool        m_vpsBaseLayerAvailableFlag;
-#endif
-
-  UInt        m_uiMaxTLayers;
-
-#if H_MV
-  UInt        m_uiMaxLayersMinus1;
+  Int                   m_VPSId;
+#if NH_MV
+  Bool                  m_vpsBaseLayerInternalFlag;
+  Bool                  m_vpsBaseLayerAvailableFlag;
+#endif
+
+  UInt                  m_uiMaxTLayers;
+
+#if NH_MV
+  UInt                  m_uiMaxLayersMinus1;
 #else
-  UInt        m_uiMaxLayers;
-#endif
-  Bool        m_bTemporalIdNestingFlag;
-  
-  UInt        m_numReorderPics[MAX_TLAYER];
-  UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
-  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER]; // Really max latency increase plus 1 (value 0 expresses no limit)
-
-  UInt        m_numHrdParameters;
-#if H_MV
-  UInt        m_maxLayerId;
+  UInt                  m_uiMaxLayers;
+#endif
+  Bool                  m_bTemporalIdNestingFlag;
+
+  UInt                  m_numReorderPics[MAX_TLAYER];
+  UInt                  m_uiMaxDecPicBuffering[MAX_TLAYER];
+  UInt                  m_uiMaxLatencyIncrease[MAX_TLAYER]; // Really max latency increase plus 1 (value 0 expresses no limit)
+
+  UInt                  m_numHrdParameters;
+#if NH_MV
+  UInt                  m_maxLayerId;
 #else
-  UInt        m_maxNuhReservedZeroLayerId;
-#endif
-  TComHRD*    m_hrdParameters;
-  UInt*       m_hrdOpSetIdx;
-  Bool*       m_cprmsPresentFlag;
-#if H_MV
-  UInt        m_vpsNumLayerSetsMinus1;
-  Bool        m_layerIdIncludedFlag[MAX_VPS_OP_SETS_PLUS1][MAX_VPS_NUH_LAYER_ID_PLUS1];
+  UInt                  m_maxNuhReservedZeroLayerId;
+#endif
+  std::vector<TComHRD>  m_hrdParameters;
+  std::vector<UInt>     m_hrdOpSetIdx;
+  std::vector<Bool>     m_cprmsPresentFlag;
+#if NH_MV
+  UInt                  m_vpsNumLayerSetsMinus1;
+  Bool                  m_layerIdIncludedFlag[MAX_VPS_OP_SETS_PLUS1][MAX_VPS_NUH_LAYER_ID_PLUS1];
 #else
-  UInt        m_numOpSets;
-  Bool        m_layerIdIncludedFlag[MAX_VPS_OP_SETS_PLUS1][MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1];
-#endif
-
-#if H_MV
-  TComPTL     m_pcPTL[MAX_VPS_OP_SETS_PLUS1];
+  UInt                  m_numOpSets;
+  Bool                  m_layerIdIncludedFlag[MAX_VPS_OP_SETS_PLUS1][MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1];
+#endif
+
+#if NH_MV
+  TComPTL               m_pcPTL[MAX_VPS_OP_SETS_PLUS1];
 #else
-  TComPTL     m_pcPTL;
-#endif
-  TimingInfo  m_timingInfo;
-#if H_MV
-  Bool        m_vpsExtensionFlag;
+  TComPTL               m_pcPTL;
+#endif
+  TimingInfo            m_timingInfo;
+#if NH_MV
+  Bool                  m_vpsExtensionFlag;
 
   /// VPS EXTENSION SYNTAX ELEMENTS
@@ -859,10 +890,11 @@
   Int         m_vpsNumRepFormatsMinus1;
   Int         m_vpsRepFormatIdx          [MAX_NUM_LAYERS];
-  TComRepFormat* m_repFormat             [MAX_NUM_LAYERS]; 
+
+  std::vector<TComRepFormat> m_repFormat; 
   Bool        m_maxOneActiveRefLayerFlag;       
   Bool        m_vpsPocLsbAlignedFlag;
   Bool        m_pocLsbNotPresentFlag     [MAX_NUM_LAYERS];
 
-  TComDpbSize* m_dpbSize; 
+  TComDpbSize m_dpbSize; 
   Int         m_directDepTypeLenMinus2;         
   Bool        m_defaultDirectDependencyFlag;
@@ -873,5 +905,5 @@
 #endif
   Bool        m_vpsVuiPresentFlag;
-  TComVPSVUI* m_vpsVUI; 
+  TComVPSVUI  m_vpsVUI; 
 #if !H_MV_HLS7_GEN
   Int         m_directDependencyType     [MAX_NUM_LAYERS] [MAX_NUM_LAYERS];
@@ -885,5 +917,5 @@
   Int         m_numDirectRefLayers       [MAX_NUM_LAYERS];
   Int         m_idDirectRefLayer         [MAX_NUM_LAYERS][MAX_NUM_LAYERS];  
-#if H_3D
+#if NH_3D
   Int         m_numRefListLayers         [MAX_NUM_LAYERS];
   Int         m_idRefListLayer           [MAX_NUM_LAYERS][MAX_NUM_LAYERS];  
@@ -903,334 +935,383 @@
   Int         m_viewIndex                [MAX_NUM_LAYERS   ];
   
-  std::vector< std::vector< Int> >       m_targetDecLayerIdLists;   //[TargetOptLayerSetIdx][i]
-  std::vector< std::vector< Int> >       m_targetOptLayerIdLists; 
-  std::vector< std::vector< Int> >       m_layerSetLayerIdList; 
-
-  Int        m_numNecessaryLayers        [MAX_VPS_OUTPUTLAYER_SETS];
-  Bool       m_necessaryLayerFlag        [MAX_VPS_OUTPUTLAYER_SETS][MAX_NUM_LAYERS]; 
-
-  Int         xGetDimBitOffset( Int j );
+  IntAry2d    m_targetDecLayerIdLists;   //[TargetOptLayerSetIdx][i]
+  IntAry2d    m_targetOptLayerIdLists; 
+  IntAry2d    m_layerSetLayerIdList; 
+
+  Int         m_numNecessaryLayers        [MAX_VPS_OUTPUTLAYER_SETS];
+  Bool        m_necessaryLayerFlag        [MAX_VPS_OUTPUTLAYER_SETS][MAX_NUM_LAYERS]; 
+
+  Int         xGetDimBitOffset( Int j ) const;
   Void        xSetRefLayerFlags( Int currLayerId );
 
   // VPS EXTENSION 2 SYNTAX ELEMENTS
-#if H_3D
-  Int*        m_numCp;  
-  Int**       m_cpRefVoi;
-  Bool**      m_cpPresentFlag; 
-  Int         m_cpPrecision;
-  Bool*       m_cpInSliceSegmentHeaderFlag;
-  Int         ***m_aaaiCodedScale ;
-  Int         ***m_aaaiCodedOffset;
-
-  std::vector<Int>  m_viewOIdxList;
-  std::vector< std::vector<Bool> > m_viewCompLayerPresentFlag;
-  std::vector< std::vector<Int>  > m_viewCompLayerId;
-#endif
-
-#endif
+#if NH_3D
+  IntAry1d       m_numCp;  
+  IntAry2d       m_cpRefVoi;
+  BoolAry2d      m_cpPresentFlag; 
+  Int            m_cpPrecision;
+  BoolAry1d      m_cpInSliceSegmentHeaderFlag;
+  IntAry3d       m_aaaiCodedScale ;
+  IntAry3d       m_aaaiCodedOffset;
+
+  IntAry1d       m_viewOIdxList;
+  BoolAry2d      m_viewCompLayerPresentFlag;
+  IntAry2d       m_viewCompLayerId;
+#endif
+
+#endif
+
 public:
-  TComVPS();
-  virtual ~TComVPS();
-
-  Void    createHrdParamBuffer()
+                    TComVPS();
+
+  virtual           ~TComVPS();
+
+  Void              createHrdParamBuffer()
   {
-    m_hrdParameters    = new TComHRD[ getNumHrdParameters() ];
-    m_hrdOpSetIdx      = new UInt   [ getNumHrdParameters() ];
-    m_cprmsPresentFlag = new Bool   [ getNumHrdParameters() ];
+    m_hrdParameters.resize(getNumHrdParameters());
+    m_hrdOpSetIdx.resize(getNumHrdParameters());
+    m_cprmsPresentFlag.resize(getNumHrdParameters());
   }
 
-  TComHRD* getHrdParameters   ( UInt i )             { return &m_hrdParameters[ i ]; }
-  UInt    getHrdOpSetIdx      ( UInt i )             { return m_hrdOpSetIdx[ i ]; }
-  Void    setHrdOpSetIdx      ( UInt val, UInt i )   { m_hrdOpSetIdx[ i ] = val;  }
-  Bool    getCprmsPresentFlag ( UInt i )             { return m_cprmsPresentFlag[ i ]; }
-  Void    setCprmsPresentFlag ( Bool val, UInt i )   { m_cprmsPresentFlag[ i ] = val;  }
-
-  Int     getVPSId       ()                   { return m_VPSId;          }
-  Void    setVPSId       (Int i)              { m_VPSId = i;             }
-
-#if H_MV
-  Void    setVpsBaseLayerInternalFlag( Bool flag ) { m_vpsBaseLayerInternalFlag = flag; } 
-  Bool    getVpsBaseLayerInternalFlag(  )          { return m_vpsBaseLayerInternalFlag; } 
-  Void    setVpsBaseLayerAvailableFlag( Bool flag ) { m_vpsBaseLayerAvailableFlag = flag; } 
-  Bool    getVpsBaseLayerAvailableFlag(  )          { return m_vpsBaseLayerAvailableFlag; } 
-#endif
-
-  UInt    getMaxTLayers  ()                   { return m_uiMaxTLayers;   }
-  Void    setMaxTLayers  (UInt t)             { m_uiMaxTLayers = t; }
-
-#if H_MV    
-  UInt    getMaxSubLayersMinus1()             { return m_uiMaxTLayers - 1;  }  // For consistency with draft spec
-  Void    setMaxSubLayersMinus1(UInt val)     { m_uiMaxTLayers = (val + 1); };
-  UInt    getMaxLayersMinus1()                { return m_uiMaxLayersMinus1;  }; 
-  Void    setMaxLayersMinus1(UInt l)          { m_uiMaxLayersMinus1 = l; }
+  TComHRD*          getHrdParameters( UInt i )                           { return &m_hrdParameters[ i ];                                    }
+  const TComHRD*    getHrdParameters( UInt i ) const                     { return &m_hrdParameters[ i ];                                    }
+  UInt              getHrdOpSetIdx( UInt i ) const                       { return m_hrdOpSetIdx[ i ];                                       }
+  Void              setHrdOpSetIdx( UInt val, UInt i )                   { m_hrdOpSetIdx[ i ] = val;                                        }
+  Bool              getCprmsPresentFlag( UInt i ) const                  { return m_cprmsPresentFlag[ i ];                                  }
+  Void              setCprmsPresentFlag( Bool val, UInt i )              { m_cprmsPresentFlag[ i ] = val;                                   }
+
+  Int               getVPSId() const                                     { return m_VPSId;                                                  }
+  Void              setVPSId(Int i)                                      { m_VPSId = i;                                                     }
+#if NH_MV
+  Void              setVpsBaseLayerInternalFlag( Bool flag )             { m_vpsBaseLayerInternalFlag = flag;                               } 
+  Bool              getVpsBaseLayerInternalFlag(  )           const      { return m_vpsBaseLayerInternalFlag;                               } 
+  Void              setVpsBaseLayerAvailableFlag( Bool flag )            { m_vpsBaseLayerAvailableFlag = flag;                              } 
+  Bool              getVpsBaseLayerAvailableFlag(  )          const      { return m_vpsBaseLayerAvailableFlag;                              } 
+#endif
+
+  UInt              getMaxTLayers() const                                { return m_uiMaxTLayers;                                           }
+  Void              setMaxTLayers(UInt t)                                { m_uiMaxTLayers = t;                                              }
+#if NH_MV    
+  UInt              getMaxSubLayersMinus1()            const             { return m_uiMaxTLayers - 1;   }  // For consistency with draft spec
+  Void              setMaxSubLayersMinus1(UInt val)                      { m_uiMaxTLayers = (val + 1);  }
+  UInt              getMaxLayersMinus1()               const             { return m_uiMaxLayersMinus1;  } 
+  Void              setMaxLayersMinus1(UInt l)                           { m_uiMaxLayersMinus1 = l;     }
 #else
-  UInt    getMaxLayers   ()                   { return m_uiMaxLayers;   }
-  Void    setMaxLayers   (UInt l)             { m_uiMaxLayers = l; }
-#endif
-
-  Bool    getTemporalNestingFlag   ()         { return m_bTemporalIdNestingFlag;   }
-  Void    setTemporalNestingFlag   (Bool t)   { m_bTemporalIdNestingFlag = t; }
-  
-  Void    setNumReorderPics(UInt v, UInt tLayer)                { m_numReorderPics[tLayer] = v;    }
-  UInt    getNumReorderPics(UInt tLayer)                        { return m_numReorderPics[tLayer]; }
-  
-  Void    setMaxDecPicBuffering(UInt v, UInt tLayer)            { assert(tLayer < MAX_TLAYER); m_uiMaxDecPicBuffering[tLayer] = v;    }
-  UInt    getMaxDecPicBuffering(UInt tLayer)                    { return m_uiMaxDecPicBuffering[tLayer]; }
-  
-  Void    setMaxLatencyIncrease(UInt v, UInt tLayer)            { m_uiMaxLatencyIncrease[tLayer] = v;    }
-  UInt    getMaxLatencyIncrease(UInt tLayer)                    { return m_uiMaxLatencyIncrease[tLayer]; }
-
-  UInt    getNumHrdParameters()                                 { return m_numHrdParameters; }
-  Void    setNumHrdParameters(UInt v)                           { m_numHrdParameters = v;    }
-
-#if H_MV
-  UInt    getVpsMaxLayerId()                                    { return m_maxLayerId; }
-  Void    setVpsMaxLayerId(UInt v)                              { m_maxLayerId = v;    }
-
-  UInt    getVpsNumLayerSetsMinus1()                            { return m_vpsNumLayerSetsMinus1; }
-  Void    setVpsNumLayerSetsMinus1(UInt v)                      { m_vpsNumLayerSetsMinus1 = v;    }
+
+  UInt              getMaxLayers() const                                 { return m_uiMaxLayers;                                            }
+  Void              setMaxLayers(UInt l)                                 { m_uiMaxLayers = l;                                               }
+#endif
+
+  Bool              getTemporalNestingFlag() const                       { return m_bTemporalIdNestingFlag;                                 }
+  Void              setTemporalNestingFlag(Bool t)                       { m_bTemporalIdNestingFlag = t;                                    }
+
+  Void              setNumReorderPics(UInt v, UInt tLayer)               { m_numReorderPics[tLayer] = v;                                    }
+  UInt              getNumReorderPics(UInt tLayer) const                 { return m_numReorderPics[tLayer];                                 }
+
+  Void              setMaxDecPicBuffering(UInt v, UInt tLayer)           { assert(tLayer < MAX_TLAYER); m_uiMaxDecPicBuffering[tLayer] = v; }
+  UInt              getMaxDecPicBuffering(UInt tLayer) const             { return m_uiMaxDecPicBuffering[tLayer];                           }
+
+  Void              setMaxLatencyIncrease(UInt v, UInt tLayer)           { m_uiMaxLatencyIncrease[tLayer] = v;                              }
+  UInt              getMaxLatencyIncrease(UInt tLayer) const             { return m_uiMaxLatencyIncrease[tLayer];                           }
+
+  UInt              getNumHrdParameters() const                          { return m_numHrdParameters;                                       }
+  Void              setNumHrdParameters(UInt v)                          { m_numHrdParameters = v;                                          }
+#if NH_MV
+  UInt              getVpsMaxLayerId()                           const   { return m_maxLayerId; }
+  Void              setVpsMaxLayerId(UInt v)                             { m_maxLayerId = v;    }
+                    
+  UInt              getVpsNumLayerSetsMinus1()                   const   { return m_vpsNumLayerSetsMinus1; }
+  Void              setVpsNumLayerSetsMinus1(UInt v)                     { m_vpsNumLayerSetsMinus1 = v;    }
+#else  
+  UInt              getMaxNuhReservedZeroLayerId() const                 { return m_maxNuhReservedZeroLayerId;                              }
+  Void              setMaxNuhReservedZeroLayerId(UInt v)                 { m_maxNuhReservedZeroLayerId = v;                                 }
+
+  UInt              getMaxOpSets() const                                 { return m_numOpSets;                                              }
+  Void              setMaxOpSets(UInt v)                                 { m_numOpSets = v;                                                 }
+#endif
+  Bool              getLayerIdIncludedFlag(UInt opsIdx, UInt id) const   { return m_layerIdIncludedFlag[opsIdx][id];                        }
+  Void              setLayerIdIncludedFlag(Bool v, UInt opsIdx, UInt id) { m_layerIdIncludedFlag[opsIdx][id] = v;                           }
+
+#if NH_MV
+  TComPTL*          getPTL( Int idx = 0 )                                { return &m_pcPTL[idx];                                            }
+  const TComPTL*    getPTL( Int idx = 0 ) const                          { return &m_pcPTL[idx];                                            }
 #else
-  UInt    getMaxNuhReservedZeroLayerId()                        { return m_maxNuhReservedZeroLayerId; }
-  Void    setMaxNuhReservedZeroLayerId(UInt v)                  { m_maxNuhReservedZeroLayerId = v;    }
-
-  UInt    getMaxOpSets()                                        { return m_numOpSets; }
-  Void    setMaxOpSets(UInt v)                                  { m_numOpSets = v;    }
-#endif
-  Bool    getLayerIdIncludedFlag(UInt opsIdx, UInt id)          { return m_layerIdIncludedFlag[opsIdx][id]; }
-  Void    setLayerIdIncludedFlag(Bool v, UInt opsIdx, UInt id)  { m_layerIdIncludedFlag[opsIdx][id] = v;    }
-
-#if H_MV
-  TComPTL* getPTL( Int idx = 0 ) { return &m_pcPTL[idx]; }
-#else
-  TComPTL* getPTL() { return &m_pcPTL; }
-#endif
-  TimingInfo* getTimingInfo() { return &m_timingInfo; }
-#if H_MV
-  Void    setVpsExtensionFlag( Bool flag )                                 { m_vpsExtensionFlag = flag; } 
-  Bool    getVpsExtensionFlag(  )                                          { return m_vpsExtensionFlag; } 
-
-  Void    setVpsNonVuiExtensionLength( Int  val )                          { m_vpsNonVuiExtensionLength = val; } 
-  Int     getVpsNonVuiExtensionLength(  )                                  { return m_vpsNonVuiExtensionLength; } 
+  TComPTL*          getPTL()                                             { return &m_pcPTL;                                                 }
+  const TComPTL*    getPTL() const                                       { return &m_pcPTL;                                                 }
+#endif
+  TimingInfo*       getTimingInfo()                                      { return &m_timingInfo;                                            }
+  const TimingInfo* getTimingInfo() const                                { return &m_timingInfo;                                            }
+
+#if NH_MV
+  Void    setVpsExtensionFlag( Bool flag )                                      { m_vpsExtensionFlag = flag; } 
+  Bool    getVpsExtensionFlag(  )                                   const       { return m_vpsExtensionFlag; } 
+
+  Void    setVpsNonVuiExtensionLength( Int  val )                               { m_vpsNonVuiExtensionLength = val; } 
+  Int     getVpsNonVuiExtensionLength(  )                           const       { return m_vpsNonVuiExtensionLength; } 
   
   // VPS Extension
-  Void    setSplittingFlag( Bool val )                                     { m_splittingFlag = val;  }
-  Bool    getSplittingFlag()                                               { return m_splittingFlag; }
+  Void    setSplittingFlag( Bool val )                                          { m_splittingFlag = val;  }
+  Bool    getSplittingFlag()                                        const       { return m_splittingFlag; }
 
   Void    setScalabilityMaskFlag( UInt val );
-  Void    setScalabilityMaskFlag( Int scalType, Bool val )                     { m_scalabilityMaskFlag[scalType] = val;  }
-  Bool    getScalabilityMaskFlag( Int scalType )                               { return m_scalabilityMaskFlag[scalType]; }
+  Void    setScalabilityMaskFlag( Int scalType, Bool val )                          { m_scalabilityMaskFlag[scalType] = val;  }
+  Bool    getScalabilityMaskFlag( Int scalType )                    const           { return m_scalabilityMaskFlag[scalType]; }
   
-  Int     getNumScalabilityTypes( );
-
-  Void    setDimensionIdLen( Int sIdx, Int val )                           { m_dimensionIdLen[sIdx] = val;  }
-  Int     getDimensionIdLen( Int sIdx )                                    { assert( m_dimensionIdLen[sIdx] > 0) ; return m_dimensionIdLen[sIdx]; }  
-
-  Void    setVpsNuhLayerIdPresentFlag( Bool val )                          { m_vpsNuhLayerIdPresentFlag = val; }
-  Bool    getVpsNuhLayerIdPresentFlag()                                    { return m_vpsNuhLayerIdPresentFlag; }
-
-  Void    setLayerIdInNuh( Int layerIdInVps, Int val )                     { m_layerIdInNuh[layerIdInVps] = val;  }
-  Int     getLayerIdInNuh( Int layerIdInVps )                              { assert( m_layerIdInNuh[layerIdInVps] >= 0 ); return m_layerIdInNuh[layerIdInVps]; }
-
-  Bool    nuhLayerIdIncluded( Int layerIdinNuh )                           { return ( m_layerIdInVps[ layerIdinNuh ] > 0 );  }
-
-  Void    setDimensionId( Int layerIdInVps, Int scalIdx, Int val )         { m_dimensionId[layerIdInVps][scalIdx] = val;  }
-  Int     getDimensionId( Int layerIdInVps, Int scalIdx )                  { return m_dimensionId[layerIdInVps][scalIdx]; }
-
-  Void    setViewIdLen( Int  val )                                         { m_viewIdLen = val; } 
-  Int     getViewIdLen(  )                                                 { return m_viewIdLen; } 
-
-  Void    setViewIdVal( Int viewOrderIndex, Int  val )                     { m_viewIdVal[viewOrderIndex] = val; } 
-  Int     getViewIdVal( Int viewOrderIndex )                               { return m_viewIdVal[viewOrderIndex]; } 
+  Int     getNumScalabilityTypes( ) const;                                
+
+  Void    setDimensionIdLen( Int sIdx, Int val )                                { m_dimensionIdLen[sIdx] = val;  }
+  Int     getDimensionIdLen( Int sIdx )                             const       { assert( m_dimensionIdLen[sIdx] > 0) ; return m_dimensionIdLen[sIdx]; }  
+
+  Void    setVpsNuhLayerIdPresentFlag( Bool val )                               { m_vpsNuhLayerIdPresentFlag = val; }
+  Bool    getVpsNuhLayerIdPresentFlag()                             const       { return m_vpsNuhLayerIdPresentFlag; }
+
+  Void    setLayerIdInNuh( Int layerIdInVps, Int val )                          { m_layerIdInNuh[layerIdInVps] = val;  }
+  Int     getLayerIdInNuh( Int layerIdInVps )                       const       { assert( m_layerIdInNuh[layerIdInVps] >= 0 ); return m_layerIdInNuh[layerIdInVps]; }
+
+  Bool    nuhLayerIdIncluded( Int layerIdinNuh )                    const       { return ( m_layerIdInVps[ layerIdinNuh ] > 0 );  }
+
+  Void    setDimensionId( Int layerIdInVps, Int scalIdx, Int val )              { m_dimensionId[layerIdInVps][scalIdx] = val;  }
+  Int     getDimensionId( Int layerIdInVps, Int scalIdx )           const       { return m_dimensionId[layerIdInVps][scalIdx]; }
+
+  Void    setViewIdLen( Int  val )                                              { m_viewIdLen = val; } 
+  Int     getViewIdLen(  )                                          const       { return m_viewIdLen; } 
+
+  Void    setViewIdVal( Int viewOrderIndex, Int  val )                          { m_viewIdVal[viewOrderIndex] = val; } 
+  Int     getViewIdVal( Int viewOrderIndex )                        const       { return m_viewIdVal[viewOrderIndex]; } 
   
-  Void    setDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps, Bool val ) { m_directDependencyFlag[depLayeridInVps][refLayeridInVps] = val;  }
-  Bool    getDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps )           { return m_directDependencyFlag[depLayeridInVps][refLayeridInVps]; }
+  Void    setDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps, Bool val )       { m_directDependencyFlag[depLayeridInVps][refLayeridInVps] = val;  }
+  Bool    getDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps )           const { return m_directDependencyFlag[depLayeridInVps][refLayeridInVps]; }
   
-  Void    setVpsSubLayersMaxMinus1PresentFlag( Bool flag )                 { m_vpsSubLayersMaxMinus1PresentFlag = flag; } 
-  Bool    getVpsSubLayersMaxMinus1PresentFlag(  )                          { return m_vpsSubLayersMaxMinus1PresentFlag; } 
+  Void    setVpsSubLayersMaxMinus1PresentFlag( Bool flag )                      { m_vpsSubLayersMaxMinus1PresentFlag = flag; } 
+  Bool    getVpsSubLayersMaxMinus1PresentFlag(  )                    const      { return m_vpsSubLayersMaxMinus1PresentFlag; } 
   
-  Void    setSubLayersVpsMaxMinus1( Int i, Int  val )                      { m_subLayersVpsMaxMinus1[i] = val; } 
-  Int     getSubLayersVpsMaxMinus1( Int i )                                { return m_subLayersVpsMaxMinus1[i]; } 
-  Void    checkSubLayersVpsMaxMinus1( Int i )                              { assert( m_subLayersVpsMaxMinus1[i] >= 0 && m_subLayersVpsMaxMinus1[i] <= m_uiMaxTLayers - 1 ); }
-
-  Void    setMaxTidRefPresentFlag( Bool flag )                             { m_maxTidRefPresentFlag = flag; } 
-  Bool    getMaxTidRefPresentFlag(  )                                      { return m_maxTidRefPresentFlag; } 
-
-  Void    setMaxTidIlRefPicsPlus1( Int i, Int j, Int  val )                { m_maxTidIlRefPicsPlus1[i][j] = val; } 
-  Int     getMaxTidIlRefPicsPlus1( Int i, Int j )                          { return m_maxTidIlRefPicsPlus1[i][j]; } 
+  Void    setSubLayersVpsMaxMinus1( Int i, Int  val )                           { m_subLayersVpsMaxMinus1[i] = val; } 
+  Int     getSubLayersVpsMaxMinus1( Int i )                          const      { return m_subLayersVpsMaxMinus1[i]; } 
+  Void    checkSubLayersVpsMaxMinus1( Int i )                        const      { assert( m_subLayersVpsMaxMinus1[i] >= 0 && m_subLayersVpsMaxMinus1[i] <= m_uiMaxTLayers - 1 ); }
+
+  Void    setMaxTidRefPresentFlag( Bool flag )                                  { m_maxTidRefPresentFlag = flag; } 
+  Bool    getMaxTidRefPresentFlag(  )                                const      { return m_maxTidRefPresentFlag; } 
+
+  Void    setMaxTidIlRefPicsPlus1( Int i, Int j, Int  val )                     { m_maxTidIlRefPicsPlus1[i][j] = val; } 
+  Int     getMaxTidIlRefPicsPlus1( Int i, Int j )                    const      { return m_maxTidIlRefPicsPlus1[i][j]; } 
  
-  Void    setAllRefLayersActiveFlag( Bool flag )                           { m_allRefLayersActiveFlag = flag; } 
-  Bool    getAllRefLayersActiveFlag(  )                                    { return m_allRefLayersActiveFlag; } 
+  Void    setAllRefLayersActiveFlag( Bool flag )                                { m_allRefLayersActiveFlag = flag; } 
+  Bool    getAllRefLayersActiveFlag(  )                              const      { return m_allRefLayersActiveFlag; } 
   
-  Void    setVpsNumProfileTierLevelMinus1( Int val )                       { m_vpsNumProfileTierLevelMinus1 = val;  } 
-  Int     getVpsNumProfileTierLevelMinus1( )                               { return m_vpsNumProfileTierLevelMinus1; } 
+  Void    setVpsNumProfileTierLevelMinus1( Int val )                            { m_vpsNumProfileTierLevelMinus1 = val;  } 
+  Int     getVpsNumProfileTierLevelMinus1( )                         const      { return m_vpsNumProfileTierLevelMinus1; } 
   
-  Void    setVpsProfilePresentFlag( Int idx, Bool val )                    { m_vpsProfilePresentFlag[idx] = val;  }
-  Bool    getVpsProfilePresentFlag( Int idx )                              { return m_vpsProfilePresentFlag[idx]; }
-
-  Void    setNumAddLayerSets( Int val )                                    { m_numAddLayerSets = val; } 
-  Int     getNumAddLayerSets( )                                            { return m_numAddLayerSets; } 
+  Void    setVpsProfilePresentFlag( Int idx, Bool val )                         { m_vpsProfilePresentFlag[idx] = val;  }
+  Bool    getVpsProfilePresentFlag( Int idx )                        const      { return m_vpsProfilePresentFlag[idx]; }
+
+  Void    setNumAddLayerSets( Int val )                                         { m_numAddLayerSets = val; } 
+  Int     getNumAddLayerSets( )                                      const      { return m_numAddLayerSets; } 
   
-  Void    setHighestLayerIdxPlus1( Int i, Int j, Int  val )                { m_highestLayerIdxPlus1[i][j] = val; } 
-  Int     getHighestLayerIdxPlus1( Int i, Int j )                          { return m_highestLayerIdxPlus1[i][j]; } 
-
-  Void    setNumAddOlss( Int  val )                                        { m_numAddOlss = val; } 
-  Int     getNumAddOlss(  )                                                { return m_numAddOlss; } 
-
-  Void    setDefaultOutputLayerIdc( Int  val )                             { m_defaultOutputLayerIdc = val; } 
-  Int     getDefaultOutputLayerIdc(  )                                     { return m_defaultOutputLayerIdc; }   
+  Void    setHighestLayerIdxPlus1( Int i, Int j, Int  val )                     { m_highestLayerIdxPlus1[i][j] = val; } 
+  Int     getHighestLayerIdxPlus1( Int i, Int j )                    const      { return m_highestLayerIdxPlus1[i][j]; } 
+
+  Void    setNumAddOlss( Int  val )                                             { m_numAddOlss = val; } 
+  Int     getNumAddOlss(  )                                          const      { return m_numAddOlss; } 
+
+  Void    setDefaultOutputLayerIdc( Int  val )                                  { m_defaultOutputLayerIdc = val; } 
+  Int     getDefaultOutputLayerIdc(  )                               const      { return m_defaultOutputLayerIdc; }   
   
-  Void    setLayerSetIdxForOlsMinus1( Int outLayerSetIdx, Int val )        { m_layerSetIdxForOlsMinus1[ outLayerSetIdx ]  = val; } 
-  Int     getLayerSetIdxForOlsMinus1( Int outLayerSetIdx )                 { return m_layerSetIdxForOlsMinus1[ outLayerSetIdx ]; } 
-  Int     getLayerSetIdxForOlsMinus1Len( Int outLayerSetIdx )              { return gCeilLog2( getNumLayerSets() ); } 
-
-  Void    setOutputLayerFlag( Int outLayerSetIdx, Int i, Bool flag )       { m_outputLayerFlag[ outLayerSetIdx ][ i ] = flag; } 
-  Bool    getOutputLayerFlag( Int outLayerSetIdx, Int i )                  { return m_outputLayerFlag[ outLayerSetIdx ][ i ]; } 
-
-  Bool    inferOutputLayerFlag( Int i, Int j );
-
-  Void    setProfileTierLevelIdx( Int i, Int j, Int val )                  { m_profileTierLevelIdx[ i ][ j ] = val; }
-  Int     getProfileTierLevelIdx( Int i, Int j )                           { return m_profileTierLevelIdx[ i ][ j ]; } 
-  Int     inferProfileTierLevelIdx( Int i, Int j );
-  
-  Void    setAltOutputLayerFlag( Int i, Bool flag )                        { m_altOutputLayerFlag[i] = flag; } 
-  Bool    getAltOutputLayerFlag( Int i )                                   { return m_altOutputLayerFlag[i]; } 
-
-  Void    setRepFormatIdxPresentFlag( Bool flag )                          { m_repFormatIdxPresentFlag = flag; } 
-  Bool    getRepFormatIdxPresentFlag(  )                                   { return m_repFormatIdxPresentFlag; } 
-
-  Void    setVpsNumRepFormatsMinus1( Int  val )                            { m_vpsNumRepFormatsMinus1 = val; } 
-  Int     getVpsNumRepFormatsMinus1(  )                                    { return m_vpsNumRepFormatsMinus1; } 
-
-  Void    setVpsRepFormatIdx( Int i, Int  val )                            { m_vpsRepFormatIdx[i] = val; } 
-  Int     getVpsRepFormatIdx( Int i )                                      { return m_vpsRepFormatIdx[i]; } 
-
-  Int     inferVpsRepFormatIdx( Int i )                                    { return std::min( i, getVpsNumRepFormatsMinus1()  );  }
-
-  Void    setRepFormat( Int i, TComRepFormat* val )                        { m_repFormat[i] = val;  }
-  TComRepFormat* getRepFormat( Int i )                                     { return m_repFormat[i]; }
-  
-  Void    setMaxOneActiveRefLayerFlag( Bool flag)                          { m_maxOneActiveRefLayerFlag = flag; } 
-  Bool    getMaxOneActiveRefLayerFlag( )                                   { return m_maxOneActiveRefLayerFlag; } 
-
-  Void    setVpsPocLsbAlignedFlag( Bool flag )                             { m_vpsPocLsbAlignedFlag = flag; } 
-  Bool    getVpsPocLsbAlignedFlag(  )                                      { return m_vpsPocLsbAlignedFlag; } 
-
-  Void    setDpbSize( TComDpbSize* val )                                   { assert( m_dpbSize != 0 ); m_dpbSize = val; } 
-  TComDpbSize* getDpbSize( )                                               { return m_dpbSize;} 
-  
-
-  Void    setPocLsbNotPresentFlag( Int i, Bool flag )                      { m_pocLsbNotPresentFlag[i] = flag; } 
-  Bool    getPocLsbNotPresentFlag( Int i )                                 { return m_pocLsbNotPresentFlag[i]; } 
-  
-  Void    setDirectDepTypeLenMinus2( Int val)                              { m_directDepTypeLenMinus2 = val; } 
-  Int     getDirectDepTypeLenMinus2( )                                     { return m_directDepTypeLenMinus2; } 
-
-  Void    setDefaultDirectDependencyFlag( Bool flag )                      { m_defaultDirectDependencyFlag = flag; } 
-  Bool    getDefaultDirectDependencyFlag(  )                               { return m_defaultDirectDependencyFlag; } 
-
-  Void    setDefaultDirectDependencyType( Int  val )                       { m_defaultDirectDependencyType = val; } 
-  Int     getDefaultDirectDependencyType(  )                               { return m_defaultDirectDependencyType; } 
+  Void    setLayerSetIdxForOlsMinus1( Int outLayerSetIdx, Int val )             { m_layerSetIdxForOlsMinus1[ outLayerSetIdx ]  = val; } 
+  Int     getLayerSetIdxForOlsMinus1( Int outLayerSetIdx )           const      { return m_layerSetIdxForOlsMinus1[ outLayerSetIdx ]; } 
+  Int     getLayerSetIdxForOlsMinus1Len( Int outLayerSetIdx )        const      { return gCeilLog2( getNumLayerSets() ); } 
+
+  Void    setOutputLayerFlag( Int outLayerSetIdx, Int i, Bool flag )            { m_outputLayerFlag[ outLayerSetIdx ][ i ] = flag; } 
+  Bool    getOutputLayerFlag( Int outLayerSetIdx, Int i )            const      { return m_outputLayerFlag[ outLayerSetIdx ][ i ]; } 
+
+  Bool    inferOutputLayerFlag( Int i, Int j )                       const;
+
+  Void    setProfileTierLevelIdx( Int i, Int j, Int val )                       { m_profileTierLevelIdx[ i ][ j ] = val; }
+  Int     getProfileTierLevelIdx( Int i, Int j )                     const      { return m_profileTierLevelIdx[ i ][ j ]; } 
+  Int     inferProfileTierLevelIdx( Int i, Int j )                   const; 
+                                                                     
+  Void    setAltOutputLayerFlag( Int i, Bool flag )                             { m_altOutputLayerFlag[i] = flag; } 
+  Bool    getAltOutputLayerFlag( Int i )                             const      { return m_altOutputLayerFlag[i]; } 
+                                                                     
+  Void    setRepFormatIdxPresentFlag( Bool flag )                               { m_repFormatIdxPresentFlag = flag; } 
+  Bool    getRepFormatIdxPresentFlag(  )                             const      { return m_repFormatIdxPresentFlag; } 
+                                                                     
+  Void    setVpsNumRepFormatsMinus1( Int  val )                                 { m_vpsNumRepFormatsMinus1 = val; } 
+  Int     getVpsNumRepFormatsMinus1(  )                              const      { return m_vpsNumRepFormatsMinus1; } 
+                                                                     
+  Void    setVpsRepFormatIdx( Int i, Int  val )                                 { m_vpsRepFormatIdx[i] = val; } 
+  Int     getVpsRepFormatIdx( Int i )                                const      { return m_vpsRepFormatIdx[i]; } 
+
+  Int     inferVpsRepFormatIdx( Int i )                              const      { return std::min( i, getVpsNumRepFormatsMinus1()  );  }
+
+  Void    setRepFormat( Int i, TComRepFormat val )                              { m_repFormat[i] = val;  }
+  Void    setRepFormat( std::vector<TComRepFormat> val )                        { m_repFormat = val;  }
+  const TComRepFormat* getRepFormat( Int i )                         const      { return &m_repFormat[i]; }
+                                                                     
+  Void    setMaxOneActiveRefLayerFlag( Bool flag)                               { m_maxOneActiveRefLayerFlag = flag; } 
+  Bool    getMaxOneActiveRefLayerFlag( )                             const      { return m_maxOneActiveRefLayerFlag; } 
+                                                                     
+  Void    setVpsPocLsbAlignedFlag( Bool flag )                                  { m_vpsPocLsbAlignedFlag = flag; } 
+  Bool    getVpsPocLsbAlignedFlag(  )                                const      { return m_vpsPocLsbAlignedFlag; } 
+                                                                     
+  Void    setDpbSize( TComDpbSize val )                                         { m_dpbSize = val; } 
+  const TComDpbSize * getDpbSize( )                                  const      { return &m_dpbSize; } 
+                                                                     
+                                                                     
+  Void    setPocLsbNotPresentFlag( Int i, Bool flag )                           { m_pocLsbNotPresentFlag[i] = flag; } 
+  Bool    getPocLsbNotPresentFlag( Int i )                           const      { return m_pocLsbNotPresentFlag[i]; } 
+                                                                     
+  Void    setDirectDepTypeLenMinus2( Int val)                                   { m_directDepTypeLenMinus2 = val; } 
+  Int     getDirectDepTypeLenMinus2( )                               const      { return m_directDepTypeLenMinus2; } 
+                                                                     
+  Void    setDefaultDirectDependencyFlag( Bool flag )                           { m_defaultDirectDependencyFlag = flag; } 
+  Bool    getDefaultDirectDependencyFlag(  )                         const      { return m_defaultDirectDependencyFlag; } 
+                                                                     
+  Void    setDefaultDirectDependencyType( Int  val )                            { m_defaultDirectDependencyType = val; } 
+  Int     getDefaultDirectDependencyType(  )                         const      { return m_defaultDirectDependencyType; } 
   
   Void    setDirectDependencyType( Int depLayeridInVps, Int refLayeridInVps, Int val) { m_directDependencyType[ depLayeridInVps ][ refLayeridInVps ] = val; } 
-  Int     getDirectDependencyType( Int depLayeridInVps, Int refLayeridInVps)   { return m_directDependencyType[ depLayeridInVps ][ refLayeridInVps ]; } 
-
-  Void    setVpsVuiPresentFlag( Bool flag )                                { m_vpsVuiPresentFlag = flag; } 
-  Bool    getVpsVuiPresentFlag(  )                                         { return m_vpsVuiPresentFlag; } 
-
-  TComVPSVUI* getVPSVUI(  )                                                { return m_vpsVUI;  }
+  Int     getDirectDependencyType( Int depLayeridInVps, Int refLayeridInVps) const { return m_directDependencyType[ depLayeridInVps ][ refLayeridInVps ]; } 
+
+  Void    setVpsVuiPresentFlag( Bool flag )                                     { m_vpsVuiPresentFlag = flag; } 
+  Bool    getVpsVuiPresentFlag(  )                                   const      { return m_vpsVuiPresentFlag; } 
+                                                         
+  const TComVPSVUI* getVPSVUI(  )                                    const      { return &m_vpsVUI;  }
+  Void  setVPSVUI( TComVPSVUI val )                                             { m_vpsVUI = val;  }
  
  // VPS EXTENSION SEMANTICS VARIABLES
-  Void    setLayerIdInVps( Int layerIdInNuh, Int val )                     { m_layerIdInVps[layerIdInNuh] = val;  }
-  Int     getLayerIdInVps( Int layerIdInNuh )                              { assert( m_layerIdInVps[layerIdInNuh] >= 0 ); return m_layerIdInVps[layerIdInNuh]; }
-
-  Int     getScalabilityId ( Int layerIdInVps, ScalabilityType scalType );
-  Int     getViewId        ( Int layerIdInNuh )                            { return m_viewIdVal[ getViewIndex( layerIdInNuh )]; }
+  Void    setLayerIdInVps( Int layerIdInNuh, Int val )                          { m_layerIdInVps[layerIdInNuh] = val;  }
+  Int     getLayerIdInVps( Int layerIdInNuh )                        const      { assert( m_layerIdInVps[layerIdInNuh] >= 0 ); return m_layerIdInVps[layerIdInNuh]; }
+
+  Int     getScalabilityId ( Int layerIdInVps, ScalabilityType scalType ) const ;
+  Int     getViewId        ( Int layerIdInNuh )                 const           { return m_viewIdVal[ getViewIndex( layerIdInNuh )]; }
   Void    setRefLayers(); 
 
   // To be aligned with spec naming, getViewIndex will be removed in future versions
-  Int     getViewOrderIdx ( Int layerIdInNuh )                             { return getScalabilityId( getLayerIdInVps(layerIdInNuh), VIEW_ORDER_INDEX  ); }    
-  Int     getViewIndex    ( Int layerIdInNuh )                             { return getViewOrderIdx( layerIdInNuh ); }    
-  Int     getAuxId        ( Int layerIdInNuh )                             { return getScalabilityId( getLayerIdInVps(layerIdInNuh), AUX_ID  ); }    
-  Int     getDependencyId ( Int layerIdInNuh )                             { return getScalabilityId( getLayerIdInVps(layerIdInNuh), DEPENDENCY_ID  ); }    
-  Int     getNumViews()                                                    { return m_numViews; }
+  Int     getViewOrderIdx ( Int layerIdInNuh ) const                            { return getScalabilityId( getLayerIdInVps(layerIdInNuh), VIEW_ORDER_INDEX  ); }    
+  Int     getViewIndex    ( Int layerIdInNuh ) const                            { return getViewOrderIdx( layerIdInNuh ); }    
+  Int     getAuxId        ( Int layerIdInNuh ) const                            { return getScalabilityId( getLayerIdInVps(layerIdInNuh), AUX_ID  ); }    
+  Int     getDependencyId ( Int layerIdInNuh ) const                            { return getScalabilityId( getLayerIdInVps(layerIdInNuh), DEPENDENCY_ID  ); }    
+  Int     getNumViews()                        const                            { return m_numViews; }
   Void    initNumViews();
-#if H_3D
-  Void   initViewCompLayer( );
-  Int     getViewOIdxList( Int i )                                         { return m_viewOIdxList[i]; }
-  std::vector<Int> getViewOIdxList( )                                               { return m_viewOIdxList; }
-
-  Int     getVoiInVps( Int viewOIdx );;
-
-  Bool    getViewCompLayerPresentFlag (Int i, Bool d ) { return  m_viewCompLayerPresentFlag[ getVoiInVps(i) ][d]; }
-  Bool    getViewCompLayerId          (Int i, Bool d ) { return  m_viewCompLayerId         [ getVoiInVps(i) ][d]; }
-#endif
-  Bool    getDependencyFlag( Int i, Int j )                                { return m_dependencyFlag[i][j]; }
-  Int     getNumDirectRefLayers( Int layerIdInNuh )                        { return m_numDirectRefLayers[ layerIdInNuh ];  };                               
-#if H_3D
-  Int     getNumRefListLayers( Int layerIdInNuh )                         { return m_numRefListLayers[ layerIdInNuh ];  };                               
-#endif
-
-  Int     getNumRefLayers            ( Int i )        { return m_numRefLayers[i]; } 
-  Int     getNumPredictedLayers      ( Int i )        { return m_numPredictedLayers[i]; } 
-
-
-  Int     getIdRefLayer              ( Int i, Int j ) { assert( j >= 0 && j < getNumRefLayers      ( i )); return m_idRefLayer      [i][j]; } 
-  Int     getIdPredictedLayer        ( Int i, Int j ) { assert( j >= 0 && j < getNumPredictedLayers( i )); return m_idPredictedLayer[i][j]; } 
-  Int     getIdDirectRefLayer        ( Int i, Int j ) { assert( j >= 0 && j < getNumDirectRefLayers( i )); return m_idDirectRefLayer[i][j]; } 
-#if H_3D
-  Int     getIdRefListLayer          ( Int i, Int j ) { assert( j >= 0 && j < getNumRefListLayers   ( i )); return m_idRefListLayer[i][j]; } 
-#endif
-  Int     getNumIndependentLayers    (  )             { return m_numIndependentLayers; } 
-  Int     getNumLayersInTreePartition( Int i )        { return m_numLayersInTreePartition[i]; } 
-  Int     getTreePartitionLayerIdList( Int i, Int j ) { return m_treePartitionLayerIdList[i][j]; } 
-  Bool    getRecursiveRefLayerFlag   ( Int i, Int j ) { return m_recursiveRefLayerFlag[i][j]; } 
-  Int     getNumLayerSets( )                                               { return getVpsNumLayerSetsMinus1() + 1 + getNumAddLayerSets();  };  
-  
-  Int     getFirstAddLayerSetIdx()                    { return getVpsNumLayerSetsMinus1() + 1; } 
-  Int     getLastAddLayerSetIdx()                     { return getFirstAddLayerSetIdx() + getNumAddLayerSets() - 1; }
+#if NH_3D
+  Void    initViewCompLayer( );
+  Int     getViewOIdxList( Int i )             const                            { return m_viewOIdxList[i]; }
+  std::vector<Int> getViewOIdxList( )          const                            { return m_viewOIdxList; }
+
+  Int     getVoiInVps( Int viewOIdx )          const;
+
+  Bool    getViewCompLayerPresentFlag (Int i, Bool d ) const                    { return  m_viewCompLayerPresentFlag[ getVoiInVps(i) ][d]; }
+  Bool    getViewCompLayerId          (Int i, Bool d ) const                    { return  m_viewCompLayerId         [ getVoiInVps(i) ][d]; }
+#endif
+  Bool    getDependencyFlag( Int i, Int j ) const                               { return m_dependencyFlag[i][j]; }
+  Int     getNumDirectRefLayers( Int layerIdInNuh ) const                       { return m_numDirectRefLayers[ layerIdInNuh ];  };                               
+#if NH_3D                                                                      
+  Int     getNumRefListLayers( Int layerIdInNuh )   const                       { return m_numRefListLayers[ layerIdInNuh ];  };                               
+#endif
+
+  Int     getNumRefLayers            ( Int i )      const                       { return m_numRefLayers[i]; } 
+  Int     getNumPredictedLayers      ( Int i )      const                       { return m_numPredictedLayers[i]; } 
+                                                                                
+  Int     getIdRefLayer              ( Int i, Int j ) const                     { assert( j >= 0 && j < getNumRefLayers      ( i )); return m_idRefLayer      [i][j]; } 
+  Int     getIdPredictedLayer        ( Int i, Int j ) const                     { assert( j >= 0 && j < getNumPredictedLayers( i )); return m_idPredictedLayer[i][j]; } 
+  Int     getIdDirectRefLayer        ( Int i, Int j ) const                     { assert( j >= 0 && j < getNumDirectRefLayers( i )); return m_idDirectRefLayer[i][j]; } 
+#if NH_3D                                                                      
+  Int     getIdRefListLayer          ( Int i, Int j ) const                     { assert( j >= 0 && j < getNumRefListLayers   ( i )); return m_idRefListLayer[i][j]; } 
+#endif                                                                          
+  Int     getNumIndependentLayers    (  )             const                     { return m_numIndependentLayers; } 
+  Int     getNumLayersInTreePartition( Int i )        const                     { return m_numLayersInTreePartition[i]; } 
+  Int     getTreePartitionLayerIdList( Int i, Int j ) const                     { return m_treePartitionLayerIdList[i][j]; } 
+  Bool    getRecursiveRefLayerFlag   ( Int i, Int j ) const                     { return m_recursiveRefLayerFlag[i][j]; } 
+  Int     getNumLayerSets( )                          const                     { return getVpsNumLayerSetsMinus1() + 1 + getNumAddLayerSets();  };  
+                                                                                
+  Int     getFirstAddLayerSetIdx()                    const                     { return getVpsNumLayerSetsMinus1() + 1; } 
+  Int     getLastAddLayerSetIdx()                     const                     { return getFirstAddLayerSetIdx() + getNumAddLayerSets() - 1; }
   Bool    checkVPSExtensionSyntax(); 
-  Int     scalTypeToScalIdx   ( ScalabilityType scalType );
-
-  Int     getProfileTierLevelIdxLen()                                      { return gCeilLog2( getVpsNumProfileTierLevelMinus1() + 1 ); };       
-  Int     getVpsRepFormatIdxLen()                                          { return gCeilLog2( getVpsNumRepFormatsMinus1() + 1 ); };       
-
-  Int     getNumLayersInIdList ( Int lsIdx );
-  Int     getLayerSetLayerIdList(Int lsIdx, Int j )                       { return m_layerSetLayerIdList[ lsIdx ][ j ]; }; 
-
-  Int     getNumOutputLayerSets() ;   
-
-  Bool    isOutputLayer( Int outLayerSetIdx, Int layerIdInNuh );   
+  Int     scalTypeToScalIdx   ( ScalabilityType scalType ) const ;
+
+  Int     getProfileTierLevelIdxLen()                 const                     { return gCeilLog2( getVpsNumProfileTierLevelMinus1() + 1 ); };       
+  Int     getVpsRepFormatIdxLen()                     const                     { return gCeilLog2( getVpsNumRepFormatsMinus1() + 1 ); };       
+
+  Int     getNumLayersInIdList ( Int lsIdx )          const; 
+  Int     getLayerSetLayerIdList(Int lsIdx, Int j )   const                     { return m_layerSetLayerIdList[ lsIdx ][ j ]; }; 
+
+  Int     getNumOutputLayerSets()                     const; 
+
+  Bool    isOutputLayer( Int outLayerSetIdx, Int layerIdInNuh )  const;    
   Void    deriveLayerSetLayerIdList();
 
-  Int     olsIdxToLsIdx( Int i )                                           { return ( i < getNumLayerSets() ) ? i  : getLayerSetIdxForOlsMinus1( i ) + 1 ; };
+  Int     olsIdxToLsIdx( Int i )                                       const    { return ( i < getNumLayerSets() ) ? i  : getLayerSetIdxForOlsMinus1( i ) + 1 ; };
   Void    initTargetLayerIdLists  ( );
   Void    deriveTargetLayerIdList ( Int i );
-  std::vector<Int> getTargetDecLayerIdList( Int targetDecLayerSetIdx )     { return m_targetDecLayerIdLists[targetDecLayerSetIdx]; }; 
-  std::vector<Int> getTargetOptLayerIdList( Int targetOptLayerSetIdx )     { return m_targetOptLayerIdLists[targetOptLayerSetIdx]; }; 
-
-  Int     getNumOutputLayersInOutputLayerSet( Int i )                      { return (Int) getTargetOptLayerIdList( i ).size(); }; 
-  Int     getOlsHighestOutputLayerId( Int i )                              { return getTargetOptLayerIdList( i ).back(); };  
+  std::vector<Int> getTargetDecLayerIdList( Int targetDecLayerSetIdx ) const     { return m_targetDecLayerIdLists[targetDecLayerSetIdx]; }; 
+  std::vector<Int> getTargetOptLayerIdList( Int targetOptLayerSetIdx ) const     { return m_targetOptLayerIdLists[targetOptLayerSetIdx]; }; 
+
+  Int     getNumOutputLayersInOutputLayerSet( Int i )                  const     { return (Int) getTargetOptLayerIdList( i ).size(); }; 
+  Int     getOlsHighestOutputLayerId( Int i )                          const     { return getTargetOptLayerIdList( i ).back(); };  
 
   Void    deriveAddLayerSetLayerIdList( Int i );
-  Void    deriveNecessaryLayerFlags( Int olsIdx );;
-  Int     getNecessaryLayerFlag( Int i, Int j )                            { AOF( i >= 0 && i < getNumOutputLayerSets() ); AOF( j >= 0 && j < getNumLayersInIdList( olsIdxToLsIdx( i ) )  );  return m_necessaryLayerFlag[i][j]; };  
-
-  Int     getMaxSubLayersInLayerSetMinus1( Int i );
-  Int     getHighestLayerIdxPlus1Len( Int j )                                   { return gCeilLog2( getNumLayersInTreePartition( j ) + 1 );   }; 
-  Bool    getAltOutputLayerFlagVar( Int i );;
+  Void    deriveNecessaryLayerFlags( Int olsIdx );
+  Int     getNecessaryLayerFlag( Int i, Int j )                        const     { AOF( i >= 0 && i < getNumOutputLayerSets() ); AOF( j >= 0 && j < getNumLayersInIdList( olsIdxToLsIdx( i ) )  );  return m_necessaryLayerFlag[i][j]; };  
+
+  Int     getMaxSubLayersInLayerSetMinus1( Int i )                     const;
+  Int     getHighestLayerIdxPlus1Len( Int j )                          const     { return gCeilLog2( getNumLayersInTreePartition( j ) + 1 );   }; 
+  Bool    getAltOutputLayerFlagVar( Int i )                            const;
 
   // inference
-  Int     inferDimensionId     ( Int i, Int j );
-  Int     inferLastDimsionIdLenMinus1();
+  Int     inferDimensionId     ( Int i, Int j )                        const;
+  Int     inferLastDimsionIdLenMinus1()                                const;
 
   // helpers
-  Void    printPTL();
-  Void    printLayerDependencies();
-  Void    printScalabilityId();;
-  Void    printLayerSets();;
-
-
-
-  template <typename T, typename S, typename U> Void xPrintArray( const Char* name, Int numElemDim1, U idx, S numElemDim2, T vec, Bool printNumber, Bool printIdx = true )
+  Void    printPTL()                                                   const;
+  Void    printLayerDependencies()                                     const;
+  Void    printScalabilityId()                                         const;
+  Void    printLayerSets()                                             const;
+
+
+  /// VPS EXTENSION 2 SYNTAX ELEMENTS
+  Int     getDepthId                   ( Int layerIdInNuh)             const    { return getScalabilityId( getLayerIdInVps(layerIdInNuh), DEPTH_ID ); }
+#if NH_3D                                                             
+  Bool    getVpsDepthFlag              ( Int layerIdInNuh)             const    { return (getDepthId( layerIdInNuh ) > 0);  }
+  Int     getLayerIdInNuh              ( Int viewIndex, Bool depthFlag ) const;   
+          
+  Void    createCamPars                ( Int iNumViews );  
+  Void    initCamParaVPS               ( Int vOIdxInVps, Int numCp, Bool cpInSliceSegmentHeaderFlag, Int* cpRefVoi, Int** aaiScale, Int** aaiOffset );                                                
+                                       
+  Void    setCpPrecision               ( Int  val )                             { m_cpPrecision = val;                       }
+  Int     getCpPrecision               (  )                            const    { return m_cpPrecision;                      }
+                                                                                                                
+  Void    setNumCp                     ( Int i, Int  val )                      { m_numCp[i] = val;                          }
+  Int     getNumCp                     ( Int i )                       const    { return m_numCp[i];                         }
+                                                                                                                
+  Void    setCpRefVoi                  ( Int i, Int m, Int  val )               { m_cpRefVoi[i][m] = val;                    }
+  Int     getCpRefVoi                  ( Int i, Int m )                const    { return m_cpRefVoi[i][m];                   }
+                                                                                                                
+  Void    setCpInSliceSegmentHeaderFlag( Int i, Bool flag )                     { m_cpInSliceSegmentHeaderFlag[i] = flag;    }
+  Bool    getCpInSliceSegmentHeaderFlag( Int i )                       const    { return m_cpInSliceSegmentHeaderFlag[i];    }
+                                                                                                                
+  Void    setVpsCpScale                ( Int i, Int j, Int val )                { m_aaaiCodedScale [i][0][j] = val;          }
+  Int     getVpsCpScale                ( Int i, Int j )                const    { return m_aaaiCodedScale[i][0][j];          }
+                                                                                                                
+  Void    setVpsCpOff                  ( Int i, Int j, Int val )                { m_aaaiCodedOffset[i][0][j] = val;          }
+  Int     getVpsCpOff                  ( Int i, Int j )                const    { return m_aaaiCodedOffset[i][0][j];         }
+                                                                                                                
+  Void    setVpsCpInvScale             ( Int i, Int j, Int val )                { m_aaaiCodedScale[i][1][j] = val;           }
+  Int     getVpsCpInvScale             ( Int i, Int j )                const    { return m_aaaiCodedScale[i][1][j];          }
+                                                                                                                
+  Void    setVpsCpInvOff               ( Int i, Int j, Int val )                { m_aaaiCodedOffset[i][1][j] = val;          }
+  Int     getVpsCpInvOff               ( Int i, Int j )                const    { return m_aaaiCodedOffset[i][1][j];         }
+
+// Derived
+  Void    deriveCpPresentFlag          ( );                  
+  Void    setCpPresentFlag             ( Int i, Int m, Bool flag )              { m_cpPresentFlag[i][m] = flag;             } 
+  Bool    getCpPresentFlag             ( Int i, Int m )                const    { return m_cpPresentFlag[i][m];             }   
+                                                                       
+  const IntAry1d& getCodedScale        ( Int viewIndex )               const    { return m_aaaiCodedScale [viewIndex][0];   }
+  const IntAry1d& getCodedOffset       ( Int viewIndex )               const    { return m_aaaiCodedOffset[viewIndex][0];   }
+  const IntAry1d& getInvCodedScale     ( Int viewIndex )               const    { return m_aaaiCodedScale [viewIndex][1];   }
+  const IntAry1d& getInvCodedOffset    ( Int viewIndex )               const    { return m_aaaiCodedOffset[viewIndex][1];   }
+#endif
+
+  template <typename T, typename S, typename U> Void xPrintArray( const Char* name, Int numElemDim1, U idx, S numElemDim2, T vec, Bool printNumber, Bool printIdx = true ) const
   {
     std::cout << std::endl; 
@@ -1246,5 +1327,5 @@
         std::cout << std::right << std::setw(5) << " "; 
       }
-      
+
       if ( printNumber )
       {
@@ -1253,5 +1334,5 @@
       else
       {
-       std::cout << std::right << std::setw(6) << " ";              
+        std::cout << std::right << std::setw(6) << " ";              
       }
 
@@ -1265,5 +1346,5 @@
   }
 
-  template <typename T> Void xPrintArray( const char* name, Int numElem, T vec, Bool printNumber  )
+  template <typename T> Void xPrintArray( const char* name, Int numElem, T vec, Bool printNumber  )  const
   {
     std::vector<Int> numElemDim2(1, numElem);    
@@ -1273,57 +1354,4 @@
   }
 
-
-  /// VPS EXTENSION 2 SYNTAX ELEMENTS
-
-
-#if H_3D  
-  Int     getDepthId      ( Int layerIdInNuh)                             { return getScalabilityId( getLayerIdInVps(layerIdInNuh), DEPTH_ID ); }
-  Bool    getVpsDepthFlag( Int layerIdInNuh)                              { return (getDepthId( layerIdInNuh ) > 0);  }
-  Int     getLayerIdInNuh( Int viewIndex, Bool depthFlag );   
-
-
-  Void createCamPars(Int iNumViews);
-  Void deleteCamPars();
-  Void initCamParaVPS( Int vOIdxInVps, Int numCp, Bool cpInSliceSegmentHeaderFlag, Int* cpRefVoi, Int** aaiScale, Int** aaiOffset ); 
-  
-
-  Void setCpPrecision( Int  val ) { m_cpPrecision = val; } 
-  Int  getCpPrecision(  ) { return m_cpPrecision; } 
-
-  Void setNumCp( Int i, Int  val ) { m_numCp[i] = val; } 
-  Int  getNumCp( Int i )           { return m_numCp[i]; } 
-
-  Void setCpRefVoi( Int i, Int m, Int  val ) { m_cpRefVoi[i][m] = val; } 
-  Int  getCpRefVoi( Int i, Int m )           { return m_cpRefVoi[i][m]; }   
-  
-  Void setCpInSliceSegmentHeaderFlag( Int i, Bool flag ) { m_cpInSliceSegmentHeaderFlag[i] = flag; } 
-  Bool getCpInSliceSegmentHeaderFlag( Int i )            { return m_cpInSliceSegmentHeaderFlag[i]; } 
-  
-  Void setVpsCpScale( Int i, Int j, Int  val ) { m_aaaiCodedScale [i][0][j] = val; } 
-  Int  getVpsCpScale( Int i, Int j ) { return m_aaaiCodedScale[i][0][j]; } 
-
-  Void setVpsCpOff( Int i, Int j, Int  val ) { m_aaaiCodedOffset[i][0][j] = val; } 
-  Int  getVpsCpOff( Int i, Int j ) { return m_aaaiCodedOffset[i][0][j]; } 
-
-  Void setVpsCpInvScale( Int i, Int j, Int  val ) { m_aaaiCodedScale[i][1][j] = val; } 
-  Int  getVpsCpInvScale( Int i, Int j ) { return m_aaaiCodedScale[i][1][j]; } 
-
-  Void setVpsCpInvOff( Int i, Int j, Int  val ) { m_aaaiCodedOffset[i][1][j] = val; } 
-  Int  getVpsCpInvOff( Int i, Int j ) { return m_aaaiCodedOffset[i][1][j]; } 
-
-// Derived
-  Void deriveCpPresentFlag( );
-
-  Void setCpPresentFlag( Int i, Int m, Bool flag ) { m_cpPresentFlag[i][m] = flag; } 
-  Bool getCpPresentFlag( Int i, Int m )           { return m_cpPresentFlag[i][m]; }   
-
-
-
-  Int* getCodedScale         ( Int viewIndex )  { return m_aaaiCodedScale [viewIndex][0]; }
-  Int* getCodedOffset        ( Int viewIndex )  { return m_aaaiCodedOffset[viewIndex][0]; }
-  Int* getInvCodedScale      ( Int viewIndex )  { return m_aaaiCodedScale [viewIndex][1]; }
-  Int* getInvCodedOffset     ( Int viewIndex )  { return m_aaaiCodedOffset[viewIndex][1]; }
-
-#endif
 #endif
 };
@@ -1373,50 +1401,50 @@
 #endif
 
+
 class Window
 {
 private:
-  Bool          m_enabledFlag;
-  Int           m_winLeftOffset;
-  Int           m_winRightOffset;
-  Int           m_winTopOffset;
-  Int           m_winBottomOffset;
-#if H_MV
+  Bool m_enabledFlag;
+  Int  m_winLeftOffset;
+  Int  m_winRightOffset;
+  Int  m_winTopOffset;
+  Int  m_winBottomOffset;
+#if NH_MV
   Bool          m_scaledFlag; 
 #endif
 public:
   Window()
-  : m_enabledFlag (false)
-  , m_winLeftOffset     (0)
-  , m_winRightOffset    (0)
-  , m_winTopOffset      (0)
-  , m_winBottomOffset   (0)
-#if H_MV
+  : m_enabledFlag    (false)
+  , m_winLeftOffset  (0)
+  , m_winRightOffset (0)
+  , m_winTopOffset   (0)
+  , m_winBottomOffset(0)
+#if NH_MV
   , m_scaledFlag(true)
 #endif
   { }
 
-  Bool          getWindowEnabledFlag() const      { return m_enabledFlag; }
-  Void          resetWindow()                     { m_enabledFlag = false; m_winLeftOffset = m_winRightOffset = m_winTopOffset = m_winBottomOffset = 0; }
-  Int           getWindowLeftOffset() const       { return m_enabledFlag ? m_winLeftOffset : 0; }
-  Void          setWindowLeftOffset(Int val)      { m_winLeftOffset = val; m_enabledFlag = true; }
-  Int           getWindowRightOffset() const      { return m_enabledFlag ? m_winRightOffset : 0; }
-  Void          setWindowRightOffset(Int val)     { m_winRightOffset = val; m_enabledFlag = true; }
-  Int           getWindowTopOffset() const        { return m_enabledFlag ? m_winTopOffset : 0; }
-  Void          setWindowTopOffset(Int val)       { m_winTopOffset = val; m_enabledFlag = true; }
-  Int           getWindowBottomOffset() const     { return m_enabledFlag ? m_winBottomOffset: 0; }
-  Void          setWindowBottomOffset(Int val)    { m_winBottomOffset = val; m_enabledFlag = true; }
-
-#if H_MV
+  Bool getWindowEnabledFlag() const   { return m_enabledFlag;                          }
+  Int  getWindowLeftOffset() const    { return m_enabledFlag ? m_winLeftOffset : 0;    }
+  Void setWindowLeftOffset(Int val)   { m_winLeftOffset = val; m_enabledFlag = true;   }
+  Int  getWindowRightOffset() const   { return m_enabledFlag ? m_winRightOffset : 0;   }
+  Void setWindowRightOffset(Int val)  { m_winRightOffset = val; m_enabledFlag = true;  }
+  Int  getWindowTopOffset() const     { return m_enabledFlag ? m_winTopOffset : 0;     }
+  Void setWindowTopOffset(Int val)    { m_winTopOffset = val; m_enabledFlag = true;    }
+  Int  getWindowBottomOffset() const  { return m_enabledFlag ? m_winBottomOffset: 0;   }
+  Void setWindowBottomOffset(Int val) { m_winBottomOffset = val; m_enabledFlag = true; }
+
+#if NH_MV
   Void          setScaledFlag(Bool flag)          { m_scaledFlag = flag;  } 
   Bool          getScaledFlag() const             { return m_scaledFlag;  } 
   Void          scaleOffsets( Int scal );
 #endif
-  Void          setWindow(Int offsetLeft, Int offsetLRight, Int offsetLTop, Int offsetLBottom)
+  Void setWindow(Int offsetLeft, Int offsetLRight, Int offsetLTop, Int offsetLBottom)
   {
-    m_enabledFlag       = true;
-    m_winLeftOffset     = offsetLeft;
-    m_winRightOffset    = offsetLRight;
-    m_winTopOffset      = offsetLTop;
-    m_winBottomOffset   = offsetLBottom;
+    m_enabledFlag     = true;
+    m_winLeftOffset   = offsetLeft;
+    m_winRightOffset  = offsetLRight;
+    m_winTopOffset    = offsetLTop;
+    m_winBottomOffset = offsetLBottom;
   }
 };
@@ -1426,170 +1454,230 @@
 {
 private:
-  Bool m_aspectRatioInfoPresentFlag;
-  Int  m_aspectRatioIdc;
-  Int  m_sarWidth;
-  Int  m_sarHeight;
-  Bool m_overscanInfoPresentFlag;
-  Bool m_overscanAppropriateFlag;
-  Bool m_videoSignalTypePresentFlag;
-  Int  m_videoFormat;
-  Bool m_videoFullRangeFlag;
-  Bool m_colourDescriptionPresentFlag;
-  Int  m_colourPrimaries;
-  Int  m_transferCharacteristics;
-  Int  m_matrixCoefficients;
-  Bool m_chromaLocInfoPresentFlag;
-  Int  m_chromaSampleLocTypeTopField;
-  Int  m_chromaSampleLocTypeBottomField;
-  Bool m_neutralChromaIndicationFlag;
-  Bool m_fieldSeqFlag;
-
-  Window m_defaultDisplayWindow;
-  Bool m_frameFieldInfoPresentFlag;
-  Bool m_hrdParametersPresentFlag;
-  Bool m_bitstreamRestrictionFlag;
-  Bool m_tilesFixedStructureFlag;
-  Bool m_motionVectorsOverPicBoundariesFlag;
-  Bool m_restrictedRefPicListsFlag;
-  Int  m_minSpatialSegmentationIdc;
-  Int  m_maxBytesPerPicDenom;
-  Int  m_maxBitsPerMinCuDenom;
-  Int  m_log2MaxMvLengthHorizontal;
-  Int  m_log2MaxMvLengthVertical;
-  TComHRD m_hrdParameters;
+  Bool       m_aspectRatioInfoPresentFlag;
+  Int        m_aspectRatioIdc;
+  Int        m_sarWidth;
+  Int        m_sarHeight;
+  Bool       m_overscanInfoPresentFlag;
+  Bool       m_overscanAppropriateFlag;
+  Bool       m_videoSignalTypePresentFlag;
+  Int        m_videoFormat;
+  Bool       m_videoFullRangeFlag;
+  Bool       m_colourDescriptionPresentFlag;
+  Int        m_colourPrimaries;
+  Int        m_transferCharacteristics;
+  Int        m_matrixCoefficients;
+  Bool       m_chromaLocInfoPresentFlag;
+  Int        m_chromaSampleLocTypeTopField;
+  Int        m_chromaSampleLocTypeBottomField;
+  Bool       m_neutralChromaIndicationFlag;
+  Bool       m_fieldSeqFlag;
+  Window     m_defaultDisplayWindow;
+  Bool       m_frameFieldInfoPresentFlag;
+  Bool       m_hrdParametersPresentFlag;
+  Bool       m_bitstreamRestrictionFlag;
+  Bool       m_tilesFixedStructureFlag;
+  Bool       m_motionVectorsOverPicBoundariesFlag;
+  Bool       m_restrictedRefPicListsFlag;
+  Int        m_minSpatialSegmentationIdc;
+  Int        m_maxBytesPerPicDenom;
+  Int        m_maxBitsPerMinCuDenom;
+  Int        m_log2MaxMvLengthHorizontal;
+  Int        m_log2MaxMvLengthVertical;
+  TComHRD    m_hrdParameters;
   TimingInfo m_timingInfo;
 
 public:
   TComVUI()
-    :m_aspectRatioInfoPresentFlag(false)
-    ,m_aspectRatioIdc(0)
-    ,m_sarWidth(0)
-    ,m_sarHeight(0)
-    ,m_overscanInfoPresentFlag(false)
-    ,m_overscanAppropriateFlag(false)
-    ,m_videoSignalTypePresentFlag(false)
-    ,m_videoFormat(5)
-    ,m_videoFullRangeFlag(false)
-    ,m_colourDescriptionPresentFlag(false)
-    ,m_colourPrimaries(2)
-    ,m_transferCharacteristics(2)
-    ,m_matrixCoefficients(2)
-    ,m_chromaLocInfoPresentFlag(false)
-    ,m_chromaSampleLocTypeTopField(0)
-    ,m_chromaSampleLocTypeBottomField(0)
-    ,m_neutralChromaIndicationFlag(false)
-    ,m_fieldSeqFlag(false)
-    ,m_frameFieldInfoPresentFlag(false)
-    ,m_hrdParametersPresentFlag(false)
-    ,m_bitstreamRestrictionFlag(false)
-    ,m_tilesFixedStructureFlag(false)
-    ,m_motionVectorsOverPicBoundariesFlag(true)
-    ,m_restrictedRefPicListsFlag(1)
-    ,m_minSpatialSegmentationIdc(0)
-    ,m_maxBytesPerPicDenom(2)
-    ,m_maxBitsPerMinCuDenom(1)
-    ,m_log2MaxMvLengthHorizontal(15)
-    ,m_log2MaxMvLengthVertical(15)
+    : m_aspectRatioInfoPresentFlag        (false) //TODO: This initialiser list contains magic numbers
+    , m_aspectRatioIdc                    (0)
+    , m_sarWidth                          (0)
+    , m_sarHeight                         (0)
+    , m_overscanInfoPresentFlag           (false)
+    , m_overscanAppropriateFlag           (false)
+    , m_videoSignalTypePresentFlag        (false)
+    , m_videoFormat                       (5)
+    , m_videoFullRangeFlag                (false)
+    , m_colourDescriptionPresentFlag      (false)
+    , m_colourPrimaries                   (2)
+    , m_transferCharacteristics           (2)
+    , m_matrixCoefficients                (2)
+    , m_chromaLocInfoPresentFlag          (false)
+    , m_chromaSampleLocTypeTopField       (0)
+    , m_chromaSampleLocTypeBottomField    (0)
+    , m_neutralChromaIndicationFlag       (false)
+    , m_fieldSeqFlag                      (false)
+    , m_frameFieldInfoPresentFlag         (false)
+    , m_hrdParametersPresentFlag          (false)
+    , m_bitstreamRestrictionFlag          (false)
+    , m_tilesFixedStructureFlag           (false)
+    , m_motionVectorsOverPicBoundariesFlag(true)
+    , m_restrictedRefPicListsFlag         (1)
+    , m_minSpatialSegmentationIdc         (0)
+    , m_maxBytesPerPicDenom               (2)
+    , m_maxBitsPerMinCuDenom              (1)
+    , m_log2MaxMvLengthHorizontal         (15)
+    , m_log2MaxMvLengthVertical           (15)
   {}
 
-  virtual ~TComVUI() {}
-
-  Bool getAspectRatioInfoPresentFlag() { return m_aspectRatioInfoPresentFlag; }
-  Void setAspectRatioInfoPresentFlag(Bool i) { m_aspectRatioInfoPresentFlag = i; }
-
-  Int getAspectRatioIdc() { return m_aspectRatioIdc; }
-  Void setAspectRatioIdc(Int i) { m_aspectRatioIdc = i; }
-
-  Int getSarWidth() { return m_sarWidth; }
-  Void setSarWidth(Int i) { m_sarWidth = i; }
-
-  Int getSarHeight() { return m_sarHeight; }
-  Void setSarHeight(Int i) { m_sarHeight = i; }
-
-  Bool getOverscanInfoPresentFlag() { return m_overscanInfoPresentFlag; }
-  Void setOverscanInfoPresentFlag(Bool i) { m_overscanInfoPresentFlag = i; }
-
-  Bool getOverscanAppropriateFlag() { return m_overscanAppropriateFlag; }
-  Void setOverscanAppropriateFlag(Bool i) { m_overscanAppropriateFlag = i; }
-
-  Bool getVideoSignalTypePresentFlag() { return m_videoSignalTypePresentFlag; }
-  Void setVideoSignalTypePresentFlag(Bool i) { m_videoSignalTypePresentFlag = i; }
-
-  Int getVideoFormat() { return m_videoFormat; }
-  Void setVideoFormat(Int i) { m_videoFormat = i; }
-
-  Bool getVideoFullRangeFlag() { return m_videoFullRangeFlag; }
-  Void setVideoFullRangeFlag(Bool i) { m_videoFullRangeFlag = i; }
-
-  Bool getColourDescriptionPresentFlag() { return m_colourDescriptionPresentFlag; }
-  Void setColourDescriptionPresentFlag(Bool i) { m_colourDescriptionPresentFlag = i; }
-
-  Int getColourPrimaries() { return m_colourPrimaries; }
-  Void setColourPrimaries(Int i) { m_colourPrimaries = i; }
-
-  Int getTransferCharacteristics() { return m_transferCharacteristics; }
-  Void setTransferCharacteristics(Int i) { m_transferCharacteristics = i; }
-
-  Int getMatrixCoefficients() { return m_matrixCoefficients; }
-  Void setMatrixCoefficients(Int i) { m_matrixCoefficients = i; }
-
-  Bool getChromaLocInfoPresentFlag() { return m_chromaLocInfoPresentFlag; }
-  Void setChromaLocInfoPresentFlag(Bool i) { m_chromaLocInfoPresentFlag = i; }
-
-  Int getChromaSampleLocTypeTopField() { return m_chromaSampleLocTypeTopField; }
-  Void setChromaSampleLocTypeTopField(Int i) { m_chromaSampleLocTypeTopField = i; }
-
-  Int getChromaSampleLocTypeBottomField() { return m_chromaSampleLocTypeBottomField; }
-  Void setChromaSampleLocTypeBottomField(Int i) { m_chromaSampleLocTypeBottomField = i; }
-
-  Bool getNeutralChromaIndicationFlag() { return m_neutralChromaIndicationFlag; }
-  Void setNeutralChromaIndicationFlag(Bool i) { m_neutralChromaIndicationFlag = i; }
-
-  Bool getFieldSeqFlag() { return m_fieldSeqFlag; }
-  Void setFieldSeqFlag(Bool i) { m_fieldSeqFlag = i; }
-
-  Bool getFrameFieldInfoPresentFlag() { return m_frameFieldInfoPresentFlag; }
-  Void setFrameFieldInfoPresentFlag(Bool i) { m_frameFieldInfoPresentFlag = i; }
-
-  Window& getDefaultDisplayWindow()                              { return m_defaultDisplayWindow;                }
-  Void    setDefaultDisplayWindow(Window& defaultDisplayWindow ) { m_defaultDisplayWindow = defaultDisplayWindow; }
-
-  Bool getHrdParametersPresentFlag() { return m_hrdParametersPresentFlag; }
-  Void setHrdParametersPresentFlag(Bool i) { m_hrdParametersPresentFlag = i; }
-
-  Bool getBitstreamRestrictionFlag() { return m_bitstreamRestrictionFlag; }
-  Void setBitstreamRestrictionFlag(Bool i) { m_bitstreamRestrictionFlag = i; }
-
-  Bool getTilesFixedStructureFlag() { return m_tilesFixedStructureFlag; }
-  Void setTilesFixedStructureFlag(Bool i) { m_tilesFixedStructureFlag = i; }
-
-  Bool getMotionVectorsOverPicBoundariesFlag() { return m_motionVectorsOverPicBoundariesFlag; }
-  Void setMotionVectorsOverPicBoundariesFlag(Bool i) { m_motionVectorsOverPicBoundariesFlag = i; }
-
-  Bool getRestrictedRefPicListsFlag() { return m_restrictedRefPicListsFlag; }
-  Void setRestrictedRefPicListsFlag(Bool b) { m_restrictedRefPicListsFlag = b; }
-
-  Int getMinSpatialSegmentationIdc() { return m_minSpatialSegmentationIdc; }
-  Void setMinSpatialSegmentationIdc(Int i) { m_minSpatialSegmentationIdc = i; }
-  Int getMaxBytesPerPicDenom() { return m_maxBytesPerPicDenom; }
-  Void setMaxBytesPerPicDenom(Int i) { m_maxBytesPerPicDenom = i; }
-
-  Int getMaxBitsPerMinCuDenom() { return m_maxBitsPerMinCuDenom; }
-  Void setMaxBitsPerMinCuDenom(Int i) { m_maxBitsPerMinCuDenom = i; }
-
-  Int getLog2MaxMvLengthHorizontal() { return m_log2MaxMvLengthHorizontal; }
-  Void setLog2MaxMvLengthHorizontal(Int i) { m_log2MaxMvLengthHorizontal = i; }
-
-  Int getLog2MaxMvLengthVertical() { return m_log2MaxMvLengthVertical; }
-  Void setLog2MaxMvLengthVertical(Int i) { m_log2MaxMvLengthVertical = i; }
-
-  TComHRD* getHrdParameters                 ()             { return &m_hrdParameters; }
-  TimingInfo* getTimingInfo() { return &m_timingInfo; }
-#if H_MV
-  Void inferVideoSignalInfo( TComVPS* vps, Int layerIdCurr );
+  virtual           ~TComVUI() {}
+
+  Bool              getAspectRatioInfoPresentFlag() const                  { return m_aspectRatioInfoPresentFlag;           }
+  Void              setAspectRatioInfoPresentFlag(Bool i)                  { m_aspectRatioInfoPresentFlag = i;              }
+
+  Int               getAspectRatioIdc() const                              { return m_aspectRatioIdc;                       }
+  Void              setAspectRatioIdc(Int i)                               { m_aspectRatioIdc = i;                          }
+
+  Int               getSarWidth() const                                    { return m_sarWidth;                             }
+  Void              setSarWidth(Int i)                                     { m_sarWidth = i;                                }
+
+  Int               getSarHeight() const                                   { return m_sarHeight;                            }
+  Void              setSarHeight(Int i)                                    { m_sarHeight = i;                               }
+
+  Bool              getOverscanInfoPresentFlag() const                     { return m_overscanInfoPresentFlag;              }
+  Void              setOverscanInfoPresentFlag(Bool i)                     { m_overscanInfoPresentFlag = i;                 }
+
+  Bool              getOverscanAppropriateFlag() const                     { return m_overscanAppropriateFlag;              }
+  Void              setOverscanAppropriateFlag(Bool i)                     { m_overscanAppropriateFlag = i;                 }
+
+  Bool              getVideoSignalTypePresentFlag() const                  { return m_videoSignalTypePresentFlag;           }
+  Void              setVideoSignalTypePresentFlag(Bool i)                  { m_videoSignalTypePresentFlag = i;              }
+
+  Int               getVideoFormat() const                                 { return m_videoFormat;                          }
+  Void              setVideoFormat(Int i)                                  { m_videoFormat = i;                             }
+
+  Bool              getVideoFullRangeFlag() const                          { return m_videoFullRangeFlag;                   }
+  Void              setVideoFullRangeFlag(Bool i)                          { m_videoFullRangeFlag = i;                      }
+
+  Bool              getColourDescriptionPresentFlag() const                { return m_colourDescriptionPresentFlag;         }
+  Void              setColourDescriptionPresentFlag(Bool i)                { m_colourDescriptionPresentFlag = i;            }
+
+  Int               getColourPrimaries() const                             { return m_colourPrimaries;                      }
+  Void              setColourPrimaries(Int i)                              { m_colourPrimaries = i;                         }
+
+  Int               getTransferCharacteristics() const                     { return m_transferCharacteristics;              }
+  Void              setTransferCharacteristics(Int i)                      { m_transferCharacteristics = i;                 }
+
+  Int               getMatrixCoefficients() const                          { return m_matrixCoefficients;                   }
+  Void              setMatrixCoefficients(Int i)                           { m_matrixCoefficients = i;                      }
+
+  Bool              getChromaLocInfoPresentFlag() const                    { return m_chromaLocInfoPresentFlag;             }
+  Void              setChromaLocInfoPresentFlag(Bool i)                    { m_chromaLocInfoPresentFlag = i;                }
+
+  Int               getChromaSampleLocTypeTopField() const                 { return m_chromaSampleLocTypeTopField;          }
+  Void              setChromaSampleLocTypeTopField(Int i)                  { m_chromaSampleLocTypeTopField = i;             }
+
+  Int               getChromaSampleLocTypeBottomField() const              { return m_chromaSampleLocTypeBottomField;       }
+  Void              setChromaSampleLocTypeBottomField(Int i)               { m_chromaSampleLocTypeBottomField = i;          }
+
+  Bool              getNeutralChromaIndicationFlag() const                 { return m_neutralChromaIndicationFlag;          }
+  Void              setNeutralChromaIndicationFlag(Bool i)                 { m_neutralChromaIndicationFlag = i;             }
+
+  Bool              getFieldSeqFlag() const                                { return m_fieldSeqFlag;                         }
+  Void              setFieldSeqFlag(Bool i)                                { m_fieldSeqFlag = i;                            }
+
+  Bool              getFrameFieldInfoPresentFlag() const                   { return m_frameFieldInfoPresentFlag;            }
+  Void              setFrameFieldInfoPresentFlag(Bool i)                   { m_frameFieldInfoPresentFlag = i;               }
+
+  Window&           getDefaultDisplayWindow()                              { return m_defaultDisplayWindow;                 }
+  const Window&     getDefaultDisplayWindow() const                        { return m_defaultDisplayWindow;                 }
+  Void              setDefaultDisplayWindow(Window& defaultDisplayWindow ) { m_defaultDisplayWindow = defaultDisplayWindow; }
+
+  Bool              getHrdParametersPresentFlag() const                    { return m_hrdParametersPresentFlag;             }
+  Void              setHrdParametersPresentFlag(Bool i)                    { m_hrdParametersPresentFlag = i;                }
+
+  Bool              getBitstreamRestrictionFlag() const                    { return m_bitstreamRestrictionFlag;             }
+  Void              setBitstreamRestrictionFlag(Bool i)                    { m_bitstreamRestrictionFlag = i;                }
+
+  Bool              getTilesFixedStructureFlag() const                     { return m_tilesFixedStructureFlag;              }
+  Void              setTilesFixedStructureFlag(Bool i)                     { m_tilesFixedStructureFlag = i;                 }
+
+  Bool              getMotionVectorsOverPicBoundariesFlag() const          { return m_motionVectorsOverPicBoundariesFlag;   }
+  Void              setMotionVectorsOverPicBoundariesFlag(Bool i)          { m_motionVectorsOverPicBoundariesFlag = i;      }
+
+  Bool              getRestrictedRefPicListsFlag() const                   { return m_restrictedRefPicListsFlag;            }
+  Void              setRestrictedRefPicListsFlag(Bool b)                   { m_restrictedRefPicListsFlag = b;               }
+
+  Int               getMinSpatialSegmentationIdc() const                   { return m_minSpatialSegmentationIdc;            }
+  Void              setMinSpatialSegmentationIdc(Int i)                    { m_minSpatialSegmentationIdc = i;               }
+
+  Int               getMaxBytesPerPicDenom() const                         { return m_maxBytesPerPicDenom;                  }
+  Void              setMaxBytesPerPicDenom(Int i)                          { m_maxBytesPerPicDenom = i;                     }
+
+  Int               getMaxBitsPerMinCuDenom() const                        { return m_maxBitsPerMinCuDenom;                 }
+  Void              setMaxBitsPerMinCuDenom(Int i)                         { m_maxBitsPerMinCuDenom = i;                    }
+
+  Int               getLog2MaxMvLengthHorizontal() const                   { return m_log2MaxMvLengthHorizontal;            }
+  Void              setLog2MaxMvLengthHorizontal(Int i)                    { m_log2MaxMvLengthHorizontal = i;               }
+
+  Int               getLog2MaxMvLengthVertical() const                     { return m_log2MaxMvLengthVertical;              }
+  Void              setLog2MaxMvLengthVertical(Int i)                      { m_log2MaxMvLengthVertical = i;                 }
+
+  TComHRD*          getHrdParameters()                                     { return &m_hrdParameters;                       }
+  const TComHRD*    getHrdParameters()  const                              { return &m_hrdParameters;                       }
+
+  TimingInfo*       getTimingInfo()                                        { return &m_timingInfo;                          }
+  const TimingInfo* getTimingInfo() const                                  { return &m_timingInfo;                          }
+#if NH_MV
+  Void              inferVideoSignalInfo( const TComVPS* vps, Int layerIdCurr );
 #endif
 };
 
-#if H_3D
+/// SPS RExt class
+class TComSPSRExt // Names aligned to text specification
+{
+private:
+  Bool             m_transformSkipRotationEnabledFlag;
+  Bool             m_transformSkipContextEnabledFlag;
+  Bool             m_rdpcmEnabledFlag[NUMBER_OF_RDPCM_SIGNALLING_MODES];
+  Bool             m_extendedPrecisionProcessingFlag;
+  Bool             m_intraSmoothingDisabledFlag;
+  Bool             m_highPrecisionOffsetsEnabledFlag;
+  Bool             m_persistentRiceAdaptationEnabledFlag;
+  Bool             m_cabacBypassAlignmentEnabledFlag;
+
+public:
+  TComSPSRExt();
+
+  Bool settingsDifferFromDefaults() const
+  {
+    return getTransformSkipRotationEnabledFlag()
+        || getTransformSkipContextEnabledFlag()
+        || getRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT)
+        || getRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT)
+        || getExtendedPrecisionProcessingFlag()
+        || getIntraSmoothingDisabledFlag()
+        || getHighPrecisionOffsetsEnabledFlag()
+        || getPersistentRiceAdaptationEnabledFlag()
+        || getCabacBypassAlignmentEnabledFlag();
+  }
+
+
+  Bool getTransformSkipRotationEnabledFlag() const                                     { return m_transformSkipRotationEnabledFlag;     }
+  Void setTransformSkipRotationEnabledFlag(const Bool value)                           { m_transformSkipRotationEnabledFlag = value;    }
+
+  Bool getTransformSkipContextEnabledFlag() const                                      { return m_transformSkipContextEnabledFlag;      }
+  Void setTransformSkipContextEnabledFlag(const Bool value)                            { m_transformSkipContextEnabledFlag = value;     }
+
+  Bool getRdpcmEnabledFlag(const RDPCMSignallingMode signallingMode) const             { return m_rdpcmEnabledFlag[signallingMode];     }
+  Void setRdpcmEnabledFlag(const RDPCMSignallingMode signallingMode, const Bool value) { m_rdpcmEnabledFlag[signallingMode] = value;    }
+
+  Bool getExtendedPrecisionProcessingFlag() const                                      { return m_extendedPrecisionProcessingFlag;      }
+  Void setExtendedPrecisionProcessingFlag(Bool value)                                  { m_extendedPrecisionProcessingFlag = value;     }
+
+  Bool getIntraSmoothingDisabledFlag() const                                           { return m_intraSmoothingDisabledFlag;           }
+  Void setIntraSmoothingDisabledFlag(Bool bValue)                                      { m_intraSmoothingDisabledFlag=bValue;           }
+
+  Bool getHighPrecisionOffsetsEnabledFlag() const                                      { return m_highPrecisionOffsetsEnabledFlag;      }
+  Void setHighPrecisionOffsetsEnabledFlag(Bool value)                                  { m_highPrecisionOffsetsEnabledFlag = value;     }
+
+  Bool getPersistentRiceAdaptationEnabledFlag() const                                  { return m_persistentRiceAdaptationEnabledFlag;  }
+  Void setPersistentRiceAdaptationEnabledFlag(const Bool value)                        { m_persistentRiceAdaptationEnabledFlag = value; }
+
+  Bool getCabacBypassAlignmentEnabledFlag() const                                      { return m_cabacBypassAlignmentEnabledFlag;      }
+  Void setCabacBypassAlignmentEnabledFlag(const Bool value)                            { m_cabacBypassAlignmentEnabledFlag = value;     }
+};
+
+
+#if NH_3D
 class TComSps3dExtension
 {
@@ -1616,46 +1704,45 @@
   }
 
-  Void setIvMvPredFlag( Int d, Bool flag ) { m_ivMvPredFlag[d] = flag; } 
-  Bool getIvMvPredFlag( Int d ) { return m_ivMvPredFlag[d]; } 
-
-  Void setIvMvScalingFlag( Int d, Bool flag ) { m_ivMvScalingFlag[d] = flag; } 
-  Bool getIvMvScalingFlag( Int d ) { return m_ivMvScalingFlag[d]; } 
-
-  Void setLog2SubPbSizeMinus3( Int d, Int  val ) { m_log2SubPbSizeMinus3[d] = val; } 
-  Int  getLog2SubPbSizeMinus3( Int d ) { return m_log2SubPbSizeMinus3[d]; } 
-
-  Void setIvResPredFlag( Int d, Bool flag ) { m_ivResPredFlag[d] = flag; } 
-  Bool getIvResPredFlag( Int d ) { return m_ivResPredFlag[d]; } 
-
-  Void setDepthRefinementFlag( Int d, Bool flag ) { m_depthRefinementFlag[d] = flag; } 
-  Bool getDepthRefinementFlag( Int d ) { return m_depthRefinementFlag[d]; } 
-
-  Void setViewSynthesisPredFlag( Int d, Bool flag ) { m_viewSynthesisPredFlag[d] = flag; } 
-  Bool getViewSynthesisPredFlag( Int d ) { return m_viewSynthesisPredFlag[d]; } 
-
-  Void setDepthBasedBlkPartFlag( Int d, Bool flag ) { m_depthBasedBlkPartFlag[d] = flag; } 
-  Bool getDepthBasedBlkPartFlag( Int d ) { return m_depthBasedBlkPartFlag[d]; } 
-
-  Void setMpiFlag( Int d, Bool flag ) { m_mpiFlag[d] = flag; } 
-  Bool getMpiFlag( Int d ) { return m_mpiFlag[d]; } 
-
-  Void setLog2MpiSubPbSizeMinus3( Int d, Int  val ) { m_log2MpiSubPbSizeMinus3[d] = val; } 
-  Int  getLog2MpiSubPbSizeMinus3( Int d ) { return m_log2MpiSubPbSizeMinus3[d]; } 
-
-  Void setIntraContourFlag( Int d, Bool flag ) { m_intraContourFlag[d] = flag; } 
-  Bool getIntraContourFlag( Int d ) { return m_intraContourFlag[d]; } 
-
-  Void setIntraSdcWedgeFlag( Int d, Bool flag ) { m_intraSdcWedgeFlag[d] = flag; } 
-  Bool getIntraSdcWedgeFlag( Int d ) { return m_intraSdcWedgeFlag[d]; } 
-
-  Void setQtPredFlag( Int d, Bool flag ) { m_qtPredFlag[d] = flag; } 
-  Bool getQtPredFlag( Int d ) { return m_qtPredFlag[d]; } 
-
-  Void setInterSdcFlag( Int d, Bool flag ) { m_interSdcFlag[d] = flag; } 
-  Bool getInterSdcFlag( Int d ) { return m_interSdcFlag[d]; } 
-
-  Void setDepthIntraSkipFlag( Int d, Bool flag ) { m_depthIntraSkipFlag[d] = flag; } 
-  Bool getDepthIntraSkipFlag( Int d ) { return m_depthIntraSkipFlag[d]; } 
-
+  Void          setIvMvPredFlag( Int d, Bool flag )         { m_ivMvPredFlag[d] = flag;             }
+  Bool          getIvMvPredFlag( Int d ) const              { return m_ivMvPredFlag[d];             }
+
+  Void          setIvMvScalingFlag( Int d, Bool flag )      { m_ivMvScalingFlag[d] = flag;          }
+  Bool          getIvMvScalingFlag( Int d ) const           { return m_ivMvScalingFlag[d];          }
+
+  Void          setLog2SubPbSizeMinus3( Int d, Int  val )   { m_log2SubPbSizeMinus3[d] = val;       }
+  Int           getLog2SubPbSizeMinus3( Int d ) const       { return m_log2SubPbSizeMinus3[d];      }
+
+  Void          setIvResPredFlag( Int d, Bool flag )        { m_ivResPredFlag[d] = flag;            }
+  Bool          getIvResPredFlag( Int d ) const             { return m_ivResPredFlag[d];            }
+
+  Void          setDepthRefinementFlag( Int d, Bool flag )  { m_depthRefinementFlag[d] = flag;      }
+  Bool          getDepthRefinementFlag( Int d ) const       { return m_depthRefinementFlag[d];      }
+
+  Void          setViewSynthesisPredFlag( Int d, Bool flag ) { m_viewSynthesisPredFlag[d] = flag;   }
+  Bool          getViewSynthesisPredFlag( Int d ) const     { return m_viewSynthesisPredFlag[d];    }
+
+  Void          setDepthBasedBlkPartFlag( Int d, Bool flag ) { m_depthBasedBlkPartFlag[d] = flag;   }
+  Bool          getDepthBasedBlkPartFlag( Int d ) const     { return m_depthBasedBlkPartFlag[d];    }
+
+  Void          setMpiFlag( Int d, Bool flag )              { m_mpiFlag[d] = flag;                  }
+  Bool          getMpiFlag( Int d ) const                   { return m_mpiFlag[d];                  }
+
+  Void          setLog2MpiSubPbSizeMinus3( Int d, Int  val ) { m_log2MpiSubPbSizeMinus3[d] = val;   }
+  Int           getLog2MpiSubPbSizeMinus3( Int d ) const    { return m_log2MpiSubPbSizeMinus3[d];   }
+
+  Void          setIntraContourFlag( Int d, Bool flag )     { m_intraContourFlag[d] = flag;         }
+  Bool          getIntraContourFlag( Int d ) const          { return m_intraContourFlag[d];         }
+
+  Void          setIntraSdcWedgeFlag( Int d, Bool flag )    { m_intraSdcWedgeFlag[d] = flag;        }
+  Bool          getIntraSdcWedgeFlag( Int d ) const         { return m_intraSdcWedgeFlag[d];        }
+
+  Void          setQtPredFlag( Int d, Bool flag )           { m_qtPredFlag[d] = flag;               }
+  Bool          getQtPredFlag( Int d ) const                { return m_qtPredFlag[d];               }
+
+  Void          setInterSdcFlag( Int d, Bool flag )         { m_interSdcFlag[d] = flag;             }
+  Bool          getInterSdcFlag( Int d ) const              { return m_interSdcFlag[d];             }
+
+  Void          setDepthIntraSkipFlag( Int d, Bool flag )   { m_depthIntraSkipFlag[d] = flag;       }
+  Bool          getDepthIntraSkipFlag( Int d ) const        { return m_depthIntraSkipFlag[d];       }
 private:
 
@@ -1678,338 +1765,426 @@
 #endif
 
+
 /// SPS class
 class TComSPS
 {
 private:
-  Int         m_SPSId;
-  Int         m_VPSId;
-  Int         m_chromaFormatIdc;
-
-  UInt        m_uiMaxTLayers;           // maximum number of temporal layers
+  Int              m_SPSId;
+  Int              m_VPSId;
+  ChromaFormat     m_chromaFormatIdc;
+
+  UInt             m_uiMaxTLayers;           // maximum number of temporal layers
 
   // Structure
-  UInt        m_picWidthInLumaSamples;
-  UInt        m_picHeightInLumaSamples;
+  UInt             m_picWidthInLumaSamples;
+  UInt             m_picHeightInLumaSamples;
+
+  Int              m_log2MinCodingBlockSize;
+  Int              m_log2DiffMaxMinCodingBlockSize;
+  UInt             m_uiMaxCUWidth;
+  UInt             m_uiMaxCUHeight;
+  UInt             m_uiMaxTotalCUDepth; ///< Total CU depth, relative to the smallest possible transform block size.
+
+  Window           m_conformanceWindow;
+
+  TComRPSList      m_RPSList;
+  Bool             m_bLongTermRefsPresent;
+  Bool             m_TMVPFlagsPresent;
+  Int              m_numReorderPics[MAX_TLAYER];
+
+  // Tool list
+  UInt             m_uiQuadtreeTULog2MaxSize;
+  UInt             m_uiQuadtreeTULog2MinSize;
+  UInt             m_uiQuadtreeTUMaxDepthInter;
+  UInt             m_uiQuadtreeTUMaxDepthIntra;
+  Bool             m_usePCM;
+  UInt             m_pcmLog2MaxSize;
+  UInt             m_uiPCMLog2MinSize;
+  Bool             m_useAMP;
+
+  // Parameter
+  BitDepths        m_bitDepths;
+  Int              m_qpBDOffset[MAX_NUM_CHANNEL_TYPE];
+  Int              m_pcmBitDepths[MAX_NUM_CHANNEL_TYPE];
+  Bool             m_bPCMFilterDisableFlag;
+
+  UInt             m_uiBitsForPOC;
+  UInt             m_numLongTermRefPicSPS;
+  UInt             m_ltRefPicPocLsbSps[MAX_NUM_LONG_TERM_REF_PICS];
+  Bool             m_usedByCurrPicLtSPSFlag[MAX_NUM_LONG_TERM_REF_PICS];
+  // Max physical transform size
+  UInt             m_uiMaxTrSize;
+
+  Bool             m_bUseSAO;
+
+  Bool             m_bTemporalIdNestingFlag; // temporal_id_nesting_flag
+
+  Bool             m_scalingListEnabledFlag;
+  Bool             m_scalingListPresentFlag;
+  TComScalingList  m_scalingList;
+  UInt             m_uiMaxDecPicBuffering[MAX_TLAYER];
+  UInt             m_uiMaxLatencyIncrease[MAX_TLAYER];  // Really max latency increase plus 1 (value 0 expresses no limit)
+
+  Bool             m_useStrongIntraSmoothing;
+
+  Bool             m_vuiParametersPresentFlag;
+  TComVUI          m_vuiParameters;
+
+  TComSPSRExt      m_spsRangeExtension;
+
+  static const Int m_winUnitX[NUM_CHROMA_FORMAT];
+  static const Int m_winUnitY[NUM_CHROMA_FORMAT];
+  TComPTL          m_pcPTL;
+
+#if O0043_BEST_EFFORT_DECODING
+  UInt             m_forceDecodeBitDepth; // 0 = do not force the decoder's bit depth, other = force the decoder's bit depth to this value (best effort decoding)
+#endif
+#if NH_MV
+  TComVPS*         m_pcVPS; 
+  // SPS           
+  Int              m_spsMaxSubLayersMinus1;
+  Int              m_spsExtOrMaxSubLayersMinus1;
+  Bool             m_spsExtensionPresentFlag; 
+                   
+  Bool             m_spsRangeExtensionsFlag;
+  Bool             m_spsMultilayerExtensionFlag;
+
+  Bool             m_sps3dExtensionFlag;
+  Int              m_spsExtension5bits;
+
+  Bool             m_spsInferScalingListFlag;
+  Int              m_spsScalingListRefLayerId;
+  Bool             m_updateRepFormatFlag;
+  Int              m_spsRepFormatIdx;
+  // SPS Extension 
+  Bool             m_interViewMvVertConstraintFlag;
+#endif
+#if NH_3D
+  TComSps3dExtension m_sps3dExtension; 
+  Int              m_aaiCodedScale [2][MAX_NUM_LAYERS];
+  Int              m_aaiCodedOffset[2][MAX_NUM_LAYERS];
+#endif             
+#if NH_MV           
+  Int              m_layerId; 
+#endif
+
+public:
+                         TComSPS();
+  virtual                ~TComSPS();
+#if O0043_BEST_EFFORT_DECODING
+  Void                   setForceDecodeBitDepth(UInt bitDepth)                                           { m_forceDecodeBitDepth = bitDepth;                                    }
+  UInt                   getForceDecodeBitDepth()        const                                           { return m_forceDecodeBitDepth;                                        }
+#endif
+
+  Int                    getVPSId() const                                                                { return m_VPSId;                                                      }
+  Void                   setVPSId(Int i)                                                                 { m_VPSId = i;                                                         }
+  Int                    getSPSId() const                                                                { return m_SPSId;                                                      }
+  Void                   setSPSId(Int i)                                                                 { m_SPSId = i;                                                         }
+  ChromaFormat           getChromaFormatIdc () const                                                     { return m_chromaFormatIdc;                                            }
+  Void                   setChromaFormatIdc (ChromaFormat i)                                             { m_chromaFormatIdc = i;                                               }
+
+  static Int             getWinUnitX (Int chromaFormatIdc)                                               { assert (chromaFormatIdc >= 0 && chromaFormatIdc < NUM_CHROMA_FORMAT); return m_winUnitX[chromaFormatIdc]; }
+  static Int             getWinUnitY (Int chromaFormatIdc)                                               { assert (chromaFormatIdc >= 0 && chromaFormatIdc < NUM_CHROMA_FORMAT); return m_winUnitY[chromaFormatIdc]; }
+
+  // structure
+  Void                   setPicWidthInLumaSamples( UInt u )                                              { m_picWidthInLumaSamples = u;                                         }
+  UInt                   getPicWidthInLumaSamples() const                                                { return  m_picWidthInLumaSamples;                                     }
+  Void                   setPicHeightInLumaSamples( UInt u )                                             { m_picHeightInLumaSamples = u;                                        }
+  UInt                   getPicHeightInLumaSamples() const                                               { return  m_picHeightInLumaSamples;                                    }
+
+  Window&                getConformanceWindow()                                                          { return  m_conformanceWindow;                                         }
+  const Window&          getConformanceWindow() const                                                    { return  m_conformanceWindow;                                         }
+  Void                   setConformanceWindow(Window& conformanceWindow )                                { m_conformanceWindow = conformanceWindow;                             }
+
+  UInt                   getNumLongTermRefPicSPS() const                                                 { return m_numLongTermRefPicSPS;                                       }
+  Void                   setNumLongTermRefPicSPS(UInt val)                                               { m_numLongTermRefPicSPS = val;                                        }
+
+  UInt                   getLtRefPicPocLsbSps(UInt index) const                                          { assert( index < MAX_NUM_LONG_TERM_REF_PICS ); return m_ltRefPicPocLsbSps[index]; }
+  Void                   setLtRefPicPocLsbSps(UInt index, UInt val)                                      { assert( index < MAX_NUM_LONG_TERM_REF_PICS ); m_ltRefPicPocLsbSps[index] = val;  }
+
+  Bool                   getUsedByCurrPicLtSPSFlag(Int i) const                                          { assert( i < MAX_NUM_LONG_TERM_REF_PICS ); return m_usedByCurrPicLtSPSFlag[i];    }
+  Void                   setUsedByCurrPicLtSPSFlag(Int i, Bool x)                                        { assert( i < MAX_NUM_LONG_TERM_REF_PICS ); m_usedByCurrPicLtSPSFlag[i] = x;       }
+
+  Int                    getLog2MinCodingBlockSize() const                                               { return m_log2MinCodingBlockSize;                                     }
+  Void                   setLog2MinCodingBlockSize(Int val)                                              { m_log2MinCodingBlockSize = val;                                      }
+  Int                    getLog2DiffMaxMinCodingBlockSize() const                                        { return m_log2DiffMaxMinCodingBlockSize;                              }
+  Void                   setLog2DiffMaxMinCodingBlockSize(Int val)                                       { m_log2DiffMaxMinCodingBlockSize = val;                               }
+
+  Void                   setMaxCUWidth( UInt u )                                                         { m_uiMaxCUWidth = u;                                                  }
+  UInt                   getMaxCUWidth() const                                                           { return  m_uiMaxCUWidth;                                              }
+  Void                   setMaxCUHeight( UInt u )                                                        { m_uiMaxCUHeight = u;                                                 }
+  UInt                   getMaxCUHeight() const                                                          { return  m_uiMaxCUHeight;                                             }
+  Void                   setMaxTotalCUDepth( UInt u )                                                    { m_uiMaxTotalCUDepth = u;                                             }
+  UInt                   getMaxTotalCUDepth() const                                                      { return  m_uiMaxTotalCUDepth;                                         }
+  Void                   setUsePCM( Bool b )                                                             { m_usePCM = b;                                                        }
+  Bool                   getUsePCM() const                                                               { return m_usePCM;                                                     }
+  Void                   setPCMLog2MaxSize( UInt u )                                                     { m_pcmLog2MaxSize = u;                                                }
+  UInt                   getPCMLog2MaxSize() const                                                       { return  m_pcmLog2MaxSize;                                            }
+  Void                   setPCMLog2MinSize( UInt u )                                                     { m_uiPCMLog2MinSize = u;                                              }
+  UInt                   getPCMLog2MinSize() const                                                       { return  m_uiPCMLog2MinSize;                                          }
+  Void                   setBitsForPOC( UInt u )                                                         { m_uiBitsForPOC = u;                                                  }
+  UInt                   getBitsForPOC() const                                                           { return m_uiBitsForPOC;                                               }
+  Bool                   getUseAMP() const                                                               { return m_useAMP;                                                     }
+  Void                   setUseAMP( Bool b )                                                             { m_useAMP = b;                                                        }
+  Void                   setQuadtreeTULog2MaxSize( UInt u )                                              { m_uiQuadtreeTULog2MaxSize = u;                                       }
+  UInt                   getQuadtreeTULog2MaxSize() const                                                { return m_uiQuadtreeTULog2MaxSize;                                    }
+  Void                   setQuadtreeTULog2MinSize( UInt u )                                              { m_uiQuadtreeTULog2MinSize = u;                                       }
+  UInt                   getQuadtreeTULog2MinSize() const                                                { return m_uiQuadtreeTULog2MinSize;                                    }
+  Void                   setQuadtreeTUMaxDepthInter( UInt u )                                            { m_uiQuadtreeTUMaxDepthInter = u;                                     }
+  Void                   setQuadtreeTUMaxDepthIntra( UInt u )                                            { m_uiQuadtreeTUMaxDepthIntra = u;                                     }
+  UInt                   getQuadtreeTUMaxDepthInter() const                                              { return m_uiQuadtreeTUMaxDepthInter;                                  }
+  UInt                   getQuadtreeTUMaxDepthIntra() const                                              { return m_uiQuadtreeTUMaxDepthIntra;                                  }
+  Void                   setNumReorderPics(Int i, UInt tlayer)                                           { m_numReorderPics[tlayer] = i;                                        }
+  Int                    getNumReorderPics(UInt tlayer) const                                            { return m_numReorderPics[tlayer];                                     }
+  Void                   createRPSList( Int numRPS );
+  const TComRPSList*     getRPSList() const                                                              { return &m_RPSList;                                                   }
+  TComRPSList*           getRPSList()                                                                    { return &m_RPSList;                                                   }
+  Bool                   getLongTermRefsPresent() const                                                  { return m_bLongTermRefsPresent;                                       }
+  Void                   setLongTermRefsPresent(Bool b)                                                  { m_bLongTermRefsPresent=b;                                            }
+  Bool                   getTMVPFlagsPresent() const                                                     { return m_TMVPFlagsPresent;                                           }
+  Void                   setTMVPFlagsPresent(Bool b)                                                     { m_TMVPFlagsPresent=b;                                                }
+  // physical transform
+  Void                   setMaxTrSize( UInt u )                                                          { m_uiMaxTrSize = u;                                                   }
+  UInt                   getMaxTrSize() const                                                            { return  m_uiMaxTrSize;                                               }
+
+  // Bit-depth
+  Int                    getBitDepth(ChannelType type) const                                             { return m_bitDepths.recon[type];                                      }
+  Void                   setBitDepth(ChannelType type, Int u )                                           { m_bitDepths.recon[type] = u;                                         }
+#if O0043_BEST_EFFORT_DECODING
+  Int                    getStreamBitDepth(ChannelType type) const                                       { return m_bitDepths.stream[type];                                     }
+  Void                   setStreamBitDepth(ChannelType type, Int u )                                     { m_bitDepths.stream[type] = u;                                        }
+#endif
+  const BitDepths&       getBitDepths() const                                                            { return m_bitDepths;                                                  }
+  Int                    getMaxLog2TrDynamicRange(ChannelType channelType) const                         { return getSpsRangeExtension().getExtendedPrecisionProcessingFlag() ? std::max<Int>(15, Int(m_bitDepths.recon[channelType] + 6)) : 15; }
+
+  Int                    getDifferentialLumaChromaBitDepth() const                                       { return Int(m_bitDepths.recon[CHANNEL_TYPE_LUMA]) - Int(m_bitDepths.recon[CHANNEL_TYPE_CHROMA]); }
+  Int                    getQpBDOffset(ChannelType type) const                                           { return m_qpBDOffset[type];                                           }
+  Void                   setQpBDOffset(ChannelType type, Int i)                                          { m_qpBDOffset[type] = i;                                              }
+
+  Void                   setUseSAO(Bool bVal)                                                            { m_bUseSAO = bVal;                                                    }
+  Bool                   getUseSAO() const                                                               { return m_bUseSAO;                                                    }
+
+  UInt                   getMaxTLayers() const                                                           { return m_uiMaxTLayers; }
+  Void                   setMaxTLayers( UInt uiMaxTLayers )                                              { assert( uiMaxTLayers <= MAX_TLAYER ); m_uiMaxTLayers = uiMaxTLayers; }
+
+  Bool                   getTemporalIdNestingFlag() const                                                { return m_bTemporalIdNestingFlag;                                     }
+  Void                   setTemporalIdNestingFlag( Bool bValue )                                         { m_bTemporalIdNestingFlag = bValue;                                   }
+  UInt                   getPCMBitDepth(ChannelType type) const                                          { return m_pcmBitDepths[type];                                         }
+  Void                   setPCMBitDepth(ChannelType type, UInt u)                                        { m_pcmBitDepths[type] = u;                                            }
+  Void                   setPCMFilterDisableFlag( Bool bValue )                                          { m_bPCMFilterDisableFlag = bValue;                                    }
+  Bool                   getPCMFilterDisableFlag() const                                                 { return m_bPCMFilterDisableFlag;                                      }
+
+  Bool                   getScalingListFlag() const                                                      { return m_scalingListEnabledFlag;                                     }
+  Void                   setScalingListFlag( Bool b )                                                    { m_scalingListEnabledFlag  = b;                                       }
+  Bool                   getScalingListPresentFlag() const                                               { return m_scalingListPresentFlag;                                     }
+  Void                   setScalingListPresentFlag( Bool b )                                             { m_scalingListPresentFlag  = b;                                       }
+  Void                   setScalingList( TComScalingList *scalingList);
+  TComScalingList&       getScalingList()                                                                { return m_scalingList;                                                }
+  const TComScalingList& getScalingList() const                                                          { return m_scalingList;                                                }
+  UInt                   getMaxDecPicBuffering(UInt tlayer) const                                        { return m_uiMaxDecPicBuffering[tlayer];                               }
+  Void                   setMaxDecPicBuffering( UInt ui, UInt tlayer )                                   { assert(tlayer < MAX_TLAYER); m_uiMaxDecPicBuffering[tlayer] = ui;    }
+  UInt                   getMaxLatencyIncrease(UInt tlayer) const                                        { return m_uiMaxLatencyIncrease[tlayer];                               }
+  Void                   setMaxLatencyIncrease( UInt ui , UInt tlayer)                                   { m_uiMaxLatencyIncrease[tlayer] = ui;                                 }
+
+  Void                   setUseStrongIntraSmoothing(Bool bVal)                                           { m_useStrongIntraSmoothing = bVal;                                    }
+  Bool                   getUseStrongIntraSmoothing() const                                              { return m_useStrongIntraSmoothing;                                    }
+
+  Bool                   getVuiParametersPresentFlag() const                                             { return m_vuiParametersPresentFlag;                                   }
+  Void                   setVuiParametersPresentFlag(Bool b)                                             { m_vuiParametersPresentFlag = b;                                      }
+  TComVUI*               getVuiParameters()                                                              { return &m_vuiParameters;                                             }
+  const TComVUI*         getVuiParameters() const                                                        { return &m_vuiParameters;                                             }
+  const TComPTL*         getPTL() const                                                                  { return &m_pcPTL;                                                     }
+  TComPTL*               getPTL()                                                                        { return &m_pcPTL;                                                     }
+
+  const TComSPSRExt&     getSpsRangeExtension() const                                                    { return m_spsRangeExtension;                                          }
+  TComSPSRExt&           getSpsRangeExtension()                                                          { return m_spsRangeExtension;                                          }
+
+  // Sequence parameter set range extension syntax
+  // WAS: getUseResidualRotation and setUseResidualRotation
+  // Now getSpsRangeExtension().getTransformSkipRotationEnabledFlag and getSpsRangeExtension().setTransformSkipRotationEnabledFlag
+
+  // WAS: getUseSingleSignificanceMapContext and setUseSingleSignificanceMapContext
+  // Now: getSpsRangeExtension().getTransformSkipContextEnabledFlag and getSpsRangeExtension().setTransformSkipContextEnabledFlag
+
+  // WAS: getUseResidualDPCM and setUseResidualDPCM
+  // Now: getSpsRangeExtension().getRdpcmEnabledFlag and getSpsRangeExtension().setRdpcmEnabledFlag and
+
+  // WAS: getUseExtendedPrecision and setUseExtendedPrecision
+  // Now: getSpsRangeExtension().getExtendedPrecisionProcessingFlag and getSpsRangeExtension().setExtendedPrecisionProcessingFlag
+
+  // WAS: getDisableIntraReferenceSmoothing and setDisableIntraReferenceSmoothing
+  // Now: getSpsRangeExtension().getIntraSmoothingDisabledFlag and getSpsRangeExtension().setIntraSmoothingDisabledFlag
+
+  // WAS: getUseHighPrecisionPredictionWeighting and setUseHighPrecisionPredictionWeighting
+  // Now: getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag and getSpsRangeExtension().setHighPrecisionOffsetsEnabledFlag
+
+  // WAS: getUseGolombRiceParameterAdaptation and setUseGolombRiceParameterAdaptation
+  // Now: getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag and getSpsRangeExtension().setPersistentRiceAdaptationEnabledFlag
+
+  // WAS: getAlignCABACBeforeBypass and setAlignCABACBeforeBypass
+  // Now: getSpsRangeExtension().getCabacBypassAlignmentEnabledFlag and getSpsRangeExtension().setCabacBypassAlignmentEnabledFlag
+
+
+#if NH_MV
+
+  UInt                   getSpsMaxSubLayersMinus1() const                                                { return ( m_uiMaxTLayers - 1);                                        }
+  Void                   setSpsMaxSubLayersMinus1( UInt val )                                            { setMaxTLayers( val + 1 );                                            }
+
+  Void                   setSpsExtOrMaxSubLayersMinus1( Int  val )                                       { m_spsExtOrMaxSubLayersMinus1 = val;                                  }
+  Int                    getSpsExtOrMaxSubLayersMinus1(  )         const                                 { return m_spsExtOrMaxSubLayersMinus1;                                 }
+  Void                   inferSpsMaxSubLayersMinus1( Bool atPsActivation, TComVPS* vps  );                                                                                      
+                                                                                                                                                                                
+  Bool                   getMultiLayerExtSpsFlag()            const { return ( getLayerId() != 0  &&  getSpsExtOrMaxSubLayersMinus1() == 7 );                                   }
+  Void                   inferSpsMaxDecPicBufferingMinus1( TComVPS* vps, Int targetOptLayerSetIdx, Int currLayerId, Bool encoder );                                             
+                                                                                                                                                                                
+  Void                   setSpsExtensionPresentFlag( Bool flag )                                         { m_spsExtensionPresentFlag = flag;                                    }
+  Bool                   getSpsExtensionPresentFlag( )           const                                   { return m_spsExtensionPresentFlag;                                    }
+                                                                                                                                                                                
+  Void                   setSpsRangeExtensionsFlag( Bool flag )                                          { m_spsRangeExtensionsFlag = flag;                                     }
+  Bool                   getSpsRangeExtensionsFlag(  )                     const                         { return m_spsRangeExtensionsFlag;                                     }
+                                                                                                                                                                                
+  Void                   setSpsMultilayerExtensionFlag( Bool flag )                                      { m_spsMultilayerExtensionFlag = flag;                                 }
+  Bool                   getSpsMultilayerExtensionFlag( )                  const                         { return m_spsMultilayerExtensionFlag;                                 }
+
+  Void                   setSps3dExtensionFlag( Bool flag )                                              { m_sps3dExtensionFlag = flag;                                         }
+  Bool                   getSps3dExtensionFlag(  )                         const                         { return m_sps3dExtensionFlag;                                         }
+                                                                                                                                                                                
+  Void                   setSpsExtension5bits( Int  val )                                                { m_spsExtension5bits = val;                                           }
+  Int                    getSpsExtension5bits(  )                          const                         { return m_spsExtension5bits;                                          }
+                                                                                                                                                                                
+  Void                   setVPS          ( TComVPS* pcVPS )                                              { m_pcVPS = pcVPS;                                                     }
+  TComVPS*               getVPS          ()                 const                                        { return m_pcVPS;                                                      }
+                                                                                                                                                                                
+  Void                   setSpsInferScalingListFlag( Bool flag )                                         { m_spsInferScalingListFlag = flag;                                    }
+  Bool                   getSpsInferScalingListFlag(  )          const                                   { return m_spsInferScalingListFlag;                                    }
+                                                                                                                                                                                
+  Void                   setSpsScalingListRefLayerId( Int  val )                                         { m_spsScalingListRefLayerId = val;                                    }
+  Int                    getSpsScalingListRefLayerId(  )         const                                   { return m_spsScalingListRefLayerId;                                   }
+                                                                                                                                                                                
+  Void                   setUpdateRepFormatFlag( Bool flag )                                             { m_updateRepFormatFlag = flag;                                        }
+  Bool                   getUpdateRepFormatFlag(  )              const                                   { return m_updateRepFormatFlag;                                        }
   
-  Int         m_log2MinCodingBlockSize;
-  Int         m_log2DiffMaxMinCodingBlockSize;
-  UInt        m_uiMaxCUWidth;
-  UInt        m_uiMaxCUHeight;
-  UInt        m_uiMaxCUDepth;
-
-  Window      m_conformanceWindow;
-
-  TComRPSList m_RPSList;
-  Bool        m_bLongTermRefsPresent;
-  Bool        m_TMVPFlagsPresent;
-  Int         m_numReorderPics[MAX_TLAYER];
-  
-  // Tool list
-  UInt        m_uiQuadtreeTULog2MaxSize;
-  UInt        m_uiQuadtreeTULog2MinSize;
-  UInt        m_uiQuadtreeTUMaxDepthInter;
-  UInt        m_uiQuadtreeTUMaxDepthIntra;
-  Bool        m_usePCM;
-  UInt        m_pcmLog2MaxSize;
-  UInt        m_uiPCMLog2MinSize;
-  Bool        m_useAMP;
-
-  // Parameter
-  Int         m_bitDepthY;
-  Int         m_bitDepthC;
-  Int         m_qpBDOffsetY;
-  Int         m_qpBDOffsetC;
-
-  UInt        m_uiPCMBitDepthLuma;
-  UInt        m_uiPCMBitDepthChroma;
-  Bool        m_bPCMFilterDisableFlag;
-
-  UInt        m_uiBitsForPOC;
-
-  UInt        m_numLongTermRefPicSPS;
-  UInt        m_ltRefPicPocLsbSps[33];
-  Bool        m_usedByCurrPicLtSPSFlag[33];
-  // Max physical transform size
-  UInt        m_uiMaxTrSize;
-  
-  Int m_iAMPAcc[MAX_CU_DEPTH];
-  Bool        m_bUseSAO; 
-
-  Bool        m_bTemporalIdNestingFlag; // temporal_id_nesting_flag
-
-  Bool        m_scalingListEnabledFlag;
-  Bool        m_scalingListPresentFlag;
-  TComScalingList*     m_scalingList;   //!< ScalingList class pointer
-  UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
-  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];  // Really max latency increase plus 1 (value 0 expresses no limit)
-
-  Bool        m_useDF;
-  Bool        m_useStrongIntraSmoothing;
-
-  Bool        m_vuiParametersPresentFlag;
-  TComVUI     m_vuiParameters;
-
-  static const Int   m_winUnitX[MAX_CHROMA_FORMAT_IDC+1];
-  static const Int   m_winUnitY[MAX_CHROMA_FORMAT_IDC+1];
-  TComPTL     m_pcPTL;
-#if H_MV
-  TComVPS*    m_pcVPS; 
-  // SPS 
-  Int         m_spsMaxSubLayersMinus1;
-  Int         m_spsExtOrMaxSubLayersMinus1;
-  Bool        m_spsExtensionPresentFlag; 
-
-  Bool        m_spsRangeExtensionsFlag;
-  Bool        m_spsMultilayerExtensionFlag;
-#if H_3D
-  Bool        m_sps3dExtensionFlag;
-  Int         m_spsExtension5bits;
-#else
-  Int         m_spsExtension6bits;
-#endif
-
-  Bool        m_spsInferScalingListFlag;
-  Int         m_spsScalingListRefLayerId;
-  Bool        m_updateRepFormatFlag;
-  Int         m_spsRepFormatIdx;
-  // SPS Extension 
-  Bool        m_interViewMvVertConstraintFlag;
-#endif
-#if H_3D
-  TComSps3dExtension m_sps3dExtension; 
-  Int         m_aaiCodedScale [2][MAX_NUM_LAYERS];
-  Int         m_aaiCodedOffset[2][MAX_NUM_LAYERS];
-#endif
-#if H_MV
-  Int         m_layerId; 
-#endif
-public:
-  TComSPS();
-  virtual ~TComSPS();
-
-  Int  getVPSId       ()         { return m_VPSId;          }
-  Void setVPSId       (Int i)    { m_VPSId = i;             }
-  Int  getSPSId       ()         { return m_SPSId;          }
-  Void setSPSId       (Int i)    { m_SPSId = i;             }
-  Int  getChromaFormatIdc ()         { return m_chromaFormatIdc;       }
-  Void setChromaFormatIdc (Int i)    { m_chromaFormatIdc = i;          }
-
-#if H_3D_DISABLE_CHROMA
-  static Int getWinUnitX (Int chromaFormatIdc) { assert (chromaFormatIdc >= 0 && chromaFormatIdc <= MAX_CHROMA_FORMAT_IDC); return m_winUnitX[chromaFormatIdc];      }
-  static Int getWinUnitY (Int chromaFormatIdc) { assert (chromaFormatIdc >= 0 && chromaFormatIdc <= MAX_CHROMA_FORMAT_IDC); return m_winUnitY[chromaFormatIdc];      }
-#else
-  static Int getWinUnitX (Int chromaFormatIdc) { assert (chromaFormatIdc > 0 && chromaFormatIdc <= MAX_CHROMA_FORMAT_IDC); return m_winUnitX[chromaFormatIdc];      }
-  static Int getWinUnitY (Int chromaFormatIdc) { assert (chromaFormatIdc > 0 && chromaFormatIdc <= MAX_CHROMA_FORMAT_IDC); return m_winUnitY[chromaFormatIdc];      }
-#endif
-  
-  // structure
-  Void setPicWidthInLumaSamples       ( UInt u ) { m_picWidthInLumaSamples = u;        }
-  UInt getPicWidthInLumaSamples       ()         { return  m_picWidthInLumaSamples;    }
-  Void setPicHeightInLumaSamples      ( UInt u ) { m_picHeightInLumaSamples = u;       }
-  UInt getPicHeightInLumaSamples      ()         { return  m_picHeightInLumaSamples;   }
-
-  Window& getConformanceWindow()                           { return  m_conformanceWindow;             }
-  Void    setConformanceWindow(Window& conformanceWindow ) { m_conformanceWindow = conformanceWindow; }
-
-  UInt  getNumLongTermRefPicSPS()             { return m_numLongTermRefPicSPS; }
-  Void  setNumLongTermRefPicSPS(UInt val)     { m_numLongTermRefPicSPS = val; }
-
-  UInt  getLtRefPicPocLsbSps(UInt index)             { return m_ltRefPicPocLsbSps[index]; }
-  Void  setLtRefPicPocLsbSps(UInt index, UInt val)     { m_ltRefPicPocLsbSps[index] = val; }
-
-  Bool getUsedByCurrPicLtSPSFlag(Int i)        {return m_usedByCurrPicLtSPSFlag[i];}
-  Void setUsedByCurrPicLtSPSFlag(Int i, Bool x)      { m_usedByCurrPicLtSPSFlag[i] = x;}
-
-  Int  getLog2MinCodingBlockSize() const           { return m_log2MinCodingBlockSize; }
-  Void setLog2MinCodingBlockSize(Int val)          { m_log2MinCodingBlockSize = val; }
-  Int  getLog2DiffMaxMinCodingBlockSize() const    { return m_log2DiffMaxMinCodingBlockSize; }
-  Void setLog2DiffMaxMinCodingBlockSize(Int val)   { m_log2DiffMaxMinCodingBlockSize = val; }
-
-  Void setMaxCUWidth  ( UInt u ) { m_uiMaxCUWidth = u;      }
-  UInt getMaxCUWidth  ()         { return  m_uiMaxCUWidth;  }
-  Void setMaxCUHeight ( UInt u ) { m_uiMaxCUHeight = u;     }
-  UInt getMaxCUHeight ()         { return  m_uiMaxCUHeight; }
-  Void setMaxCUDepth  ( UInt u ) { m_uiMaxCUDepth = u;      }
-  UInt getMaxCUDepth  ()         { return  m_uiMaxCUDepth;  }
-  Void setUsePCM      ( Bool b ) { m_usePCM = b;           }
-  Bool getUsePCM      ()         { return m_usePCM;        }
-  Void setPCMLog2MaxSize  ( UInt u ) { m_pcmLog2MaxSize = u;      }
-  UInt getPCMLog2MaxSize  ()         { return  m_pcmLog2MaxSize;  }
-  Void setPCMLog2MinSize  ( UInt u ) { m_uiPCMLog2MinSize = u;      }
-  UInt getPCMLog2MinSize  ()         { return  m_uiPCMLog2MinSize;  }
-  Void setBitsForPOC  ( UInt u ) { m_uiBitsForPOC = u;      }
-  UInt getBitsForPOC  ()         { return m_uiBitsForPOC;   }
-  Bool getUseAMP() { return m_useAMP; }
-  Void setUseAMP( Bool b ) { m_useAMP = b; }
-  Void setQuadtreeTULog2MaxSize( UInt u ) { m_uiQuadtreeTULog2MaxSize = u;    }
-  UInt getQuadtreeTULog2MaxSize()         { return m_uiQuadtreeTULog2MaxSize; }
-  Void setQuadtreeTULog2MinSize( UInt u ) { m_uiQuadtreeTULog2MinSize = u;    }
-  UInt getQuadtreeTULog2MinSize()         { return m_uiQuadtreeTULog2MinSize; }
-  Void setQuadtreeTUMaxDepthInter( UInt u ) { m_uiQuadtreeTUMaxDepthInter = u;    }
-  Void setQuadtreeTUMaxDepthIntra( UInt u ) { m_uiQuadtreeTUMaxDepthIntra = u;    }
-  UInt getQuadtreeTUMaxDepthInter()         { return m_uiQuadtreeTUMaxDepthInter; }
-  UInt getQuadtreeTUMaxDepthIntra()         { return m_uiQuadtreeTUMaxDepthIntra; }
-  Void setNumReorderPics(Int i, UInt tlayer)              { m_numReorderPics[tlayer] = i;    }
-  Int  getNumReorderPics(UInt tlayer)                     { return m_numReorderPics[tlayer]; }
-  Void         createRPSList( Int numRPS );
-  TComRPSList* getRPSList()                      { return &m_RPSList;          }
-  Bool      getLongTermRefsPresent()         { return m_bLongTermRefsPresent; }
-  Void      setLongTermRefsPresent(Bool b)   { m_bLongTermRefsPresent=b;      }
-  Bool      getTMVPFlagsPresent()         { return m_TMVPFlagsPresent; }
-  Void      setTMVPFlagsPresent(Bool b)   { m_TMVPFlagsPresent=b;      }  
-  // physical transform
-  Void setMaxTrSize   ( UInt u ) { m_uiMaxTrSize = u;       }
-  UInt getMaxTrSize   ()         { return  m_uiMaxTrSize;   }
-  
-  // AMP accuracy
-  Int       getAMPAcc   ( UInt uiDepth ) { return m_iAMPAcc[uiDepth]; }
-  Void      setAMPAcc   ( UInt uiDepth, Int iAccu ) { assert( uiDepth < g_uiMaxCUDepth);  m_iAMPAcc[uiDepth] = iAccu; }
-
-  // Bit-depth
-  Int      getBitDepthY() { return m_bitDepthY; }
-  Void     setBitDepthY(Int u) { m_bitDepthY = u; }
-  Int      getBitDepthC() { return m_bitDepthC; }
-  Void     setBitDepthC(Int u) { m_bitDepthC = u; }
-  Int       getQpBDOffsetY  ()             { return m_qpBDOffsetY;   }
-  Void      setQpBDOffsetY  ( Int value  ) { m_qpBDOffsetY = value;  }
-  Int       getQpBDOffsetC  ()             { return m_qpBDOffsetC;   }
-  Void      setQpBDOffsetC  ( Int value  ) { m_qpBDOffsetC = value;  }
-  Void setUseSAO                  (Bool bVal)  {m_bUseSAO = bVal;}
-  Bool getUseSAO                  ()           {return m_bUseSAO;}
-
-  UInt      getMaxTLayers()                           { return m_uiMaxTLayers; }
-  Void      setMaxTLayers( UInt uiMaxTLayers )        { assert( uiMaxTLayers <= MAX_TLAYER ); m_uiMaxTLayers = uiMaxTLayers; }
-#if H_MV
-  UInt      getSpsMaxSubLayersMinus1()                { return ( m_uiMaxTLayers - 1); }
-  Void      setSpsMaxSubLayersMinus1( UInt val )       { setMaxTLayers( val + 1 ); }
-#endif
-
-  Bool      getTemporalIdNestingFlag()                { return m_bTemporalIdNestingFlag; }
-  Void      setTemporalIdNestingFlag( Bool bValue )   { m_bTemporalIdNestingFlag = bValue; }
-  UInt      getPCMBitDepthLuma     ()         { return m_uiPCMBitDepthLuma;     }
-  Void      setPCMBitDepthLuma     ( UInt u ) { m_uiPCMBitDepthLuma = u;        }
-  UInt      getPCMBitDepthChroma   ()         { return m_uiPCMBitDepthChroma;   }
-  Void      setPCMBitDepthChroma   ( UInt u ) { m_uiPCMBitDepthChroma = u;      }
-  Void      setPCMFilterDisableFlag     ( Bool   bValue  )    { m_bPCMFilterDisableFlag = bValue; }
-  Bool      getPCMFilterDisableFlag     ()                    { return m_bPCMFilterDisableFlag;   } 
-
-  Bool getScalingListFlag       ()         { return m_scalingListEnabledFlag;     }
-  Void setScalingListFlag       ( Bool b ) { m_scalingListEnabledFlag  = b;       }
-  Bool getScalingListPresentFlag()         { return m_scalingListPresentFlag;     }
-  Void setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
-  Void setScalingList      ( TComScalingList *scalingList);
-  TComScalingList* getScalingList ()       { return m_scalingList; }               //!< get ScalingList class pointer in SPS
-  UInt getMaxDecPicBuffering  (UInt tlayer)            { return m_uiMaxDecPicBuffering[tlayer]; }
-  Void setMaxDecPicBuffering  ( UInt ui, UInt tlayer ) { assert(tlayer < MAX_TLAYER);  m_uiMaxDecPicBuffering[tlayer] = ui;   }
-  UInt getMaxLatencyIncrease  (UInt tlayer)            { return m_uiMaxLatencyIncrease[tlayer];   }
-  Void setMaxLatencyIncrease  ( UInt ui , UInt tlayer) { m_uiMaxLatencyIncrease[tlayer] = ui;      }
-
-  Void setUseStrongIntraSmoothing (Bool bVal)  {m_useStrongIntraSmoothing = bVal;}
-  Bool getUseStrongIntraSmoothing ()           {return m_useStrongIntraSmoothing;}
-
-  Bool getVuiParametersPresentFlag() { return m_vuiParametersPresentFlag; }
-  Void setVuiParametersPresentFlag(Bool b) { m_vuiParametersPresentFlag = b; }
-  TComVUI* getVuiParameters() { return &m_vuiParameters; }
-  Void setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess );
-
-  TComPTL* getPTL()     { return &m_pcPTL; }
-#if H_MV
-  Void setSpsExtOrMaxSubLayersMinus1( Int  val ) { m_spsExtOrMaxSubLayersMinus1 = val; } 
-  Int  getSpsExtOrMaxSubLayersMinus1(  ) { return m_spsExtOrMaxSubLayersMinus1; } 
-  Void inferSpsMaxSubLayersMinus1( Bool atPsActivation, TComVPS* vps  );
-
-  Bool getMultiLayerExtSpsFlag()            { return ( getLayerId() != 0  &&  getSpsExtOrMaxSubLayersMinus1() == 7 ); }
-  Void inferSpsMaxDecPicBufferingMinus1( TComVPS* vps, Int targetOptLayerSetIdx, Int currLayerId, Bool encoder );
-
-  Void setSpsExtensionPresentFlag( Bool flag ) { m_spsExtensionPresentFlag = flag; } 
-  Bool getSpsExtensionPresentFlag( )           { return m_spsExtensionPresentFlag; }
-
-  Void setSpsRangeExtensionsFlag( Bool flag )            { m_spsRangeExtensionsFlag = flag; } 
-  Bool getSpsRangeExtensionsFlag(  )                     { return m_spsRangeExtensionsFlag; } 
-
-  Void setSpsMultilayerExtensionFlag( Bool flag )        { m_spsMultilayerExtensionFlag = flag; } 
-  Bool getSpsMultilayerExtensionFlag( )                  { return m_spsMultilayerExtensionFlag; } 
-#if H_3D
-  Void setSps3dExtensionFlag( Bool flag )                { m_sps3dExtensionFlag = flag; } 
-  Bool getSps3dExtensionFlag(  )                        { return m_sps3dExtensionFlag; } 
-
-  Void setSpsExtension5bits( Int  val )                  { m_spsExtension5bits = val; } 
-  Int  getSpsExtension5bits(  )                          { return m_spsExtension5bits; } 
-#else
-  Void setSpsExtension6bits( Int  val )                  { m_spsExtension6bits = val; } 
-  Int  getSpsExtension6bits(  )                          { return m_spsExtension6bits; } 
-#endif
-  
-  Void      setVPS          ( TComVPS* pcVPS ) { m_pcVPS = pcVPS; }
-  TComVPS*  getVPS          () { return m_pcVPS; }
-
-  Void setSpsInferScalingListFlag( Bool flag ) { m_spsInferScalingListFlag = flag; } 
-  Bool getSpsInferScalingListFlag(  )          { return m_spsInferScalingListFlag; } 
-
-  Void setSpsScalingListRefLayerId( Int  val ) { m_spsScalingListRefLayerId = val; } 
-  Int  getSpsScalingListRefLayerId(  )         { return m_spsScalingListRefLayerId; } 
-
-  Void setUpdateRepFormatFlag( Bool flag )     { m_updateRepFormatFlag = flag; } 
-  Bool getUpdateRepFormatFlag(  )              { return m_updateRepFormatFlag; } 
-  Void setSpsRepFormatIdx( Int  val )          { m_spsRepFormatIdx = val; } 
-  Int  getSpsRepFormatIdx(  )                  { return m_spsRepFormatIdx; } 
-  
-// SPS Extension 
-  Void setInterViewMvVertConstraintFlag(Bool val) { m_interViewMvVertConstraintFlag = val; }
-  Bool getInterViewMvVertConstraintFlag()         { return m_interViewMvVertConstraintFlag;}
-
-#if H_3D
-  Void setSps3dExtension ( TComSps3dExtension& sps3dExtension ) { m_sps3dExtension = sps3dExtension; }
-  TComSps3dExtension* getSps3dExtension ( )                     { return &m_sps3dExtension; }
-#endif
-
-  // Inference 
-
-  Void inferRepFormat( TComVPS* vps, Int layerIdCurr );
-  Void inferScalingList( TComSPS* spsSrc );
-
-  // others
-  Void checkRpsMaxNumPics( TComVPS* vps, Int currLayerId );
-
-#endif
-#if H_MV
-  Int  getLayerId            ()           { return m_layerId; }
-  Void setLayerId            ( Int val )  { m_layerId = val; }
+  Void                   setSpsRepFormatIdx( Int  val )                                                  { m_spsRepFormatIdx = val;                                             }
+  Int                    getSpsRepFormatIdx(  )                  const                                   { return m_spsRepFormatIdx;                                            }
+                                                                                                                                                                                
+// SPS Extension                                                                                                                                                                
+  Void                   setInterViewMvVertConstraintFlag(Bool val)                                      { m_interViewMvVertConstraintFlag = val;                               }
+  Bool                   getInterViewMvVertConstraintFlag()         const                                { return m_interViewMvVertConstraintFlag;                              }
+                                                                                                                                                                                
+#if NH_3D
+  Void                   setSps3dExtension ( TComSps3dExtension& sps3dExtension )                        { m_sps3dExtension = sps3dExtension;                                   }
+  const TComSps3dExtension* getSps3dExtension ( )  const                                                 { return &m_sps3dExtension;                                            } 
+#endif                  
+                        
+  // Inference          
+                        
+  Void                   inferRepFormat( TComVPS* vps, Int layerIdCurr, Bool encoder );
+  Void                   inferScalingList( const TComSPS* spsSrc );
+                        
+  // others             
+  Void                   checkRpsMaxNumPics( const TComVPS* vps, Int currLayerId ) const;
+                        
+  Int                    getLayerId            ()           const                                        { return m_layerId;                                                    }
+  Void                   setLayerId            ( Int val )                                               { m_layerId = val;                                                     }
+
 #endif
 
 };
 
+
 /// Reference Picture Lists class
+
 class TComRefPicListModification
 {
 private:
-  UInt      m_bRefPicListModificationFlagL0;  
-  UInt      m_bRefPicListModificationFlagL1;  
-  UInt      m_RefPicSetIdxL0[32];
-  UInt      m_RefPicSetIdxL1[32];
-    
+  Bool m_refPicListModificationFlagL0;
+  Bool m_refPicListModificationFlagL1;
+  UInt m_RefPicSetIdxL0[REF_PIC_LIST_NUM_IDX];
+  UInt m_RefPicSetIdxL1[REF_PIC_LIST_NUM_IDX];
+
 public:
-  TComRefPicListModification();
+          TComRefPicListModification();
   virtual ~TComRefPicListModification();
-  
-  Void  create                    ();
-  Void  destroy                   ();
-
-  Bool       getRefPicListModificationFlagL0() { return m_bRefPicListModificationFlagL0; }
-  Void       setRefPicListModificationFlagL0(Bool flag) { m_bRefPicListModificationFlagL0 = flag; }
-  Bool       getRefPicListModificationFlagL1() { return m_bRefPicListModificationFlagL1; }
-  Void       setRefPicListModificationFlagL1(Bool flag) { m_bRefPicListModificationFlagL1 = flag; }
-  Void       setRefPicSetIdxL0(UInt idx, UInt refPicSetIdx) { m_RefPicSetIdxL0[idx] = refPicSetIdx; }
-  UInt       getRefPicSetIdxL0(UInt idx) { return m_RefPicSetIdxL0[idx]; }
-  Void       setRefPicSetIdxL1(UInt idx, UInt refPicSetIdx) { m_RefPicSetIdxL1[idx] = refPicSetIdx; }
-  UInt       getRefPicSetIdxL1(UInt idx) { return m_RefPicSetIdxL1[idx]; }
-#if H_MV
-  // Why not an listIdx for all members, would avoid code duplication?? 
-  Void       setRefPicSetIdxL(UInt li, UInt idx, UInt refPicSetIdx) {( li==0 ? m_RefPicSetIdxL0[idx] : m_RefPicSetIdxL1[idx] ) = refPicSetIdx; }
-  UInt       getRefPicSetIdxL(UInt li, UInt idx ) { return ( li == 0 ) ? m_RefPicSetIdxL0[idx] : m_RefPicSetIdxL1[idx] ; }
-  Void       setRefPicListModificationFlagL(UInt li, Bool flag) { ( li==0  ? m_bRefPicListModificationFlagL0 : m_bRefPicListModificationFlagL1 ) = flag;  }
-  Bool       getRefPicListModificationFlagL(UInt li ) { return ( li== 0) ? m_bRefPicListModificationFlagL0 : m_bRefPicListModificationFlagL1; }
+
+  Void    create();
+  Void    destroy();
+
+  Bool    getRefPicListModificationFlagL0() const        { return m_refPicListModificationFlagL0;                                  }
+  Void    setRefPicListModificationFlagL0(Bool flag)     { m_refPicListModificationFlagL0 = flag;                                  }
+  Bool    getRefPicListModificationFlagL1() const        { return m_refPicListModificationFlagL1;                                  }
+  Void    setRefPicListModificationFlagL1(Bool flag)     { m_refPicListModificationFlagL1 = flag;                                  }
+  UInt    getRefPicSetIdxL0(UInt idx) const              { assert(idx<REF_PIC_LIST_NUM_IDX); return m_RefPicSetIdxL0[idx];         }
+  Void    setRefPicSetIdxL0(UInt idx, UInt refPicSetIdx) { assert(idx<REF_PIC_LIST_NUM_IDX); m_RefPicSetIdxL0[idx] = refPicSetIdx; }
+  UInt    getRefPicSetIdxL1(UInt idx) const              { assert(idx<REF_PIC_LIST_NUM_IDX); return m_RefPicSetIdxL1[idx];         }
+  Void    setRefPicSetIdxL1(UInt idx, UInt refPicSetIdx) { assert(idx<REF_PIC_LIST_NUM_IDX); m_RefPicSetIdxL1[idx] = refPicSetIdx; }
+#if NH_MV
+  // Why not a listIdx for all members, would avoid code duplication?? 
+  Void    setRefPicSetIdxL(UInt li, UInt idx, UInt refPicSetIdx) {( li==0 ? m_RefPicSetIdxL0[idx] : m_RefPicSetIdxL1[idx] ) = refPicSetIdx;              }
+  UInt    getRefPicSetIdxL(UInt li, UInt idx )                   { return ( li == 0 ) ? m_RefPicSetIdxL0[idx] : m_RefPicSetIdxL1[idx] ;                  }
+  Void    setRefPicListModificationFlagL(UInt li, Bool flag)     { ( li==0  ? m_refPicListModificationFlagL0 : m_refPicListModificationFlagL1 ) = flag;  }
+  Bool    getRefPicListModificationFlagL(UInt li )               { return ( li== 0) ? m_refPicListModificationFlagL0 : m_refPicListModificationFlagL1;   }
 #endif
 };
+
+/// PPS RExt class
+class TComPPSRExt // Names aligned to text specification
+{
+private:
+  Int              m_log2MaxTransformSkipBlockSize;
+  Bool             m_crossComponentPredictionEnabledFlag;
+
+  // Chroma QP Adjustments
+  Int              m_diffCuChromaQpOffsetDepth;
+  Int              m_chromaQpOffsetListLen; // size (excludes the null entry used in the following array).
+  ChromaQpAdj      m_ChromaQpAdjTableIncludingNullEntry[1+MAX_QP_OFFSET_LIST_SIZE]; //!< Array includes entry [0] for the null offset used when cu_chroma_qp_offset_flag=0, and entries [cu_chroma_qp_offset_idx+1...] otherwise
+
+  UInt             m_log2SaoOffsetScale[MAX_NUM_CHANNEL_TYPE];
+
+public:
+  TComPPSRExt();
+
+  Bool settingsDifferFromDefaults(const bool bTransformSkipEnabledFlag) const
+  {
+    return (bTransformSkipEnabledFlag && (getLog2MaxTransformSkipBlockSize() !=2))
+        || (getCrossComponentPredictionEnabledFlag() )
+        || (getChromaQpOffsetListEnabledFlag() )
+        || (getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA) !=0 )
+        || (getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA) !=0 );
+  }
+
+  UInt                   getLog2MaxTransformSkipBlockSize() const                         { return m_log2MaxTransformSkipBlockSize;         }
+  Void                   setLog2MaxTransformSkipBlockSize( UInt u )                       { m_log2MaxTransformSkipBlockSize  = u;           }
+
+  Bool                   getCrossComponentPredictionEnabledFlag() const                   { return m_crossComponentPredictionEnabledFlag;   }
+  Void                   setCrossComponentPredictionEnabledFlag(Bool value)               { m_crossComponentPredictionEnabledFlag = value;  }
+
+  Void                   clearChromaQpOffsetList()                                        { m_chromaQpOffsetListLen = 0;                    }
+
+  UInt                   getDiffCuChromaQpOffsetDepth () const                            { return m_diffCuChromaQpOffsetDepth;             }
+  Void                   setDiffCuChromaQpOffsetDepth ( UInt u )                          { m_diffCuChromaQpOffsetDepth = u;                }
+
+  Bool                   getChromaQpOffsetListEnabledFlag() const                         { return getChromaQpOffsetListLen()>0;            }
+  Int                    getChromaQpOffsetListLen() const                                 { return m_chromaQpOffsetListLen;                 }
+
+  const ChromaQpAdj&     getChromaQpOffsetListEntry( Int cuChromaQpOffsetIdxPlus1 ) const
+  {
+    assert(cuChromaQpOffsetIdxPlus1 < m_chromaQpOffsetListLen+1);
+    return m_ChromaQpAdjTableIncludingNullEntry[cuChromaQpOffsetIdxPlus1]; // Array includes entry [0] for the null offset used when cu_chroma_qp_offset_flag=0, and entries [cu_chroma_qp_offset_idx+1...] otherwise
+  }
+
+  Void                   setChromaQpOffsetListEntry( Int cuChromaQpOffsetIdxPlus1, Int cbOffset, Int crOffset )
+  {
+    assert (cuChromaQpOffsetIdxPlus1 != 0 && cuChromaQpOffsetIdxPlus1 <= MAX_QP_OFFSET_LIST_SIZE);
+    m_ChromaQpAdjTableIncludingNullEntry[cuChromaQpOffsetIdxPlus1].u.comp.CbOffset = cbOffset; // Array includes entry [0] for the null offset used when cu_chroma_qp_offset_flag=0, and entries [cu_chroma_qp_offset_idx+1...] otherwise
+    m_ChromaQpAdjTableIncludingNullEntry[cuChromaQpOffsetIdxPlus1].u.comp.CrOffset = crOffset;
+    m_chromaQpOffsetListLen = max(m_chromaQpOffsetListLen, cuChromaQpOffsetIdxPlus1);
+  }
+
+  // Now: getPpsRangeExtension().getLog2SaoOffsetScale and getPpsRangeExtension().setLog2SaoOffsetScale
+  UInt                   getLog2SaoOffsetScale(ChannelType type) const                    { return m_log2SaoOffsetScale[type];             }
+  Void                   setLog2SaoOffsetScale(ChannelType type, UInt uiBitShift)         { m_log2SaoOffsetScale[type] = uiBitShift;       }
+
+};
+
 
 /// PPS class
@@ -2017,33 +2192,30 @@
 {
 private:
-  Int         m_PPSId;                    // pic_parameter_set_id
-  Int         m_SPSId;                    // seq_parameter_set_id
-  Int         m_picInitQPMinus26;
-  Bool        m_useDQP;
-  Bool        m_bConstrainedIntraPred;    // constrained_intra_pred_flag
-  Bool        m_bSliceChromaQpFlag;       // slicelevel_chroma_qp_flag
+  Int              m_PPSId;                    // pic_parameter_set_id
+  Int              m_SPSId;                    // seq_parameter_set_id
+  Int              m_picInitQPMinus26;
+  Bool             m_useDQP;
+  Bool             m_bConstrainedIntraPred;    // constrained_intra_pred_flag
+  Bool             m_bSliceChromaQpFlag;       // slicelevel_chroma_qp_flag
 
   // access channel
-  TComSPS*    m_pcSPS;
-  UInt        m_uiMaxCuDQPDepth;
-  UInt        m_uiMinCuDQPSize;
-
-  Int         m_chromaCbQpOffset;
-  Int         m_chromaCrQpOffset;
-
-  UInt        m_numRefIdxL0DefaultActive;
-  UInt        m_numRefIdxL1DefaultActive;
-
-  Bool        m_bUseWeightPred;           // Use of Weighting Prediction (P_SLICE)
-  Bool        m_useWeightedBiPred;        // Use of Weighting Bi-Prediction (B_SLICE)
-  Bool        m_OutputFlagPresentFlag;   // Indicates the presence of output_flag in slice header
-
-  Bool        m_TransquantBypassEnableFlag; // Indicates presence of cu_transquant_bypass_flag in CUs.
-  Bool        m_useTransformSkip;
-  Bool        m_dependentSliceSegmentsEnabledFlag;     //!< Indicates the presence of dependent slices
-  Bool        m_tilesEnabledFlag;              //!< Indicates the presence of tiles
-  Bool        m_entropyCodingSyncEnabledFlag;  //!< Indicates the presence of wavefronts
-  
-  Bool     m_loopFilterAcrossTilesEnabledFlag;
+  UInt             m_uiMaxCuDQPDepth;
+
+  Int              m_chromaCbQpOffset;
+  Int              m_chromaCrQpOffset;
+
+  UInt             m_numRefIdxL0DefaultActive;
+  UInt             m_numRefIdxL1DefaultActive;
+
+  Bool             m_bUseWeightPred;                    //!< Use of Weighting Prediction (P_SLICE)
+  Bool             m_useWeightedBiPred;                 //!< Use of Weighting Bi-Prediction (B_SLICE)
+  Bool             m_OutputFlagPresentFlag;             //!< Indicates the presence of output_flag in slice header
+  Bool             m_TransquantBypassEnableFlag;        //!< Indicates presence of cu_transquant_bypass_flag in CUs.
+  Bool             m_useTransformSkip;
+  Bool             m_dependentSliceSegmentsEnabledFlag; //!< Indicates the presence of dependent slices
+  Bool             m_tilesEnabledFlag;                  //!< Indicates the presence of tiles
+  Bool             m_entropyCodingSyncEnabledFlag;      //!< Indicates the presence of wavefronts
+
+  Bool             m_loopFilterAcrossTilesEnabledFlag;
   Bool             m_uniformSpacingFlag;
   Int              m_numTileColumnsMinus1;
@@ -2052,319 +2224,339 @@
   std::vector<Int> m_tileRowHeight;
 
-  Int      m_numSubstreams;
-
-  Int      m_signHideFlag;
-
-  Bool     m_cabacInitPresentFlag;
-  UInt     m_encCABACTableIdx;           // Used to transmit table selection across slices
-
-  Bool     m_sliceHeaderExtensionPresentFlag;
-  Bool     m_loopFilterAcrossSlicesEnabledFlag;
-  Bool     m_deblockingFilterControlPresentFlag;
-  Bool     m_deblockingFilterOverrideEnabledFlag;
-  Bool     m_picDisableDeblockingFilterFlag;
-  Int      m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
-  Int      m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
-  Bool     m_scalingListPresentFlag;
-  TComScalingList*     m_scalingList;   //!< ScalingList class pointer
-  Bool m_listsModificationPresentFlag;
-  UInt m_log2ParallelMergeLevelMinus2;
-  Int m_numExtraSliceHeaderBits;
-
-#if H_MV
-  Int  m_layerId; 
-  Bool m_ppsInferScalingListFlag;
-  Int  m_ppsScalingListRefLayerId;
-
-  Bool m_ppsRangeExtensionsFlag;
-  Bool m_ppsMultilayerExtensionFlag;
-#if !H_3D
-  Int  m_ppsExtension6bits;
-#else
-  Bool m_pps3dExtensionFlag;
-  Int  m_ppsExtension5bits;
-#endif
-
-  Bool m_pocResetInfoPresentFlag;
+  Bool             m_signHideFlag;
+
+  Bool             m_cabacInitPresentFlag;
+
+  Bool             m_sliceHeaderExtensionPresentFlag;
+  Bool             m_loopFilterAcrossSlicesEnabledFlag;
+  Bool             m_deblockingFilterControlPresentFlag;
+  Bool             m_deblockingFilterOverrideEnabledFlag;
+  Bool             m_picDisableDeblockingFilterFlag;
+  Int              m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int              m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  Bool             m_scalingListPresentFlag;
+  TComScalingList  m_scalingList;                       //!< ScalingList class
+  Bool             m_listsModificationPresentFlag;
+  UInt             m_log2ParallelMergeLevelMinus2;
+  Int              m_numExtraSliceHeaderBits;
+
+  TComPPSRExt      m_ppsRangeExtension;
+
+#if NH_MV
+  Int              m_layerId; 
+  Bool             m_ppsInferScalingListFlag;
+  Int              m_ppsScalingListRefLayerId;
+                   
+  Bool             m_ppsRangeExtensionsFlag;
+  Bool             m_ppsMultilayerExtensionFlag;
+  Bool             m_pps3dExtensionFlag;
+  Int              m_ppsExtension5bits;
+
+  Bool             m_pocResetInfoPresentFlag;
 #endif
 
 #if H_3D
-  TComDLT*  m_pcDLT; 
+  TComDLT*         m_pcDLT; 
 #endif
 
 public:
-  TComPPS();
-  virtual ~TComPPS();
-  
-  Int       getPPSId ()      { return m_PPSId; }
-  Void      setPPSId (Int i) { m_PPSId = i; }
-  Int       getSPSId ()      { return m_SPSId; }
-  Void      setSPSId (Int i) { m_SPSId = i; }
-  
-  Int       getPicInitQPMinus26 ()         { return  m_picInitQPMinus26; }
-  Void      setPicInitQPMinus26 ( Int i )  { m_picInitQPMinus26 = i;     }
-  Bool      getUseDQP ()                   { return m_useDQP;        }
-  Void      setUseDQP ( Bool b )           { m_useDQP   = b;         }
-  Bool      getConstrainedIntraPred ()         { return  m_bConstrainedIntraPred; }
-  Void      setConstrainedIntraPred ( Bool b ) { m_bConstrainedIntraPred = b;     }
-  Bool      getSliceChromaQpFlag ()         { return  m_bSliceChromaQpFlag; }
-  Void      setSliceChromaQpFlag ( Bool b ) { m_bSliceChromaQpFlag = b;     }
-
-  Void      setSPS              ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
-  TComSPS*  getSPS              ()         { return m_pcSPS;          }
-  Void      setMaxCuDQPDepth    ( UInt u ) { m_uiMaxCuDQPDepth = u;   }
-  UInt      getMaxCuDQPDepth    ()         { return m_uiMaxCuDQPDepth;}
-  Void      setMinCuDQPSize     ( UInt u ) { m_uiMinCuDQPSize = u;    }
-  UInt      getMinCuDQPSize     ()         { return m_uiMinCuDQPSize; }
+                         TComPPS();
+  virtual                ~TComPPS();
+
+  Int                    getPPSId() const                                                 { return m_PPSId;                               }
+  Void                   setPPSId(Int i)                                                  { m_PPSId = i;                                  }
+  Int                    getSPSId() const                                                 { return m_SPSId;                               }
+  Void                   setSPSId(Int i)                                                  { m_SPSId = i;                                  }
+
+  Int                    getPicInitQPMinus26() const                                      { return  m_picInitQPMinus26;                   }
+  Void                   setPicInitQPMinus26( Int i )                                     { m_picInitQPMinus26 = i;                       }
+  Bool                   getUseDQP() const                                                { return m_useDQP;                              }
+  Void                   setUseDQP( Bool b )                                              { m_useDQP   = b;                               }
+  Bool                   getConstrainedIntraPred() const                                  { return  m_bConstrainedIntraPred;              }
+  Void                   setConstrainedIntraPred( Bool b )                                { m_bConstrainedIntraPred = b;                  }
+  Bool                   getSliceChromaQpFlag() const                                     { return  m_bSliceChromaQpFlag;                 }
+  Void                   setSliceChromaQpFlag( Bool b )                                   { m_bSliceChromaQpFlag = b;                     }
+
+  Void                   setMaxCuDQPDepth( UInt u )                                       { m_uiMaxCuDQPDepth = u;                        }
+  UInt                   getMaxCuDQPDepth() const                                         { return m_uiMaxCuDQPDepth;                     }
 
 #if H_3D
-  Void      setDLT              ( TComDLT* pcDLT ) { m_pcDLT = pcDLT; }
-  TComDLT*  getDLT              ()                 { return m_pcDLT; }
-#endif
-
-  Void      setChromaCbQpOffset( Int i ) { m_chromaCbQpOffset = i;    }
-  Int       getChromaCbQpOffset()        { return m_chromaCbQpOffset; }
-  Void      setChromaCrQpOffset( Int i ) { m_chromaCrQpOffset = i;    }
-  Int       getChromaCrQpOffset()        { return m_chromaCrQpOffset; }
-
-  Void      setNumRefIdxL0DefaultActive(UInt ui)    { m_numRefIdxL0DefaultActive=ui;     }
-  UInt      getNumRefIdxL0DefaultActive()           { return m_numRefIdxL0DefaultActive; }
-  Void      setNumRefIdxL1DefaultActive(UInt ui)    { m_numRefIdxL1DefaultActive=ui;     }
-  UInt      getNumRefIdxL1DefaultActive()           { return m_numRefIdxL1DefaultActive; }
-
-  Bool getUseWP                     ()          { return m_bUseWeightPred;  }
-  Bool getWPBiPred                  ()          { return m_useWeightedBiPred;     }
-  Void setUseWP                     ( Bool b )  { m_bUseWeightPred = b;     }
-  Void setWPBiPred                  ( Bool b )  { m_useWeightedBiPred = b;  }
-  Void      setOutputFlagPresentFlag( Bool b )  { m_OutputFlagPresentFlag = b;    }
-  Bool      getOutputFlagPresentFlag()          { return m_OutputFlagPresentFlag; }
-  Void      setTransquantBypassEnableFlag( Bool b ) { m_TransquantBypassEnableFlag = b; }
-  Bool      getTransquantBypassEnableFlag()         { return m_TransquantBypassEnableFlag; }
-
-  Bool      getUseTransformSkip       ()         { return m_useTransformSkip;     }
-  Void      setUseTransformSkip       ( Bool b ) { m_useTransformSkip  = b;       }
-
-  Void    setLoopFilterAcrossTilesEnabledFlag  (Bool b)    { m_loopFilterAcrossTilesEnabledFlag = b; }
-  Bool    getLoopFilterAcrossTilesEnabledFlag  ()          { return m_loopFilterAcrossTilesEnabledFlag;   }
-  Bool    getDependentSliceSegmentsEnabledFlag() const     { return m_dependentSliceSegmentsEnabledFlag; }
-  Void    setDependentSliceSegmentsEnabledFlag(Bool val)   { m_dependentSliceSegmentsEnabledFlag = val; }
-  Bool    getEntropyCodingSyncEnabledFlag() const          { return m_entropyCodingSyncEnabledFlag; }
-  Void    setEntropyCodingSyncEnabledFlag(Bool val)        { m_entropyCodingSyncEnabledFlag = val; }
-
-  Void     setTilesEnabledFlag       (Bool val)                             { m_tilesEnabledFlag = val; }
-  Bool     getTilesEnabledFlag       () const                               { return m_tilesEnabledFlag; }
-  Void     setTileUniformSpacingFlag (Bool b)                               { m_uniformSpacingFlag = b; }
-  Bool     getTileUniformSpacingFlag () const                               { return m_uniformSpacingFlag; }
-  Void     setNumTileColumnsMinus1   (Int i)                                { m_numTileColumnsMinus1 = i; }
-  Int      getNumTileColumnsMinus1   () const                               { return m_numTileColumnsMinus1; }
-  Void     setTileColumnWidth        (const std::vector<Int>& columnWidth ) { m_tileColumnWidth = columnWidth; }
-  UInt     getTileColumnWidth        (UInt columnIdx) const                 { return  m_tileColumnWidth[columnIdx]; }
-  Void     setNumTileRowsMinus1      (Int i)                                { m_numTileRowsMinus1 = i; }
-  Int      getTileNumRowsMinus1      () const                               { return m_numTileRowsMinus1; }
-  Void     setTileRowHeight          (const std::vector<Int>& rowHeight)    { m_tileRowHeight = rowHeight;  }
-  UInt     getTileRowHeight          (UInt rowIdx) const                    { return m_tileRowHeight[rowIdx]; }
-
-  Void     setNumSubstreams    (Int numSubstreams)                     { m_numSubstreams = numSubstreams; }
-  Int      getNumSubstreams    ()                                      { return m_numSubstreams; }
-
-  Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
-  Int       getSignHideFlag()                    { return m_signHideFlag; }
-
-  Void     setCabacInitPresentFlag( Bool flag )     { m_cabacInitPresentFlag = flag;    }
-  Void     setEncCABACTableIdx( Int idx )           { m_encCABACTableIdx = idx;         }
-  Bool     getCabacInitPresentFlag()                { return m_cabacInitPresentFlag;    }
-  UInt     getEncCABACTableIdx()                    { return m_encCABACTableIdx;        }
-  Void     setDeblockingFilterControlPresentFlag( Bool val )  { m_deblockingFilterControlPresentFlag = val; }
-  Bool     getDeblockingFilterControlPresentFlag()            { return m_deblockingFilterControlPresentFlag; }
-  Void     setDeblockingFilterOverrideEnabledFlag( Bool val ) { m_deblockingFilterOverrideEnabledFlag = val; }
-  Bool     getDeblockingFilterOverrideEnabledFlag()           { return m_deblockingFilterOverrideEnabledFlag; }
-  Void     setPicDisableDeblockingFilterFlag(Bool val)        { m_picDisableDeblockingFilterFlag = val; }       //!< set offset for deblocking filter disabled
-  Bool     getPicDisableDeblockingFilterFlag()                { return m_picDisableDeblockingFilterFlag; }      //!< get offset for deblocking filter disabled
-  Void     setDeblockingFilterBetaOffsetDiv2(Int val)         { m_deblockingFilterBetaOffsetDiv2 = val; }       //!< set beta offset for deblocking filter
-  Int      getDeblockingFilterBetaOffsetDiv2()                { return m_deblockingFilterBetaOffsetDiv2; }      //!< get beta offset for deblocking filter
-  Void     setDeblockingFilterTcOffsetDiv2(Int val)           { m_deblockingFilterTcOffsetDiv2 = val; }               //!< set tc offset for deblocking filter
-  Int      getDeblockingFilterTcOffsetDiv2()                  { return m_deblockingFilterTcOffsetDiv2; }              //!< get tc offset for deblocking filter
-  Bool     getScalingListPresentFlag()         { return m_scalingListPresentFlag;     }
-  Void     setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
-  Void     setScalingList      ( TComScalingList *scalingList);
-  TComScalingList* getScalingList ()          { return m_scalingList; }         //!< get ScalingList class pointer in PPS
-  Bool getListsModificationPresentFlag ()          { return m_listsModificationPresentFlag; }
-  Void setListsModificationPresentFlag ( Bool b )  { m_listsModificationPresentFlag = b;    }
-  UInt getLog2ParallelMergeLevelMinus2      ()                    { return m_log2ParallelMergeLevelMinus2; }
-  Void setLog2ParallelMergeLevelMinus2      (UInt mrgLevel)       { m_log2ParallelMergeLevelMinus2 = mrgLevel; }
-  Int getNumExtraSliceHeaderBits() { return m_numExtraSliceHeaderBits; }
-  Void setNumExtraSliceHeaderBits(Int i) { m_numExtraSliceHeaderBits = i; }
-  Void      setLoopFilterAcrossSlicesEnabledFlag ( Bool   bValue  )    { m_loopFilterAcrossSlicesEnabledFlag = bValue; }
-  Bool      getLoopFilterAcrossSlicesEnabledFlag ()                    { return m_loopFilterAcrossSlicesEnabledFlag;   } 
-  Bool getSliceHeaderExtensionPresentFlag   ()                    { return m_sliceHeaderExtensionPresentFlag; }
-  Void setSliceHeaderExtensionPresentFlag   (Bool val)            { m_sliceHeaderExtensionPresentFlag = val; }
-#if H_MV
-  Void setLayerId( Int  val ) { m_layerId = val; } 
-  Int  getLayerId(  ) { return m_layerId; } 
-
-  Void setPpsInferScalingListFlag( Bool flag ) { m_ppsInferScalingListFlag = flag; } 
-  Bool getPpsInferScalingListFlag(  ) { return m_ppsInferScalingListFlag; } 
-
-  Void setPpsScalingListRefLayerId( Int  val ) { m_ppsScalingListRefLayerId = val; } 
-  Int  getPpsScalingListRefLayerId(  ) { return m_ppsScalingListRefLayerId; } 
-
-  Void setPpsRangeExtensionsFlag( Bool flag ) { m_ppsRangeExtensionsFlag = flag; } 
-  Bool getPpsRangeExtensionsFlag(  ) { return m_ppsRangeExtensionsFlag; } 
-
-  Void setPpsMultilayerExtensionFlag( Bool flag ) { m_ppsMultilayerExtensionFlag = flag; } 
-  Bool getPpsMultilayerExtensionFlag(  ) { return m_ppsMultilayerExtensionFlag; } 
-
-#if !H_3D
-  Void setPpsExtension6bits( Int  val ) { m_ppsExtension6bits = val; } 
-  Int  getPpsExtension6bits(  ) { return m_ppsExtension6bits; } 
-#else
-  Void setPps3dExtensionFlag( Bool flag ) { m_pps3dExtensionFlag = flag; } 
-  Bool getPps3dExtensionFlag(  ) { return m_pps3dExtensionFlag; } 
-
-  Void setPpsExtension5bits( Int  val ) { m_ppsExtension5bits = val; } 
-  Int  getPpsExtension5bits(  ) { return m_ppsExtension5bits; } 
-#endif
-
-  Void setPocResetInfoPresentFlag( Bool flag ) { m_pocResetInfoPresentFlag = flag; } 
-  Bool getPocResetInfoPresentFlag(  ) { return m_pocResetInfoPresentFlag; } 
+  Void                   setDLT( TComDLT* pcDLT )                                         { m_pcDLT = pcDLT;                             }
+  TComDLT*               getDLT()                                                         { return m_pcDLT;                              }
+#endif
+
+
+  Void                   setQpOffset(ComponentID compID, Int i )
+  {
+    if      (compID==COMPONENT_Cb)
+    {
+      m_chromaCbQpOffset = i;
+    }
+    else if (compID==COMPONENT_Cr)
+    {
+      m_chromaCrQpOffset = i;
+    }
+    else
+    {
+      assert(0);
+    }
+  }
+  Int                    getQpOffset(ComponentID compID) const
+  {
+    return (compID==COMPONENT_Y) ? 0 : (compID==COMPONENT_Cb ? m_chromaCbQpOffset : m_chromaCrQpOffset );
+  }
+
+  Void                   setNumRefIdxL0DefaultActive(UInt ui)                             { m_numRefIdxL0DefaultActive=ui;                }
+  UInt                   getNumRefIdxL0DefaultActive() const                              { return m_numRefIdxL0DefaultActive;            }
+  Void                   setNumRefIdxL1DefaultActive(UInt ui)                             { m_numRefIdxL1DefaultActive=ui;                }
+  UInt                   getNumRefIdxL1DefaultActive() const                              { return m_numRefIdxL1DefaultActive;            }
+
+  Bool                   getUseWP() const                                                 { return m_bUseWeightPred;                      }
+  Bool                   getWPBiPred() const                                              { return m_useWeightedBiPred;                   }
+  Void                   setUseWP( Bool b )                                               { m_bUseWeightPred = b;                         }
+  Void                   setWPBiPred( Bool b )                                            { m_useWeightedBiPred = b;                      }
+
+  Void                   setOutputFlagPresentFlag( Bool b )                               { m_OutputFlagPresentFlag = b;                  }
+  Bool                   getOutputFlagPresentFlag() const                                 { return m_OutputFlagPresentFlag;               }
+  Void                   setTransquantBypassEnableFlag( Bool b )                          { m_TransquantBypassEnableFlag = b;             }
+  Bool                   getTransquantBypassEnableFlag() const                            { return m_TransquantBypassEnableFlag;          }
+
+  Bool                   getUseTransformSkip() const                                      { return m_useTransformSkip;                    }
+  Void                   setUseTransformSkip( Bool b )                                    { m_useTransformSkip  = b;                      }
+
+  Void                   setLoopFilterAcrossTilesEnabledFlag(Bool b)                      { m_loopFilterAcrossTilesEnabledFlag = b;       }
+  Bool                   getLoopFilterAcrossTilesEnabledFlag() const                      { return m_loopFilterAcrossTilesEnabledFlag;    }
+  Bool                   getDependentSliceSegmentsEnabledFlag() const                     { return m_dependentSliceSegmentsEnabledFlag;   }
+  Void                   setDependentSliceSegmentsEnabledFlag(Bool val)                   { m_dependentSliceSegmentsEnabledFlag = val;    }
+  Bool                   getEntropyCodingSyncEnabledFlag() const                          { return m_entropyCodingSyncEnabledFlag;        }
+  Void                   setEntropyCodingSyncEnabledFlag(Bool val)                        { m_entropyCodingSyncEnabledFlag = val;         }
+
+  Void                   setTilesEnabledFlag(Bool val)                                    { m_tilesEnabledFlag = val;                     }
+  Bool                   getTilesEnabledFlag() const                                      { return m_tilesEnabledFlag;                    }
+  Void                   setTileUniformSpacingFlag(Bool b)                                { m_uniformSpacingFlag = b;                     }
+  Bool                   getTileUniformSpacingFlag() const                                { return m_uniformSpacingFlag;                  }
+  Void                   setNumTileColumnsMinus1(Int i)                                   { m_numTileColumnsMinus1 = i;                   }
+  Int                    getNumTileColumnsMinus1() const                                  { return m_numTileColumnsMinus1;                }
+  Void                   setTileColumnWidth(const std::vector<Int>& columnWidth )         { m_tileColumnWidth = columnWidth;              }
+  UInt                   getTileColumnWidth(UInt columnIdx) const                         { return  m_tileColumnWidth[columnIdx];         }
+  Void                   setNumTileRowsMinus1(Int i)                                      { m_numTileRowsMinus1 = i;                      }
+  Int                    getNumTileRowsMinus1() const                                     { return m_numTileRowsMinus1;                   }
+  Void                   setTileRowHeight(const std::vector<Int>& rowHeight)              { m_tileRowHeight = rowHeight;                  }
+  UInt                   getTileRowHeight(UInt rowIdx) const                              { return m_tileRowHeight[rowIdx];               }
+
+  Void                   setSignHideFlag( Bool signHideFlag )                             { m_signHideFlag = signHideFlag;                }
+  Bool                   getSignHideFlag() const                                          { return m_signHideFlag;                        }
+
+  Void                   setCabacInitPresentFlag( Bool flag )                             { m_cabacInitPresentFlag = flag;                }
+  Bool                   getCabacInitPresentFlag() const                                  { return m_cabacInitPresentFlag;                }
+  Void                   setDeblockingFilterControlPresentFlag( Bool val )                { m_deblockingFilterControlPresentFlag = val;   }
+  Bool                   getDeblockingFilterControlPresentFlag() const                    { return m_deblockingFilterControlPresentFlag;  }
+  Void                   setDeblockingFilterOverrideEnabledFlag( Bool val )               { m_deblockingFilterOverrideEnabledFlag = val;  }
+  Bool                   getDeblockingFilterOverrideEnabledFlag() const                   { return m_deblockingFilterOverrideEnabledFlag; }
+  Void                   setPicDisableDeblockingFilterFlag(Bool val)                      { m_picDisableDeblockingFilterFlag = val;       } //!< set offset for deblocking filter disabled
+  Bool                   getPicDisableDeblockingFilterFlag() const                        { return m_picDisableDeblockingFilterFlag;      } //!< get offset for deblocking filter disabled
+  Void                   setDeblockingFilterBetaOffsetDiv2(Int val)                       { m_deblockingFilterBetaOffsetDiv2 = val;       } //!< set beta offset for deblocking filter
+  Int                    getDeblockingFilterBetaOffsetDiv2() const                        { return m_deblockingFilterBetaOffsetDiv2;      } //!< get beta offset for deblocking filter
+  Void                   setDeblockingFilterTcOffsetDiv2(Int val)                         { m_deblockingFilterTcOffsetDiv2 = val;         } //!< set tc offset for deblocking filter
+  Int                    getDeblockingFilterTcOffsetDiv2() const                          { return m_deblockingFilterTcOffsetDiv2;        } //!< get tc offset for deblocking filter
+  Bool                   getScalingListPresentFlag() const                                { return m_scalingListPresentFlag;              }
+  Void                   setScalingListPresentFlag( Bool b )                              { m_scalingListPresentFlag  = b;                }
+  TComScalingList&       getScalingList()                                                 { return m_scalingList;                         }
+  const TComScalingList& getScalingList() const                                           { return m_scalingList;                         }
+  Bool                   getListsModificationPresentFlag() const                          { return m_listsModificationPresentFlag;        }
+  Void                   setListsModificationPresentFlag( Bool b )                        { m_listsModificationPresentFlag = b;           }
+  UInt                   getLog2ParallelMergeLevelMinus2() const                          { return m_log2ParallelMergeLevelMinus2;        }
+  Void                   setLog2ParallelMergeLevelMinus2(UInt mrgLevel)                   { m_log2ParallelMergeLevelMinus2 = mrgLevel;    }
+  Int                    getNumExtraSliceHeaderBits() const                               { return m_numExtraSliceHeaderBits;             }
+  Void                   setNumExtraSliceHeaderBits(Int i)                                { m_numExtraSliceHeaderBits = i;                }
+  Void                   setLoopFilterAcrossSlicesEnabledFlag( Bool bValue )              { m_loopFilterAcrossSlicesEnabledFlag = bValue; }
+  Bool                   getLoopFilterAcrossSlicesEnabledFlag() const                     { return m_loopFilterAcrossSlicesEnabledFlag;   }
+  Bool                   getSliceHeaderExtensionPresentFlag() const                       { return m_sliceHeaderExtensionPresentFlag;     }
+  Void                   setSliceHeaderExtensionPresentFlag(Bool val)                     { m_sliceHeaderExtensionPresentFlag = val;      }
+
+
+  const TComPPSRExt&     getPpsRangeExtension() const                                     { return m_ppsRangeExtension;                   }
+  TComPPSRExt&           getPpsRangeExtension()                                           { return m_ppsRangeExtension;                   }
+
+  // WAS: getTransformSkipLog2MaxSize and setTransformSkipLog2MaxSize
+  // Now: getPpsRangeExtension().getLog2MaxTransformSkipBlockSize and getPpsRangeExtension().setLog2MaxTransformSkipBlockSize
+
+  // WAS: getUseCrossComponentPrediction and setUseCrossComponentPrediction
+  // Now: getPpsRangeExtension().getCrossComponentPredictionEnabledFlag and getPpsRangeExtension().setCrossComponentPredictionEnabledFlag
+
+  // WAS: clearChromaQpAdjTable
+  // Now: getPpsRangeExtension().clearChromaQpOffsetList
+
+  // WAS: getMaxCuChromaQpAdjDepth and setMaxCuChromaQpAdjDepth
+  // Now: getPpsRangeExtension().getDiffCuChromaQpOffsetDepth and getPpsRangeExtension().setDiffCuChromaQpOffsetDepth
+
+  // WAS: getChromaQpAdjTableSize
+  // Now: getPpsRangeExtension().getChromaQpOffsetListLen
+
+  // WAS: getChromaQpAdjTableAt and setChromaQpAdjTableAt
+  // Now: getPpsRangeExtension().getChromaQpOffsetListEntry and getPpsRangeExtension().setChromaQpOffsetListEntry
+
+  // WAS: getSaoOffsetBitShift and setSaoOffsetBitShift
+  // Now: getPpsRangeExtension().getLog2SaoOffsetScale and getPpsRangeExtension().setLog2SaoOffsetScale
+
+#if NH_MV
+  Void    setLayerId( Int  val )                                                     { m_layerId = val;                                           }
+  Int     getLayerId(  ) const                                                       { return m_layerId;                                          }
+
+  Void    setPpsInferScalingListFlag( Bool flag )                                    { m_ppsInferScalingListFlag = flag;                          }
+  Bool    getPpsInferScalingListFlag(  ) const                                       { return m_ppsInferScalingListFlag;                          }
+
+  Void    setPpsScalingListRefLayerId( Int  val )                                    { m_ppsScalingListRefLayerId = val;                          }
+  Int     getPpsScalingListRefLayerId(  ) const                                      { return m_ppsScalingListRefLayerId;                         }
+
+  Void    setPpsRangeExtensionsFlag( Bool flag )                                     { m_ppsRangeExtensionsFlag = flag;                           }
+  Bool    getPpsRangeExtensionsFlag(  ) const                                        { return m_ppsRangeExtensionsFlag;                           }
+
+  Void    setPpsMultilayerExtensionFlag( Bool flag )                                 { m_ppsMultilayerExtensionFlag = flag;                       }
+  Bool    getPpsMultilayerExtensionFlag(  ) const                                    { return m_ppsMultilayerExtensionFlag;                       }
+
+  Void    setPps3dExtensionFlag( Bool flag )                                         { m_pps3dExtensionFlag = flag;                               }
+  Bool    getPps3dExtensionFlag(  ) const                                            { return m_pps3dExtensionFlag;                               }
+
+  Void    setPpsExtension5bits( Int  val )                                           { m_ppsExtension5bits = val;                                 }
+  Int     getPpsExtension5bits(  ) const                                             { return m_ppsExtension5bits;                                }
+
+  Void    setPocResetInfoPresentFlag( Bool flag )                                    { m_pocResetInfoPresentFlag = flag;                          }
+  Bool    getPocResetInfoPresentFlag(  ) const                                       { return m_pocResetInfoPresentFlag;                          }
 #endif
 };
-
-typedef struct
+struct WPScalingParam
 {
   // Explicit weighted prediction parameters parsed in slice header,
   // or Implicit weighted prediction parameters (8 bits depth values).
-  Bool        bPresentFlag;
-  UInt        uiLog2WeightDenom;
-  Int         iWeight;
-  Int         iOffset;
+  Bool bPresentFlag;
+  UInt uiLog2WeightDenom;
+  Int  iWeight;
+  Int  iOffset;
 
   // Weighted prediction scaling values built from above parameters (bitdepth scaled):
-  Int         w, o, offset, shift, round;
-} wpScalingParam;
-
-typedef struct
+  Int  w;
+  Int  o;
+  Int  offset;
+  Int  shift;
+  Int  round;
+};
+
+struct WPACDCParam
 {
   Int64 iAC;
   Int64 iDC;
-} wpACDCParam;
+};
 
 /// slice header class
 class TComSlice
 {
-  
+
 private:
   //  Bitstream writing
-  Bool       m_saoEnabledFlag;
-  Bool       m_saoEnabledFlagChroma;      ///< SAO Cb&Cr enabled flag
-  Int         m_iPPSId;               ///< picture parameter set ID
-  Bool        m_PicOutputFlag;        ///< pic_output_flag 
-#if H_MV
-  Int         m_slicePicOrderCntLsb;   
+  Bool                       m_saoEnabledFlag[MAX_NUM_CHANNEL_TYPE];
+  Int                        m_iPPSId;               ///< picture parameter set ID
+  Bool                       m_PicOutputFlag;        ///< pic_output_flag
+#if NH_MV
+  Int                        m_slicePicOrderCntLsb;   
 #endif  
-  Int         m_iPOC;
-#if H_MV
-  Int         m_iPOCBeforeReset; 
-#endif
-  Int         m_iLastIDR;
-  Int         m_iAssociatedIRAP;
-  NalUnitType m_iAssociatedIRAPType;
-  static Int  m_prevTid0POC;
-  TComReferencePictureSet *m_pcRPS;
-  TComReferencePictureSet m_LocalRPS;
-  Int         m_iBDidx; 
+  Int                        m_iPOC;
+#if NH_MV
+  Int                        m_iPOCBeforeReset; 
+#endif
+  Int                        m_iLastIDR;
+  Int                        m_iAssociatedIRAP;
+  NalUnitType                m_iAssociatedIRAPType;
+  TComReferencePictureSet*   m_pcRPS;
+  TComReferencePictureSet    m_LocalRPS;
+  Int                        m_iBDidx;
   TComRefPicListModification m_RefPicListModification;
-  NalUnitType m_eNalUnitType;         ///< Nal unit type for the slice
-  SliceType   m_eSliceType;
-  Int         m_iSliceQp;
-  Bool        m_dependentSliceSegmentFlag;
+  NalUnitType                m_eNalUnitType;         ///< Nal unit type for the slice
+  SliceType                  m_eSliceType;
+  Int                        m_iSliceQp;
+  Bool                       m_dependentSliceSegmentFlag;
 #if ADAPTIVE_QP_SELECTION
-  Int         m_iSliceQpBase;
-#endif
-  Bool        m_deblockingFilterDisable;
-  Bool        m_deblockingFilterOverrideFlag;      //< offsets for deblocking filter inherit from PPS
-  Int         m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
-  Int         m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
-  Int         m_list1IdxToList0Idx[MAX_NUM_REF];
-  Int         m_aiNumRefIdx   [2];    //  for multiple reference of current slice
-
-  Bool        m_bCheckLDC;
+  Int                        m_iSliceQpBase;
+#endif
+  Bool                       m_ChromaQpAdjEnabled;
+  Bool                       m_deblockingFilterDisable;
+  Bool                       m_deblockingFilterOverrideFlag;      //< offsets for deblocking filter inherit from PPS
+  Int                        m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int                        m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  Int                        m_list1IdxToList0Idx[MAX_NUM_REF];
+  Int                        m_aiNumRefIdx   [NUM_REF_PIC_LIST_01];    //  for multiple reference of current slice
+
+  Bool                       m_bCheckLDC;
 
   //  Data
-  Int         m_iSliceQpDelta;
-  Int         m_iSliceQpDeltaCb;
-  Int         m_iSliceQpDeltaCr;
-  TComPic*    m_apcRefPicList [2][MAX_NUM_REF+1];
-  Int         m_aiRefPOCList  [2][MAX_NUM_REF+1];
-#if H_MV
+  Int                        m_iSliceQpDelta;
+  Int                        m_iSliceChromaQpDelta[MAX_NUM_COMPONENT];
+  TComPic*                   m_apcRefPicList [NUM_REF_PIC_LIST_01][MAX_NUM_REF+1];
+  Int                        m_aiRefPOCList  [NUM_REF_PIC_LIST_01][MAX_NUM_REF+1];
+#if NH_MV
   Int         m_aiRefLayerIdList[2][MAX_NUM_REF+1];
 #endif
-  Bool        m_bIsUsedAsLongTerm[2][MAX_NUM_REF+1];
-  Int         m_iDepth;
-  
+  Bool                       m_bIsUsedAsLongTerm[NUM_REF_PIC_LIST_01][MAX_NUM_REF+1];
+  Int                        m_iDepth;
+
   // referenced slice?
-  Bool        m_bRefenced;
-  
+  Bool                       m_bRefenced;
+
   // access channel
-  TComVPS*    m_pcVPS;
-  TComSPS*    m_pcSPS;
-  TComPPS*    m_pcPPS;
-  TComPic*    m_pcPic;
-#if ADAPTIVE_QP_SELECTION
-  TComTrQuant* m_pcTrQuant;
-#endif  
-  UInt        m_colFromL0Flag;  // collocated picture from List0 flag
-  
-#if SETTING_NO_OUT_PIC_PRIOR
-  Bool        m_noOutputPriorPicsFlag;
-  Bool        m_noRaslOutputFlag;
-  Bool        m_handleCraAsBlaFlag;
-#endif
-  
-  UInt        m_colRefIdx;
-  UInt        m_maxNumMergeCand;
-
-  Double      m_lambdas[3];
-
-  Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
-  UInt        m_uiTLayer;
-  Bool        m_bTLayerSwitchingFlag;
-
-  UInt        m_sliceMode;
-  UInt        m_sliceArgument;
-  UInt        m_sliceCurStartCUAddr;
-  UInt        m_sliceCurEndCUAddr;
-  UInt        m_sliceIdx;
-  UInt        m_sliceSegmentMode;
-  UInt        m_sliceSegmentArgument;
-  UInt        m_sliceSegmentCurStartCUAddr;
-  UInt        m_sliceSegmentCurEndCUAddr;
-  Bool        m_nextSlice;
-  Bool        m_nextSliceSegment;
-  UInt        m_sliceBits;
-  UInt        m_sliceSegmentBits;
-  Bool        m_bFinalized;
-
-  wpScalingParam  m_weightPredTable[2][MAX_NUM_REF][3]; // [REF_PIC_LIST_0 or REF_PIC_LIST_1][refIdx][0:Y, 1:U, 2:V]
-  wpACDCParam    m_weightACDCParam[3];                 // [0:Y, 1:U, 2:V]
-
-  std::vector<UInt> m_tileByteLocation;
-  UInt        m_uiTileOffstForMultES;
-
-  UInt*       m_puiSubstreamSizes;
-  TComScalingList*     m_scalingList;                 //!< pointer of quantization matrix
-  Bool        m_cabacInitFlag; 
-
-  Bool       m_bLMvdL1Zero;
-  Int         m_numEntryPointOffsets;
-  Bool       m_temporalLayerNonReferenceFlag;
-  Bool       m_LFCrossSliceBoundaryFlag;
-
-  Bool       m_enableTMVPFlag;
-#if H_MV
+  const TComVPS*             m_pcVPS;
+  const TComSPS*             m_pcSPS;
+  const TComPPS*             m_pcPPS;
+  TComPic*                   m_pcPic;
+  Bool                       m_colFromL0Flag;  // collocated picture from List0 flag
+
+  Bool                       m_noOutputPriorPicsFlag;
+  Bool                       m_noRaslOutputFlag;
+  Bool                       m_handleCraAsBlaFlag;
+
+  UInt                       m_colRefIdx;
+  UInt                       m_maxNumMergeCand;
+
+  Double                     m_lambdas[MAX_NUM_COMPONENT];
+
+  Bool                       m_abEqualRef  [NUM_REF_PIC_LIST_01][MAX_NUM_REF][MAX_NUM_REF];
+  UInt                       m_uiTLayer;
+  Bool                       m_bTLayerSwitchingFlag;
+
+  SliceConstraint            m_sliceMode;
+  UInt                       m_sliceArgument;
+  UInt                       m_sliceCurStartCtuTsAddr;
+  UInt                       m_sliceCurEndCtuTsAddr;
+  UInt                       m_sliceIdx;
+  SliceConstraint            m_sliceSegmentMode;
+  UInt                       m_sliceSegmentArgument;
+  UInt                       m_sliceSegmentCurStartCtuTsAddr;
+  UInt                       m_sliceSegmentCurEndCtuTsAddr;
+  Bool                       m_nextSlice;
+  Bool                       m_nextSliceSegment;
+  UInt                       m_sliceBits;
+  UInt                       m_sliceSegmentBits;
+  Bool                       m_bFinalized;
+
+  Bool                       m_bTestWeightPred;
+  Bool                       m_bTestWeightBiPred;
+  WPScalingParam             m_weightPredTable[NUM_REF_PIC_LIST_01][MAX_NUM_REF][MAX_NUM_COMPONENT]; // [REF_PIC_LIST_0 or REF_PIC_LIST_1][refIdx][0:Y, 1:U, 2:V]
+  WPACDCParam                m_weightACDCParam[MAX_NUM_COMPONENT];
+
+  std::vector<UInt>          m_substreamSizes;
+
+  Bool                       m_cabacInitFlag;
+
+  Bool                       m_bLMvdL1Zero;
+  Bool                       m_temporalLayerNonReferenceFlag;
+  Bool                       m_LFCrossSliceBoundaryFlag;
+
+  Bool                       m_enableTMVPFlag;
+
+  SliceType                  m_encCABACTableIdx;           // Used to transmit table selection across slices.
+#if NH_MV
   Bool       m_availableForTMVPRefFlag;
 #endif
 
-#if H_MV
+#if NH_MV
   std::vector<TComPic*>* m_refPicSetInterLayer0; 
   std::vector<TComPic*>* m_refPicSetInterLayer1; 
@@ -2372,5 +2564,5 @@
   Int        m_viewId;
   Int        m_viewIndex; 
-#if H_3D
+#if NH_3D
   Bool       m_isDepth;
 #endif
@@ -2395,7 +2587,7 @@
   Bool       m_pocMsbValRequiredFlag;
 
-#if H_3D
-  Int        m_aaiCodedScale [2][MAX_NUM_LAYERS];
-  Int        m_aaiCodedOffset[2][MAX_NUM_LAYERS];
+#if NH_3D
+  IntAry2d   m_aaiCodedScale ;
+  IntAry2d   m_aaiCodedOffset;
 #endif
 #if H_3D_TMVP
@@ -2403,15 +2595,17 @@
 #endif
 #if H_3D_ARP
-  Bool m_arpRefPicAvailable[2][MAX_NUM_LAYERS];
+  Bool       m_arpRefPicAvailable[2][MAX_NUM_LAYERS];
   TComList<TComPic*> * m_pBaseViewRefPicList[MAX_NUM_LAYERS];
-  UInt                 m_nARPStepNum; 
-  Int         m_aiFirstTRefIdx    [2]; 
+  UInt        m_nARPStepNum; 
+  Int         m_aiFirstTRefIdx    [2];   
+#endif
+#if NH_3D
   std::vector<Int> m_pocsInCurrRPSs; 
 #endif
 #if H_3D_IC
-  Bool      m_bApplyIC;
-  Bool      m_icSkipParseFlag;
-#endif
-#if H_3D
+  Bool       m_bApplyIC;
+  Bool       m_icSkipParseFlag;
+#endif
+#if NH_3D
   std::vector<Int> m_inCmpRefViewIdcs;
   Bool       m_inCmpPredAvailFlag; 
@@ -2422,420 +2616,407 @@
   Int**      m_depthToDisparityB; 
   Int**      m_depthToDisparityF; 
-#endif
-#endif
-  Bool      m_bApplyDIS;
+  Bool       m_bApplyDIS;
+#endif
+#endif
 #if H_3D_IC
-  Int*      m_aICEnableCandidate;
-  Int*      m_aICEnableNum;
-#endif
-  Int       m_iDefaultRefViewIdx;
-  Bool      m_bDefaultRefViewIdxAvailableFlag;
-
-  Bool m_ivMvPredFlag         ;
-  Bool m_ivMvScalingFlag      ;
-  Bool m_ivResPredFlag        ;
-  Bool m_depthRefinementFlag  ;
-  Bool m_viewSynthesisPredFlag;
-  Bool m_depthBasedBlkPartFlag;
-  Bool m_mpiFlag              ;
-  Bool m_intraContourFlag     ;
-  Bool m_intraSdcWedgeFlag    ;
-  Bool m_qtPredFlag           ;
-  Bool m_interSdcFlag         ;
-  Bool m_depthIntraSkipFlag   ;
-  Int  m_mpiSubPbSize         ; 
-  Int  m_subPbSize            ; 
+  Int*       m_aICEnableCandidate;
+  Int*       m_aICEnableNum;
+#endif       
+#if NH_3D   
+  Int        m_iDefaultRefViewIdx;
+  Bool       m_bDefaultRefViewIdxAvailableFlag;
+             
+  Bool       m_ivMvPredFlag         ;
+  Bool       m_ivMvScalingFlag      ;
+  Bool       m_ivResPredFlag        ;
+  Bool       m_depthRefinementFlag  ;
+  Bool       m_viewSynthesisPredFlag;
+  Bool       m_depthBasedBlkPartFlag;
+  Bool       m_mpiFlag              ;
+  Bool       m_intraContourFlag     ;
+  Bool       m_intraSdcWedgeFlag    ;
+  Bool       m_qtPredFlag           ;
+  Bool       m_interSdcFlag         ;
+  Bool       m_depthIntraSkipFlag   ;
+  Int        m_mpiSubPbSize         ; 
+  Int        m_subPbSize            ; 
+#endif
 public:
-  TComSlice();
-  virtual ~TComSlice(); 
-  Void      initSlice       ();
-
-  Void      setVPS          ( TComVPS* pcVPS ) { m_pcVPS = pcVPS; }
-  TComVPS*  getVPS          () { return m_pcVPS; }
-  Void      setSPS          ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
-  TComSPS*  getSPS          () { return m_pcSPS; }
-  
-  Void      setPPS          ( TComPPS* pcPPS )         { assert(pcPPS!=NULL); m_pcPPS = pcPPS; m_iPPSId = pcPPS->getPPSId(); }
-  TComPPS*  getPPS          () { return m_pcPPS; }
-
+                              TComSlice();
+  virtual                     ~TComSlice();
+  Void                        initSlice();
+
+  Void                        setVPS( TComVPS* pcVPS )                               { m_pcVPS = pcVPS;                                              }
+  const TComVPS*              getVPS() const                                         { return m_pcVPS;                                               }
+  Void                        setSPS( const TComSPS* pcSPS )                         { m_pcSPS = pcSPS;                                              }
+  const TComSPS*              getSPS() const                                         { return m_pcSPS;                                               }
+
+  Void                        setPPS( const TComPPS* pcPPS )                         { m_pcPPS = pcPPS; m_iPPSId = (pcPPS) ? pcPPS->getPPSId() : -1; }
+  const TComPPS*              getPPS() const                                         { return m_pcPPS;                                               }
+
+  Void                        setPPSId( Int PPSId )                                  { m_iPPSId = PPSId;                                             }
+  Int                         getPPSId() const                                       { return m_iPPSId;                                              }
+  Void                        setPicOutputFlag( Bool b   )                           { m_PicOutputFlag = b;                                          }
+#if NH_MV
+  Void                        setSlicePicOrderCntLsb( Int i )                        { m_slicePicOrderCntLsb = i;                                    }
+  Int                         getSlicePicOrderCntLsb(  )  const                      { return m_slicePicOrderCntLsb;                                 }
+#endif
+  Bool                        getPicOutputFlag() const                               { return m_PicOutputFlag;                                       }
+  Void                        setSaoEnabledFlag(ChannelType chType, Bool s)          {m_saoEnabledFlag[chType] =s;                                   }
+  Bool                        getSaoEnabledFlag(ChannelType chType) const            { return m_saoEnabledFlag[chType];                              }
+  Void                        setRPS( TComReferencePictureSet *pcRPS )               { m_pcRPS = pcRPS;                                              }
+  TComReferencePictureSet*    getRPS()                                               { return m_pcRPS;                                               }
+  TComReferencePictureSet*    getLocalRPS()                                          { return &m_LocalRPS;                                           }
+
+  Void                        setRPSidx( Int iBDidx )                                { m_iBDidx = iBDidx;                                            }
+  Int                         getRPSidx() const                                      { return m_iBDidx;                                              }
+  TComRefPicListModification* getRefPicListModification()                            { return &m_RefPicListModification;                             }
+  Void                        setLastIDR(Int iIDRPOC)                                { m_iLastIDR = iIDRPOC;                                         }
+  Int                         getLastIDR() const                                     { return m_iLastIDR;                                            }
+  Void                        setAssociatedIRAPPOC(Int iAssociatedIRAPPOC)           { m_iAssociatedIRAP = iAssociatedIRAPPOC;                       }
+  Int                         getAssociatedIRAPPOC() const                           { return m_iAssociatedIRAP;                                     }
+  Void                        setAssociatedIRAPType(NalUnitType associatedIRAPType)  { m_iAssociatedIRAPType = associatedIRAPType;                   }
+  NalUnitType                 getAssociatedIRAPType() const                          { return m_iAssociatedIRAPType;                                 }
+  SliceType                   getSliceType() const                                   { return m_eSliceType;                                          }
+  Int                         getPOC() const                                         { return m_iPOC;                                                }
+  Int                         getSliceQp() const                                     { return m_iSliceQp;                                            }
+  Bool                        getDependentSliceSegmentFlag() const                   { return m_dependentSliceSegmentFlag;                           }
+  Void                        setDependentSliceSegmentFlag(Bool val)                 { m_dependentSliceSegmentFlag = val;                            }
 #if ADAPTIVE_QP_SELECTION
-  Void          setTrQuant          ( TComTrQuant* pcTrQuant ) { m_pcTrQuant = pcTrQuant; }
-  TComTrQuant*  getTrQuant          () { return m_pcTrQuant; }
-#endif
-
-  Void      setPPSId        ( Int PPSId )         { m_iPPSId = PPSId; }
-  Int       getPPSId        () { return m_iPPSId; }
-  Void      setPicOutputFlag( Bool b )         { m_PicOutputFlag = b;    }
-  Bool      getPicOutputFlag()                 { return m_PicOutputFlag; }
-#if H_MV
-  Void      setSlicePicOrderCntLsb( Int i ) { m_slicePicOrderCntLsb = i; }; 
-  Int       getSlicePicOrderCntLsb(  )      { return m_slicePicOrderCntLsb; }; 
-#endif
-  Void      setSaoEnabledFlag(Bool s) {m_saoEnabledFlag =s; }
-  Bool      getSaoEnabledFlag() { return m_saoEnabledFlag; }
-  Void      setSaoEnabledFlagChroma(Bool s) {m_saoEnabledFlagChroma =s; }       //!< set SAO Cb&Cr enabled flag
-  Bool      getSaoEnabledFlagChroma() { return m_saoEnabledFlagChroma; }        //!< get SAO Cb&Cr enabled flag
-  Void      setRPS          ( TComReferencePictureSet *pcRPS ) { m_pcRPS = pcRPS; }
-  TComReferencePictureSet*  getRPS          () { return m_pcRPS; }
-  TComReferencePictureSet*  getLocalRPS     () { return &m_LocalRPS; }
-
-  Void      setRPSidx          ( Int iBDidx ) { m_iBDidx = iBDidx; }
-  Int       getRPSidx          () { return m_iBDidx; }
-  Int       getPrevTid0POC      ()                        { return  m_prevTid0POC;       }
-  TComRefPicListModification* getRefPicListModification() { return &m_RefPicListModification; }
-  Void      setLastIDR(Int iIDRPOC)                       { m_iLastIDR = iIDRPOC; }
-  Int       getLastIDR()                                  { return m_iLastIDR; }
-  Void      setAssociatedIRAPPOC(Int iAssociatedIRAPPOC)             { m_iAssociatedIRAP = iAssociatedIRAPPOC; }
-  Int       getAssociatedIRAPPOC()                        { return m_iAssociatedIRAP; }
-  Void      setAssociatedIRAPType(NalUnitType associatedIRAPType)    { m_iAssociatedIRAPType = associatedIRAPType; }
-  NalUnitType getAssociatedIRAPType()                        { return m_iAssociatedIRAPType; }
-  SliceType getSliceType    ()                          { return  m_eSliceType;         }
-  Int       getPOC          ()                          { return  m_iPOC;           }
-  Int       getSliceQp      ()                          { return  m_iSliceQp;           }
-  Bool      getDependentSliceSegmentFlag() const        { return m_dependentSliceSegmentFlag; }
-  void      setDependentSliceSegmentFlag(Bool val)      { m_dependentSliceSegmentFlag = val; }
+  Int                         getSliceQpBase() const                                 { return m_iSliceQpBase;                                        }
+#endif
+  Int                         getSliceQpDelta() const                                { return m_iSliceQpDelta;                                       }
+  Int                         getSliceChromaQpDelta(ComponentID compID) const        { return isLuma(compID) ? 0 : m_iSliceChromaQpDelta[compID];    }
+  Bool                        getUseChromaQpAdj() const                              { return m_ChromaQpAdjEnabled;                                  }
+  Bool                        getDeblockingFilterDisable() const                     { return m_deblockingFilterDisable;                             }
+  Bool                        getDeblockingFilterOverrideFlag() const                { return m_deblockingFilterOverrideFlag;                        }
+  Int                         getDeblockingFilterBetaOffsetDiv2()const               { return m_deblockingFilterBetaOffsetDiv2;                      }
+  Int                         getDeblockingFilterTcOffsetDiv2() const                { return m_deblockingFilterTcOffsetDiv2;                        }
+
+  Int                         getNumRefIdx( RefPicList e ) const                     { return m_aiNumRefIdx[e];                                      }
+  TComPic*                    getPic()                                               { return m_pcPic;                                               }
+  TComPic*                    getRefPic( RefPicList e, Int iRefIdx)                  { return m_apcRefPicList[e][iRefIdx];                           }
+  Int                         getRefPOC( RefPicList e, Int iRefIdx)                  { return m_aiRefPOCList[e][iRefIdx];                            }
+#if NH_3D
+  Bool                        getInCmpPredAvailFlag( )                 const         { return m_inCmpPredAvailFlag;                                  }
+  Bool                        getCpAvailableFlag( )                    const         { return m_cpAvailableFlag;                                     }
+  Bool                        getInCompPredFlag( )                     const         { return m_inCmpPredFlag;                                       }
+  Void                        setInCompPredFlag( Bool b )                            { m_inCmpPredFlag = b;                                          }
+  Int                         getInCmpRefViewIdcs( Int i )             const         { return m_inCmpRefViewIdcs  [i];                               }
+  Int                         getNumCurCmpLIds( )                      const         { return (Int) m_inCmpRefViewIdcs.size();                       }
+  TComPic*                    getIvPic( Bool depthFlag, Int viewIndex) const         { return  m_ivPicsCurrPoc[ depthFlag ? 1 : 0 ][ viewIndex ];    }
+#endif                                                                                                                                               
+#if H_3D                                                                                                                                             
+  TComPic*                    getTexturePic       ()                                 { return  m_ivPicsCurrPoc[0][ m_viewIndex ];                    }
+#endif                                                                                                                                               
+#if H_3D_IC                                                                                                                                          
+  Void                        setApplyIC( Bool b )                                   { m_bApplyIC = b;                                               }
+  Bool                        getApplyIC()                                           { return m_bApplyIC;                                            }
+  Void                        xSetApplyIC();                                                                                                         
+  Void                        xSetApplyIC(Bool bUseLowLatencyICEnc);                                                                                 
+  Void                        setIcSkipParseFlag( Bool b )                           { m_icSkipParseFlag = b;                                        }
+  Bool                        getIcSkipParseFlag()                                   { return m_icSkipParseFlag;                                     }
+#endif                                                                                                                                               
+#if H_3D_ARP                                                                                                                                         
+  Void                        setBaseViewRefPicList( TComList<TComPic*> *pListPic, Int iViewIdx )      { m_pBaseViewRefPicList[iViewIdx] = pListPic; }                  
+  Void                        setARPStepNum( TComPicLists*ivPicLists );                                                                              
+  TComPic*                    getBaseViewRefPic    ( UInt uiPOC , Int iViewIdx )     { return xGetRefPic( *m_pBaseViewRefPicList[iViewIdx], uiPOC ); }
+  UInt                        getARPStepNum( )                                       { return m_nARPStepNum;                                         }  
+#endif
+  Int                         getDepth() const                                       { return m_iDepth;                                              }
+  Bool                        getColFromL0Flag() const                               { return m_colFromL0Flag;                                       }
+  UInt                        getColRefIdx() const                                   { return m_colRefIdx;                                           }
+  Void                        checkColRefIdx(UInt curSliceIdx, TComPic* pic);
+  Bool                        getIsUsedAsLongTerm(Int i, Int j) const                { return m_bIsUsedAsLongTerm[i][j];                             }
+  Void                        setIsUsedAsLongTerm(Int i, Int j, Bool value)          { m_bIsUsedAsLongTerm[i][j] = value;                            }
+  Bool                        getCheckLDC() const                                    { return m_bCheckLDC;                                           }
+  Bool                        getMvdL1ZeroFlag() const                               { return m_bLMvdL1Zero;                                         }
+  Int                         getNumRpsCurrTempList() const;
+  Int                         getList1IdxToList0Idx( Int list1Idx ) const            { return m_list1IdxToList0Idx[list1Idx];                        }
+  Void                        setReferenced(Bool b)                                  { m_bRefenced = b;                                              }
+  Bool                        isReferenced() const                                   { return m_bRefenced;                                           }
+  Bool                        isReferenceNalu() const                                { return ((getNalUnitType() <= NAL_UNIT_RESERVED_VCL_R15) && (getNalUnitType()%2 != 0)) || ((getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) && (getNalUnitType() <= NAL_UNIT_RESERVED_IRAP_VCL23) ); }
+  Void                        setPOC( Int i )                                        { m_iPOC              = i; }
+  Void                        setNalUnitType( NalUnitType e )                        { m_eNalUnitType      = e;                                      }
+  NalUnitType                 getNalUnitType() const                                 { return m_eNalUnitType;                                        }
+  Bool                        getRapPicFlag() const;
+  Bool                        getIdrPicFlag() const                                  { return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP; }
+  Bool                        isIRAP() const                                         { return (getNalUnitType() >= 16) && (getNalUnitType() <= 23);  }
+  Void                        checkCRA(const TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic);
+  Void                        decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, const bool bEfficientFieldIRAPEnabled);
+  Void                        setSliceType( SliceType e )                            { m_eSliceType        = e;                                      }
+  Void                        setSliceQp( Int i )                                    { m_iSliceQp          = i;                                      }
 #if ADAPTIVE_QP_SELECTION
-  Int       getSliceQpBase  ()                          { return  m_iSliceQpBase;       }
-#endif
-  Int       getSliceQpDelta ()                          { return  m_iSliceQpDelta;      }
-  Int       getSliceQpDeltaCb ()                          { return  m_iSliceQpDeltaCb;      }
-  Int       getSliceQpDeltaCr ()                          { return  m_iSliceQpDeltaCr;      }
-  Bool      getDeblockingFilterDisable()                { return  m_deblockingFilterDisable; }
-  Bool      getDeblockingFilterOverrideFlag()           { return  m_deblockingFilterOverrideFlag; }
-  Int       getDeblockingFilterBetaOffsetDiv2()         { return  m_deblockingFilterBetaOffsetDiv2; }
-  Int       getDeblockingFilterTcOffsetDiv2()           { return  m_deblockingFilterTcOffsetDiv2; }
-
-  Int       getNumRefIdx        ( RefPicList e )                { return  m_aiNumRefIdx[e];             }
-  TComPic*  getPic              ()                              { return  m_pcPic;                      }
-  TComPic*  getRefPic           ( RefPicList e, Int iRefIdx)    { return  m_apcRefPicList[e][iRefIdx];  }
-  Int       getRefPOC           ( RefPicList e, Int iRefIdx)    { return  m_aiRefPOCList[e][iRefIdx];   }
-#if H_3D
-  Bool      getInCmpPredAvailFlag( )                             { return m_inCmpPredAvailFlag;    } 
-  Bool      getCpAvailableFlag( )                             { return m_cpAvailableFlag;    } 
-  Bool      getInCompPredFlag( )                                 { return m_inCmpPredFlag;         }    
-  Void      setInCompPredFlag( Bool b )                          { m_inCmpPredFlag = b;            }    
-  Int       getInCmpRefViewIdcs( Int i )                         { return m_inCmpRefViewIdcs  [i]; }
-  Int       getNumCurCmpLIds( )                                  { return (Int) m_inCmpRefViewIdcs.size(); } 
-  TComPic*  getIvPic            ( Bool depthFlag, Int viewIndex){ return  m_ivPicsCurrPoc[ depthFlag ? 1 : 0 ][ viewIndex ]; }
-#endif
-#if H_3D
-  TComPic*  getTexturePic       ()                              { return  m_ivPicsCurrPoc[0][ m_viewIndex ]; }
-#endif
-#if H_3D_IC
-  Void      setApplyIC( Bool b )                                { m_bApplyIC = b; }
-  Bool      getApplyIC()                                        { return m_bApplyIC; }
-  Void      xSetApplyIC();
-  Void      xSetApplyIC(Bool bUseLowLatencyICEnc);
-  Void      setIcSkipParseFlag( Bool b )                        { m_icSkipParseFlag = b; }
-  Bool      getIcSkipParseFlag()                                { return m_icSkipParseFlag; }
-#endif
-#if H_3D_ARP
-  Void      setBaseViewRefPicList( TComList<TComPic*> *pListPic, Int iViewIdx )      { m_pBaseViewRefPicList[iViewIdx] = pListPic;                   }
-  Void      setARPStepNum( TComPicLists*ivPicLists );
-  TComPic*  getBaseViewRefPic    ( UInt uiPOC , Int iViewIdx )                       { return xGetRefPic( *m_pBaseViewRefPicList[iViewIdx], uiPOC ); }
-  UInt      getARPStepNum( )                                                         { return m_nARPStepNum;                                         }  
-#endif
-  Int       getDepth            ()                              { return  m_iDepth;                     }
-  UInt      getColFromL0Flag    ()                              { return  m_colFromL0Flag;              }
-  UInt      getColRefIdx        ()                              { return  m_colRefIdx;                  }
-  Void      checkColRefIdx      (UInt curSliceIdx, TComPic* pic);
-  Bool      getIsUsedAsLongTerm (Int i, Int j)                  { return m_bIsUsedAsLongTerm[i][j]; }
-  Void      setIsUsedAsLongTerm (Int i, Int j, Bool value)      { m_bIsUsedAsLongTerm[i][j] = value; }
-  Bool      getCheckLDC     ()                                  { return m_bCheckLDC; }
-  Bool      getMvdL1ZeroFlag ()                                  { return m_bLMvdL1Zero;    }
-  Int       getNumRpsCurrTempList();
-  Int       getList1IdxToList0Idx ( Int list1Idx )               { return m_list1IdxToList0Idx[list1Idx]; }
-  Void      setReferenced(Bool b)                               { m_bRefenced = b; }
-  Bool      isReferenced()                                      { return m_bRefenced; }
-  Bool      isReferenceNalu()                                   { return ((getNalUnitType() <= NAL_UNIT_RESERVED_VCL_R15) && (getNalUnitType()%2 != 0)) || ((getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) && (getNalUnitType() <= NAL_UNIT_RESERVED_IRAP_VCL23) ); }
-  Void      setPOC              ( Int i )                       { m_iPOC              = i; if ((getTLayer()==0) && (isReferenceNalu() && (getNalUnitType()!=NAL_UNIT_CODED_SLICE_RASL_R)&& (getNalUnitType()!=NAL_UNIT_CODED_SLICE_RADL_R))) {m_prevTid0POC=i;} }
-  Void      setNalUnitType      ( NalUnitType e )               { m_eNalUnitType      = e;      }
-  NalUnitType getNalUnitType    () const                        { return m_eNalUnitType;        }
-  Bool      getRapPicFlag       ();  
-  Bool      getIdrPicFlag       ()                              { return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP; }
-  Bool      isIRAP              () const                        { return (getNalUnitType() >= 16) && (getNalUnitType() <= 23); }  
-  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic);
-  Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic);
-  Void      setSliceType        ( SliceType e )                 { m_eSliceType        = e;      }
-  Void      setSliceQp          ( Int i )                       { m_iSliceQp          = i;      }
-#if ADAPTIVE_QP_SELECTION
-  Void      setSliceQpBase      ( Int i )                       { m_iSliceQpBase      = i;      }
-#endif
-  Void      setSliceQpDelta     ( Int i )                       { m_iSliceQpDelta     = i;      }
-  Void      setSliceQpDeltaCb   ( Int i )                       { m_iSliceQpDeltaCb   = i;      }
-  Void      setSliceQpDeltaCr   ( Int i )                       { m_iSliceQpDeltaCr   = i;      }
-  Void      setDeblockingFilterDisable( Bool b )                { m_deblockingFilterDisable= b;      }
-  Void      setDeblockingFilterOverrideFlag( Bool b )           { m_deblockingFilterOverrideFlag = b; }
-  Void      setDeblockingFilterBetaOffsetDiv2( Int i )          { m_deblockingFilterBetaOffsetDiv2 = i; }
-  Void      setDeblockingFilterTcOffsetDiv2( Int i )            { m_deblockingFilterTcOffsetDiv2 = i; }
-  
-  Void      setRefPic           ( TComPic* p, RefPicList e, Int iRefIdx ) { m_apcRefPicList[e][iRefIdx] = p; }
-  Void      setRefPOC           ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefPOCList[e][iRefIdx] = i; }
-  Void      setNumRefIdx        ( RefPicList e, Int i )         { m_aiNumRefIdx[e]    = i;      }
-  Void      setPic              ( TComPic* p )                  { m_pcPic             = p;      }
-  Void      setDepth            ( Int iDepth )                  { m_iDepth            = iDepth; }
-  
-#if H_MV
-  Void      setPocBeforeReset   ( Int i )                       { m_iPOCBeforeReset = i; }
-  Int       getPocBeforeReset   ( )                             { return m_iPOCBeforeReset; }
-  Int       getRefLayerId        ( RefPicList e, Int iRefIdx)    { return  m_aiRefLayerIdList[e][iRefIdx]; }
-  Void      setRefLayerId        ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefLayerIdList[e][iRefIdx] = i; }
-  Void      getTempRefPicLists   ( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1,                                     
-                                   std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int& numPocTotalCurr, Bool checkNumPocTotalCurr = false );
-
-  Void      setRefPicList        ( std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int numPocTotalCurr, Bool checkNumPocTotalCurr = false ); 
+  Void                        setSliceQpBase( Int i )                                { m_iSliceQpBase      = i;                                      }
+#endif
+  Void                        setSliceQpDelta( Int i )                               { m_iSliceQpDelta     = i;                                      }
+  Void                        setSliceChromaQpDelta( ComponentID compID, Int i )     { m_iSliceChromaQpDelta[compID] = isLuma(compID) ? 0 : i;       }
+  Void                        setUseChromaQpAdj( Bool b )                            { m_ChromaQpAdjEnabled = b;                                     }
+  Void                        setDeblockingFilterDisable( Bool b )                   { m_deblockingFilterDisable= b;                                 }
+  Void                        setDeblockingFilterOverrideFlag( Bool b )              { m_deblockingFilterOverrideFlag = b;                           }
+  Void                        setDeblockingFilterBetaOffsetDiv2( Int i )             { m_deblockingFilterBetaOffsetDiv2 = i;                         }
+  Void                        setDeblockingFilterTcOffsetDiv2( Int i )               { m_deblockingFilterTcOffsetDiv2 = i;                           }
+
+  Void                        setRefPic( TComPic* p, RefPicList e, Int iRefIdx )     { m_apcRefPicList[e][iRefIdx] = p;                              }
+  Void                        setRefPOC( Int i, RefPicList e, Int iRefIdx )          { m_aiRefPOCList[e][iRefIdx] = i;                               }
+  Void                        setNumRefIdx( RefPicList e, Int i )                    { m_aiNumRefIdx[e]    = i;                                      }
+  Void                        setPic( TComPic* p )                                   { m_pcPic             = p;                                      }
+  Void                        setDepth( Int iDepth )                                 { m_iDepth            = iDepth;                                 }
+#if NH_MV
+  Void                        setPocBeforeReset( Int i )                             { m_iPOCBeforeReset = i;                                        }
+  Int                         getPocBeforeReset( )                                   { return m_iPOCBeforeReset;                                     }
+  Int                         getRefLayerId( RefPicList e, Int iRefIdx)              { return  m_aiRefLayerIdList[e][iRefIdx];                       }
+  Void                        setRefLayerId( Int i, RefPicList e, Int iRefIdx )      { m_aiRefLayerIdList[e][iRefIdx] = i;                        }
+  Void                        getTempRefPicLists   ( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1,                                     
+                                                     std::vector<TComPic*> rpsCurrList[2], BoolAry1d usedAsLongTerm[2], Int& numPocTotalCurr, Bool checkNumPocTotalCurr = false );
+                              
+  Void                        setRefPicList        ( std::vector<TComPic*> rpsCurrList[2], BoolAry1d usedAsLongTerm[2], Int numPocTotalCurr, Bool checkNumPocTotalCurr = false ); 
 #else
-  Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
-#endif
-  Void      setRefPOCList       ();
-  Void      setColFromL0Flag    ( UInt colFromL0 ) { m_colFromL0Flag = colFromL0; }
-  Void      setColRefIdx        ( UInt refIdx) { m_colRefIdx = refIdx; }
-  Void      setCheckLDC         ( Bool b )                      { m_bCheckLDC = b; }
-  Void      setMvdL1ZeroFlag     ( Bool b)                       { m_bLMvdL1Zero = b; }
-
-  Bool      isIntra         ()                          { return  m_eSliceType == I_SLICE;  }
-  Bool      isInterB        ()                          { return  m_eSliceType == B_SLICE;  }
-  Bool      isInterP        ()                          { return  m_eSliceType == P_SLICE;  }
-  
-  Void      setLambdas ( const Double lambdas[3] ) { for (Int component = 0; component < 3; component++) m_lambdas[component] = lambdas[component]; }
-  const Double* getLambdas() const { return m_lambdas; }
-  
-  Void      initEqualRef();
-  Bool      isEqualRef  ( RefPicList e, Int iRefIdx1, Int iRefIdx2 )
+  Void                        setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
+#endif
+  Void                        setRefPOCList();
+  Void                        setColFromL0Flag( Bool colFromL0 )                     { m_colFromL0Flag = colFromL0;                                  }
+  Void                        setColRefIdx( UInt refIdx)                             { m_colRefIdx = refIdx;                                         }
+  Void                        setCheckLDC( Bool b )                                  { m_bCheckLDC = b;                                              }
+  Void                        setMvdL1ZeroFlag( Bool b)                              { m_bLMvdL1Zero = b;                                            }
+
+  Bool                        isIntra() const                                        { return m_eSliceType == I_SLICE;                               }
+  Bool                        isInterB() const                                       { return m_eSliceType == B_SLICE;                               }
+  Bool                        isInterP() const                                       { return m_eSliceType == P_SLICE;                               }
+
+  Void                        setLambdas( const Double lambdas[MAX_NUM_COMPONENT] )  { for (Int component = 0; component < MAX_NUM_COMPONENT; component++) m_lambdas[component] = lambdas[component]; }
+  const Double*               getLambdas() const                                     { return m_lambdas;                                             }
+
+  Void                        initEqualRef();
+  Bool                        isEqualRef( RefPicList e, Int iRefIdx1, Int iRefIdx2 )
   {
-    if (iRefIdx1 < 0 || iRefIdx2 < 0) return false;
-    return m_abEqualRef[e][iRefIdx1][iRefIdx2];
+    assert(e<NUM_REF_PIC_LIST_01);
+    if (iRefIdx1 < 0 || iRefIdx2 < 0)
+    {
+      return false;
+    }
+    else
+    {
+      return m_abEqualRef[e][iRefIdx1][iRefIdx2];
+    }
   }
-  
-  Void setEqualRef( RefPicList e, Int iRefIdx1, Int iRefIdx2, Bool b)
+
+  Void                        setEqualRef( RefPicList e, Int iRefIdx1, Int iRefIdx2, Bool b)
   {
+    assert(e<NUM_REF_PIC_LIST_01);
     m_abEqualRef[e][iRefIdx1][iRefIdx2] = m_abEqualRef[e][iRefIdx2][iRefIdx1] = b;
   }
-  
-  static Void      sortPicList         ( TComList<TComPic*>& rcListPic );
-  Void setList1IdxToList0Idx();
-
-  UInt getTLayer             ()                            { return m_uiTLayer;                      }
-  Void setTLayer             ( UInt uiTLayer )             { m_uiTLayer = uiTLayer;                  }
-#if H_MV
-  Int getTemporalId          ( )                           { return (Int) m_uiTLayer;                }
-#endif
-
-  Void setTLayerInfo( UInt uiTLayer );
-  Void decodingMarking( TComList<TComPic*>& rcListPic, Int iGOPSIze, Int& iMaxRefPicNum ); 
-  Void checkLeadingPictureRestrictions( TComList<TComPic*>& rcListPic );
-  Void applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
-#if H_MV
-  Void createInterLayerReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1 );
-  static Void markIvRefPicsAsShortTerm    ( std::vector<TComPic*> refPicSetInterLayer0, std::vector<TComPic*> refPicSetInterLayer1 );
-  static Void markCurrPic                 ( TComPic* currPic );
-  Void        printRefPicList();
-#endif
-  Bool isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic );
-  Bool isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic );
-#if ALLOW_RECOVERY_POINT_AS_RAP
-  Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0, Bool bUseRecoveryPoint = false);
-  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess = 0, Bool bUseRecoveryPoint = false);
-#else
-  Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0);
-  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP);
-#endif
-
-  Void setMaxNumMergeCand               (UInt val )         { m_maxNumMergeCand = val;                    }
-  UInt getMaxNumMergeCand               ()                  { return m_maxNumMergeCand;                   }
-
-#if SETTING_NO_OUT_PIC_PRIOR
-  Void setNoOutputPriorPicsFlag              ( Bool val )         { m_noOutputPriorPicsFlag = val;                    }
-  Bool getNoOutputPriorPicsFlag              ()                   { return m_noOutputPriorPicsFlag;                   }
-
-  Void setNoRaslOutputFlag              ( Bool val )         { m_noRaslOutputFlag = val;                    }
-  Bool getNoRaslOutputFlag              ()                   { return m_noRaslOutputFlag;                   }
-
-  Void setHandleCraAsBlaFlag              ( Bool val )         { m_handleCraAsBlaFlag = val;                    }
-  Bool getHandleCraAsBlaFlag              ()                   { return m_handleCraAsBlaFlag;                   }
-#endif
-
-  Void setSliceMode                     ( UInt uiMode )     { m_sliceMode = uiMode;                     }
-  UInt getSliceMode                     ()                  { return m_sliceMode;                       }
-  Void setSliceArgument                 ( UInt uiArgument ) { m_sliceArgument = uiArgument;             }
-  UInt getSliceArgument                 ()                  { return m_sliceArgument;                   }
-  Void setSliceCurStartCUAddr           ( UInt uiAddr )     { m_sliceCurStartCUAddr = uiAddr;           }
-  UInt getSliceCurStartCUAddr           ()                  { return m_sliceCurStartCUAddr;             }
-  Void setSliceCurEndCUAddr             ( UInt uiAddr )     { m_sliceCurEndCUAddr = uiAddr;             }
-  UInt getSliceCurEndCUAddr             ()                  { return m_sliceCurEndCUAddr;               }
-  Void setSliceIdx                      ( UInt i)           { m_sliceIdx = i;                           }
-  UInt getSliceIdx                      ()                  { return  m_sliceIdx;                       }
-  Void copySliceInfo                    (TComSlice *pcSliceSrc);
-  Void setSliceSegmentMode              ( UInt uiMode )     { m_sliceSegmentMode = uiMode;              }
-  UInt getSliceSegmentMode              ()                  { return m_sliceSegmentMode;                }
-  Void setSliceSegmentArgument          ( UInt uiArgument ) { m_sliceSegmentArgument = uiArgument;      }
-  UInt getSliceSegmentArgument          ()                  { return m_sliceSegmentArgument;            }
-  Void setSliceSegmentCurStartCUAddr    ( UInt uiAddr )     { m_sliceSegmentCurStartCUAddr = uiAddr;    }
-  UInt getSliceSegmentCurStartCUAddr    ()                  { return m_sliceSegmentCurStartCUAddr;      }
-  Void setSliceSegmentCurEndCUAddr      ( UInt uiAddr )     { m_sliceSegmentCurEndCUAddr = uiAddr;      }
-  UInt getSliceSegmentCurEndCUAddr      ()                  { return m_sliceSegmentCurEndCUAddr;        }
-  Void setNextSlice                     ( Bool b )          { m_nextSlice = b;                           }
-  Bool isNextSlice                      ()                  { return m_nextSlice;                        }
-  Void setNextSliceSegment              ( Bool b )          { m_nextSliceSegment = b;                    }
-  Bool isNextSliceSegment               ()                  { return m_nextSliceSegment;                 }
-  Void setSliceBits                     ( UInt uiVal )      { m_sliceBits = uiVal;                      }
-  UInt getSliceBits                     ()                  { return m_sliceBits;                       }  
-  Void setSliceSegmentBits              ( UInt uiVal )      { m_sliceSegmentBits = uiVal;            }
-  UInt getSliceSegmentBits              ()                  { return m_sliceSegmentBits;             }
-  Void setFinalized                     ( Bool uiVal )      { m_bFinalized = uiVal;                       }
-  Bool getFinalized                     ()                  { return m_bFinalized;                        }
-  Void  setWpScaling    ( wpScalingParam  wp[2][MAX_NUM_REF][3] ) { memcpy(m_weightPredTable, wp, sizeof(wpScalingParam)*2*MAX_NUM_REF*3); }
-  Void  getWpScaling    ( RefPicList e, Int iRefIdx, wpScalingParam *&wp);
-
-  Void  resetWpScaling  ();
-  Void  initWpScaling   ();
-  inline Bool applyWP   () { return( (m_eSliceType==P_SLICE && m_pcPPS->getUseWP()) || (m_eSliceType==B_SLICE && m_pcPPS->getWPBiPred()) ); }
-
-  Void  setWpAcDcParam  ( wpACDCParam wp[3] ) { memcpy(m_weightACDCParam, wp, sizeof(wpACDCParam)*3); }
-  Void  getWpAcDcParam  ( wpACDCParam *&wp );
-  Void  initWpAcDcParam ();
-  
-  Void setTileLocationCount             ( UInt cnt )               { return m_tileByteLocation.resize(cnt);    }
-  UInt getTileLocationCount             ()                         { return (UInt) m_tileByteLocation.size();  }
-  Void setTileLocation                  ( Int idx, UInt location ) { assert (idx<m_tileByteLocation.size());
-                                                                     m_tileByteLocation[idx] = location;       }
-  Void addTileLocation                  ( UInt location )          { m_tileByteLocation.push_back(location);   }
-  UInt getTileLocation                  ( Int idx )                { return m_tileByteLocation[idx];           }
-
-  Void setTileOffstForMultES            (UInt uiOffset )      { m_uiTileOffstForMultES = uiOffset;        }
-  UInt getTileOffstForMultES            ()                    { return m_uiTileOffstForMultES;            }
-  Void allocSubstreamSizes              ( UInt uiNumSubstreams );
-  UInt* getSubstreamSizes               ()                  { return m_puiSubstreamSizes; }
-  Void  setScalingList              ( TComScalingList* scalingList ) { m_scalingList = scalingList; }
-  TComScalingList*   getScalingList ()                               { return m_scalingList; }
-  Void  setDefaultScalingList       ();
-  Bool  checkDefaultScalingList     ();
-  Void      setCabacInitFlag  ( Bool val ) { m_cabacInitFlag = val;      }  //!< set CABAC initial flag 
-  Bool      getCabacInitFlag  ()           { return m_cabacInitFlag;     }  //!< get CABAC initial flag 
-  Void      setNumEntryPointOffsets(Int val)  { m_numEntryPointOffsets = val;     }
-  Int       getNumEntryPointOffsets()         { return m_numEntryPointOffsets;    }
-  Bool      getTemporalLayerNonReferenceFlag()       { return m_temporalLayerNonReferenceFlag;}
-  Void      setTemporalLayerNonReferenceFlag(Bool x) { m_temporalLayerNonReferenceFlag = x;}
-  Void      setLFCrossSliceBoundaryFlag     ( Bool   val )    { m_LFCrossSliceBoundaryFlag = val; }
-  Bool      getLFCrossSliceBoundaryFlag     ()                { return m_LFCrossSliceBoundaryFlag;} 
-
-  Void      setEnableTMVPFlag     ( Bool   b )    { m_enableTMVPFlag = b; }
-  Bool      getEnableTMVPFlag     ()              { return m_enableTMVPFlag;}
-#if H_MV
-  Void      setAvailableForTMVPRefFlag     ( Bool   b )    { m_availableForTMVPRefFlag = b; }
-  Bool      getAvailableForTMVPRefFlag     ()              { return m_availableForTMVPRefFlag;}
-#endif
-
-#if H_MV
-  Void      setLayerId            ( Int layerId )    { m_layerId      = layerId; }
-  Int       getLayerId            ()                 { return m_layerId;    }
-  Int       getLayerIdInVps       ()                 { return getVPS()->getLayerIdInVps( m_layerId ); }; 
-  Void      setViewId             ( Int viewId )     { m_viewId = viewId;   }
-  Int       getViewId             ()                 { return m_viewId;     }
-  Void      setViewIndex          ( Int viewIndex )  { m_viewIndex = viewIndex;   }
-  Int       getViewIndex          ()                 { return m_viewIndex;     }
-#if H_3D
+
+  static Void                 sortPicList( TComList<TComPic*>& rcListPic );
+  Void                        setList1IdxToList0Idx();
+
+  UInt                        getTLayer() const                                      { return m_uiTLayer;                                            }
+  Void                        setTLayer( UInt uiTLayer )                             { m_uiTLayer = uiTLayer;                                        }
+#if NH_MV
+  Int                         getTemporalId          ( )                             { return (Int) m_uiTLayer;                                      }
+#endif
+
+  Void                        setTLayerInfo( UInt uiTLayer );
+  Void                        decodingMarking( TComList<TComPic*>& rcListPic, Int iGOPSIze, Int& iMaxRefPicNum );
+  Void                        checkLeadingPictureRestrictions( TComList<TComPic*>& rcListPic );
+  Void                        applyReferencePictureSet( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *RPSList);
+#if NH_MV
+  Void                        createInterLayerReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1 );
+  static Void                 markIvRefPicsAsShortTerm    ( std::vector<TComPic*> refPicSetInterLayer0, std::vector<TComPic*> refPicSetInterLayer1 );
+  static Void                 markCurrPic                 ( TComPic* currPic );
+  Void                        printRefPicList();
+#endif
+  Bool                        isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic );
+  Bool                        isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic );
+  Int                         checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0, Bool bUseRecoveryPoint = false);
+  Void                        createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess, Bool bUseRecoveryPoint, const Bool bEfficientFieldIRAPEnabled);
+  Void                        setMaxNumMergeCand(UInt val )                          { m_maxNumMergeCand = val;                                      }
+  UInt                        getMaxNumMergeCand() const                             { return m_maxNumMergeCand;                                     }
+
+  Void                        setNoOutputPriorPicsFlag( Bool val )                   { m_noOutputPriorPicsFlag = val;                                }
+  Bool                        getNoOutputPriorPicsFlag() const                       { return m_noOutputPriorPicsFlag;                               }
+
+  Void                        setNoRaslOutputFlag( Bool val )                        { m_noRaslOutputFlag = val;                                     }
+  Bool                        getNoRaslOutputFlag() const                            { return m_noRaslOutputFlag;                                    }
+
+  Void                        setHandleCraAsBlaFlag( Bool val )                      { m_handleCraAsBlaFlag = val;                                   }
+  Bool                        getHandleCraAsBlaFlag() const                          { return m_handleCraAsBlaFlag;                                  }
+
+  Void                        setSliceMode( SliceConstraint mode )                   { m_sliceMode = mode;                                           }
+  SliceConstraint             getSliceMode() const                                   { return m_sliceMode;                                           }
+  Void                        setSliceArgument( UInt uiArgument )                    { m_sliceArgument = uiArgument;                                 }
+  UInt                        getSliceArgument() const                               { return m_sliceArgument;                                       }
+  Void                        setSliceCurStartCtuTsAddr( UInt ctuTsAddr )            { m_sliceCurStartCtuTsAddr = ctuTsAddr;                         } // CTU Tile-scan address (as opposed to raster-scan)
+  UInt                        getSliceCurStartCtuTsAddr() const                      { return m_sliceCurStartCtuTsAddr;                              } // CTU Tile-scan address (as opposed to raster-scan)
+  Void                        setSliceCurEndCtuTsAddr( UInt ctuTsAddr )              { m_sliceCurEndCtuTsAddr = ctuTsAddr;                           } // CTU Tile-scan address (as opposed to raster-scan)
+  UInt                        getSliceCurEndCtuTsAddr() const                        { return m_sliceCurEndCtuTsAddr;                                } // CTU Tile-scan address (as opposed to raster-scan)
+  Void                        setSliceIdx( UInt i)                                   { m_sliceIdx = i;                                               }
+  UInt                        getSliceIdx() const                                    { return  m_sliceIdx;                                           }
+  Void                        copySliceInfo(TComSlice *pcSliceSrc);
+  Void                        setSliceSegmentMode( SliceConstraint mode )            { m_sliceSegmentMode = mode;                                    }
+  SliceConstraint             getSliceSegmentMode() const                            { return m_sliceSegmentMode;                                    }
+  Void                        setSliceSegmentArgument( UInt uiArgument )             { m_sliceSegmentArgument = uiArgument;                          }
+  UInt                        getSliceSegmentArgument() const                        { return m_sliceSegmentArgument;                                }
+  Void                        setSliceSegmentCurStartCtuTsAddr( UInt ctuTsAddr )     { m_sliceSegmentCurStartCtuTsAddr = ctuTsAddr;                  } // CTU Tile-scan address (as opposed to raster-scan)
+  UInt                        getSliceSegmentCurStartCtuTsAddr() const               { return m_sliceSegmentCurStartCtuTsAddr;                       } // CTU Tile-scan address (as opposed to raster-scan)
+  Void                        setSliceSegmentCurEndCtuTsAddr( UInt ctuTsAddr )       { m_sliceSegmentCurEndCtuTsAddr = ctuTsAddr;                    } // CTU Tile-scan address (as opposed to raster-scan)
+  UInt                        getSliceSegmentCurEndCtuTsAddr() const                 { return m_sliceSegmentCurEndCtuTsAddr;                         } // CTU Tile-scan address (as opposed to raster-scan)
+  Void                        setSliceBits( UInt uiVal )                             { m_sliceBits = uiVal;                                          }
+  UInt                        getSliceBits() const                                   { return m_sliceBits;                                           }
+  Void                        setSliceSegmentBits( UInt uiVal )                      { m_sliceSegmentBits = uiVal;                                   }
+  UInt                        getSliceSegmentBits() const                            { return m_sliceSegmentBits;                                    }
+  Void                        setFinalized( Bool uiVal )                             { m_bFinalized = uiVal;                                         }
+  Bool                        getFinalized() const                                   { return m_bFinalized;                                          }
+  Bool                        testWeightPred( ) const                                { return m_bTestWeightPred;                                     }
+  Void                        setTestWeightPred( Bool bValue )                       { m_bTestWeightPred = bValue;                                   }
+  Bool                        testWeightBiPred( ) const                              { return m_bTestWeightBiPred;                                   }
+  Void                        setTestWeightBiPred( Bool bValue )                     { m_bTestWeightBiPred = bValue;                                 }
+  Void                        setWpScaling( WPScalingParam  wp[NUM_REF_PIC_LIST_01][MAX_NUM_REF][MAX_NUM_COMPONENT] )
+  {
+    memcpy(m_weightPredTable, wp, sizeof(WPScalingParam)*NUM_REF_PIC_LIST_01*MAX_NUM_REF*MAX_NUM_COMPONENT);
+  }
+
+  Void                        getWpScaling( RefPicList e, Int iRefIdx, WPScalingParam *&wp);
+
+  Void                        resetWpScaling();
+  Void                        initWpScaling(const TComSPS *sps);
+
+  Void                        setWpAcDcParam( WPACDCParam wp[MAX_NUM_COMPONENT] )
+  {
+    memcpy(m_weightACDCParam, wp, sizeof(WPACDCParam)*MAX_NUM_COMPONENT);
+  }
+
+  Void                        getWpAcDcParam( WPACDCParam *&wp );
+  Void                        initWpAcDcParam();
+
+  Void                        clearSubstreamSizes( )                                 { return m_substreamSizes.clear();                              }
+  UInt                        getNumberOfSubstreamSizes( )                           { return (UInt) m_substreamSizes.size();                        }
+  Void                        addSubstreamSize( UInt size )                          { m_substreamSizes.push_back(size);                             }
+  UInt                        getSubstreamSize( Int idx )                            { assert(idx<getNumberOfSubstreamSizes()); return m_substreamSizes[idx]; }
+
+  Void                        setCabacInitFlag( Bool val )                           { m_cabacInitFlag = val;                                        } //!< set CABAC initial flag
+  Bool                        getCabacInitFlag()                                     { return m_cabacInitFlag;                                       } //!< get CABAC initial flag
+  Bool                        getTemporalLayerNonReferenceFlag()                     { return m_temporalLayerNonReferenceFlag;                       }
+  Void                        setTemporalLayerNonReferenceFlag(Bool x)               { m_temporalLayerNonReferenceFlag = x;                          }
+  Void                        setLFCrossSliceBoundaryFlag( Bool   val )              { m_LFCrossSliceBoundaryFlag = val;                             }
+  Bool                        getLFCrossSliceBoundaryFlag()                          { return m_LFCrossSliceBoundaryFlag;                            }
+
+  Void                        setEnableTMVPFlag( Bool   b )                          { m_enableTMVPFlag = b;                                         }
+  Bool                        getEnableTMVPFlag()                                    { return m_enableTMVPFlag;                                      }
+
+  Void                        setEncCABACTableIdx( SliceType idx )                   { m_encCABACTableIdx = idx;                                     }
+  SliceType                   getEncCABACTableIdx() const                            { return m_encCABACTableIdx;                                    }
+
+#if NH_MV
+  Void                        setAvailableForTMVPRefFlag( Bool   b )                 { m_availableForTMVPRefFlag = b;                                }
+  Bool                        getAvailableForTMVPRefFlag()                           { return m_availableForTMVPRefFlag;                             }
+
+  Void                        setLayerId     ( Int layerId )                         { m_layerId      = layerId;                                     }
+  Int                         getLayerId     ()                 const                { return m_layerId;                                             }
+  Int                         getLayerIdInVps()                 const                { return getVPS()->getLayerIdInVps( m_layerId );                }
+  Void                        setViewId      ( Int viewId )                          { m_viewId = viewId;                                            }
+  Int                         getViewId      ()                 const                { return m_viewId;                                              }
+  Void                        setViewIndex   ( Int viewIndex )                       { m_viewIndex = viewIndex;                                      }
+  Int                         getViewIndex   ()                 const                { return m_viewIndex;                                           }
+#if NH_3D
 #if H_3D_TMVP
-  Void      generateAlterRefforTMVP ();   
-  Void      setAlterRefIdx          ( RefPicList e, Int i ) { m_aiAlterRefIdx[e]    = i;      }
-  Int       getAlterRefIdx          ( RefPicList e )        { return  m_aiAlterRefIdx[e];     }
-#endif
-#if H_3D_ARP
-  Int       getFirstTRefIdx        ( RefPicList e )                { return  m_aiFirstTRefIdx[e];     }
-  Void      setFirstTRefIdx        ( RefPicList e, Int i )         { m_aiFirstTRefIdx[e]    = i;      }
-  Bool      getArpRefPicAvailable( RefPicList e, Int viewIdx) {return m_arpRefPicAvailable[e][getVPS()->getLayerIdInNuh(viewIdx, 0)]; }
-  std::vector<Int> getPocsInCurrRPSs()                             { return m_pocsInCurrRPSs; }; 
-#endif
-  Void      setIsDepth            ( Bool isDepth )   { m_isDepth = isDepth; }
-  Bool      getIsDepth            ()                 { return m_isDepth; }
-  Void      setCamparaSlice       ( Int** aaiScale = 0, Int** aaiOffset = 0 );
-  Int*      getCodedScale         ()  { return m_aaiCodedScale [0]; }
-  Int*      getCodedOffset        ()  { return m_aaiCodedOffset[0]; }
-  Int*      getInvCodedScale      ()  { return m_aaiCodedScale [1]; }
-  Int*      getInvCodedOffset     ()  { return m_aaiCodedOffset[1]; }
-  Void      setCpScale( Int j, Int  val ) { m_aaiCodedScale[0][j] = val; } 
-  Int       getCpScale( Int j ) { return m_aaiCodedScale[0][j]; } 
-            
-  Void      setCpOff( Int j, Int  val ) { m_aaiCodedOffset[0][j] = val; } 
-  Int       getCpOff( Int j ) { return m_aaiCodedOffset[0][j]; } 
-            
-  Void      setCpInvScale( Int j, Int  val ) { m_aaiCodedScale[1][j] = val; } 
-  Int       getCpInvScale( Int j ) { return m_aaiCodedScale[1][j]; } 
-            
-  Void      setCpInvOff( Int j, Int  val ) { m_aaiCodedOffset[1][j] = val; } 
-  Int       getCpInvOff( Int j ) { return m_aaiCodedOffset[1][j]; } 
-
-#endif
-#endif
-#if H_3D
-  Void    setIvPicLists( TComPicLists* m_ivPicLists );
-  Void    setDepthToDisparityLUTs();
-
-  Int* getDepthToDisparityB( Int refViewIdx ) { return m_depthToDisparityB[ getVPS()->getVoiInVps( refViewIdx) ]; }; 
-  Int* getDepthToDisparityF( Int refViewIdx ) { return m_depthToDisparityF[ getVPS()->getVoiInVps( refViewIdx) ]; }; 
-#endif
-#if H_3D_IC
-  Void    setICEnableCandidate( Int* ICEnableCandidate)   { m_aICEnableCandidate = ICEnableCandidate; };
-  Void    setICEnableNum( Int* ICEnableNum)   { m_aICEnableNum = ICEnableNum; };
-  Void    setICEnableCandidate( UInt layer, Int value)   { m_aICEnableCandidate[ layer ] = value; };
-  Void    setICEnableNum( UInt layer, Int value)   { m_aICEnableNum[ layer ] = value; };
-
-  Int    getICEnableCandidate( Int layer){ return  m_aICEnableCandidate[ layer ]; }; 
-  Int    getICEnableNum( Int layer){ return m_aICEnableNum[ layer ]; }; 
-#endif
-#if H_MV
+  Void                        generateAlterRefforTMVP ();   
+  Void                        setAlterRefIdx          ( RefPicList e, Int i )        { m_aiAlterRefIdx[e]    = i;                                    }
+  Int                         getAlterRefIdx          ( RefPicList e )               { return  m_aiAlterRefIdx[e];                                   }
+#endif                                                                                                                                               
+#if H_3D_ARP                                                                                                                                         
+  Int                         getFirstTRefIdx        ( RefPicList e )                { return  m_aiFirstTRefIdx[e];                                  }
+  Void                        setFirstTRefIdx        ( RefPicList e, Int i )         { m_aiFirstTRefIdx[e]    = i;                                   }
+  Bool                        getArpRefPicAvailable  ( RefPicList e, Int viewIdx)    { return m_arpRefPicAvailable[e][getVPS()->getLayerIdInNuh(viewIdx, 0)]; }
+  IntAry1d                    getPocsInCurrRPSs()                                    { return m_pocsInCurrRPSs;                                      } 
+#endif                                                                                                                                               
+  Void                        setIsDepth            ( Bool isDepth )                 { m_isDepth = isDepth;                                          }
+  Bool                        getIsDepth            () const                         { return m_isDepth;                                             }
+  Void                        setCamparaSlice       ( Int** aaiScale = 0, Int** aaiOffset = 0 );      
+
+  IntAry1d                    getCodedScale         ()                               { return m_aaiCodedScale [0];                                   }
+  IntAry1d                    getCodedOffset        ()                               { return m_aaiCodedOffset[0];                                   }
+  IntAry1d                    getInvCodedScale      ()                               { return m_aaiCodedScale [1];                                   }
+  IntAry1d                    getInvCodedOffset     ()                               { return m_aaiCodedOffset[1];                                   }
+                                                                                                                                                     
+  Void                        setCpScale( Int j, Int  val )                          { m_aaiCodedScale[0][j] = val;                                  }
+  Int                         getCpScale( Int j )                                    { return m_aaiCodedScale[0][j];                                 }
+                                                                                                                                                     
+  Void                        setCpOff( Int j, Int  val )                            { m_aaiCodedOffset[0][j] = val;                                 }
+  Int                         getCpOff( Int j )                                      { return m_aaiCodedOffset[0][j];                                }
+                                                                                                                                                     
+  Void                        setCpInvScale( Int j, Int  val )                       { m_aaiCodedScale[1][j] = val;                                  }
+  Int                         getCpInvScale( Int j )                                 { return m_aaiCodedScale[1][j];                                 }
+                                                                                                                                                     
+  Void                        setCpInvOff( Int j, Int  val )                         { m_aaiCodedOffset[1][j] = val;                                 }
+  Int                         getCpInvOff( Int j )                                   { return m_aaiCodedOffset[1][j];                                }
+                                                                                                                                                        
+  Void                        setIvPicLists( TComPicLists* m_ivPicLists );                                                                              
+  Void                        setDepthToDisparityLUTs();                                                                                                
+                                                                                                                                                        
+  Int*                        getDepthToDisparityB( Int refViewIdx )                 { return m_depthToDisparityB[ getVPS()->getVoiInVps( refViewIdx) ];}
+  Int*                        getDepthToDisparityF( Int refViewIdx )                 { return m_depthToDisparityF[ getVPS()->getVoiInVps( refViewIdx) ];}
+#if H_3D_IC                                                                                                                                             
+  Void                        setICEnableCandidate( Int* icEnableCandidate)          { m_aICEnableCandidate = icEnableCandidate;                     }
+  Void                        setICEnableNum( Int* icEnableNum)                      { m_aICEnableNum = icEnableNum;                                 }
+  Void                        setICEnableCandidate( UInt layer, Int value)           { m_aICEnableCandidate[ layer ] = value;                        }
+  Void                        setICEnableNum( UInt layer, Int value)                 { m_aICEnableNum[ layer ] = value; ;                            }
+                                                                                                                                                     
+  Int                         getICEnableCandidate( Int layer)                       { return  m_aICEnableCandidate[ layer ];                        }
+  Int                         getICEnableNum( Int layer)                             { return m_aICEnableNum[ layer ];                               }
+#endif
+#endif
 // Additional slice header syntax elements
 
-  Void setCrossLayerBlaFlag( Bool flag ) { m_crossLayerBlaFlag = flag; } 
-  Bool getCrossLayerBlaFlag(  ) { return m_crossLayerBlaFlag; } 
-  Void checkCrossLayerBlaFlag ( );
+  Void                        setCrossLayerBlaFlag( Bool flag )                      { m_crossLayerBlaFlag = flag;                                   }
+  Bool                        getCrossLayerBlaFlag(  ) const                         { return m_crossLayerBlaFlag;                                   }
+  Void                        checkCrossLayerBlaFlag ( ) const ;
 
 #if !H_MV_HLS7_GEN
-  Void setPocResetFlag( Bool flag ) { m_pocResetFlag = flag; } 
-  Bool getPocResetFlag(  ) { return m_pocResetFlag; } 
-#endif
-
-  Void setDiscardableFlag( Bool flag ) { m_discardableFlag = flag; } 
-  Bool getDiscardableFlag(  ) { return m_discardableFlag; } 
-
-  Void setInterLayerPredEnabledFlag( Bool flag ) { m_interLayerPredEnabledFlag = flag; } 
-  Bool getInterLayerPredEnabledFlag(  ) { return m_interLayerPredEnabledFlag; } 
-
-  Void setNumInterLayerRefPicsMinus1( Int  val ) { m_numInterLayerRefPicsMinus1 = val; } 
-  Int  getNumInterLayerRefPicsMinus1(  ) { return m_numInterLayerRefPicsMinus1; } 
-
-  Void setInterLayerPredLayerIdc( Int i, Int  val ) { m_interLayerPredLayerIdc[i] = val; } 
-  Int  getInterLayerPredLayerIdc( Int i ) { return m_interLayerPredLayerIdc[i]; } 
-
-  Void setSliceSegmentHeaderExtensionLength( Int  val ) { m_sliceSegmentHeaderExtensionLength = val; } 
-  Int  getSliceSegmentHeaderExtensionLength(  ) { return m_sliceSegmentHeaderExtensionLength; } 
-
-  Void setPocResetIdc( Int  val ) { m_pocResetIdc = val; } 
-  Int  getPocResetIdc(  ) { return m_pocResetIdc; } 
-  Void checkPocResetIdc( ) { assert( !(getVPS()->getPocLsbNotPresentFlag( getLayerIdInVps() ) )  || !(getSlicePicOrderCntLsb() > 0 ) || !( getPocResetIdc() == 2) ); }  
-
-  Void setPocResetPeriodId( Int  val ) { m_pocResetPeriodId = val; } 
-  Int  getPocResetPeriodId(  ) { return m_pocResetPeriodId; } 
-
-  Void setFullPocResetFlag( Bool flag ) { m_fullPocResetFlag = flag; } 
-  Bool getFullPocResetFlag(  ) { return m_fullPocResetFlag; } 
-
-  Void setPocLsbVal( Int  val ) { m_pocLsbVal = val; } 
-  Int  getPocLsbVal(  ) { return m_pocLsbVal; } 
-  Void checkPocLsbVal( ) { assert( !(getVPS()->getPocLsbNotPresentFlag( getLayerIdInVps() ) )  || !getFullPocResetFlag() || ( getPocLsbVal() == 0 ) ); }  
-
-  Void setPocMsbValPresentFlag( Bool flag ) { m_pocMsbValPresentFlag = flag; } 
-  Bool getPocMsbValPresentFlag(  ) { return m_pocMsbValPresentFlag; } 
-
-  Void setPocMsbVal( Int  val ) { m_pocMsbVal = val; } 
-  Int  getPocMsbVal(  ) { return m_pocMsbVal; } 
-
-  Bool getCraOrBlaPicFlag() { return ( getCraPicFlag() || getBlaPicFlag() ); } 
-  Bool getPocMsbValRequiredFlag() { return ( getCraOrBlaPicFlag() && ( getVPS()->getVpsPocLsbAlignedFlag() || getVPS()->getNumDirectRefLayers( getLayerIdInVps() ) == 0 ) );  }
-
-
-  UInt getPocLsbValLen() { return getSPS()->getBitsForPOC(); }; //log2_max_pic_order_cnt_lsb_minus4 + 4  
-
-  Bool getBlaPicFlag       ()
+  Void                        setPocResetFlag( Bool flag )                           { m_pocResetFlag = flag;                                        }
+  Bool                        getPocResetFlag(  ) const                              { return m_pocResetFlag;                                        }
+#endif
+
+  Void                        setDiscardableFlag( Bool flag )                        { m_discardableFlag = flag;                                     }
+  Bool                        getDiscardableFlag(  ) const                           { return m_discardableFlag;                                     }
+
+  Void                        setInterLayerPredEnabledFlag( Bool flag )              { m_interLayerPredEnabledFlag = flag;                           }
+  Bool                        getInterLayerPredEnabledFlag(  ) const                 { return m_interLayerPredEnabledFlag;                           }
+
+  Void                        setNumInterLayerRefPicsMinus1( Int  val )              { m_numInterLayerRefPicsMinus1 = val;                           }
+  Int                         getNumInterLayerRefPicsMinus1(  ) const                { return m_numInterLayerRefPicsMinus1;                          }
+
+  Void                        setInterLayerPredLayerIdc( Int i, Int  val )           { m_interLayerPredLayerIdc[i] = val;                            }
+  Int                         getInterLayerPredLayerIdc( Int i ) const               { return m_interLayerPredLayerIdc[i];                           }
+
+  Void                        setSliceSegmentHeaderExtensionLength( Int  val )       { m_sliceSegmentHeaderExtensionLength = val;                    }
+  Int                         getSliceSegmentHeaderExtensionLength(  ) const         { return m_sliceSegmentHeaderExtensionLength;                   }
+
+  Void                        setPocResetIdc( Int  val )                             { m_pocResetIdc = val;                                          }
+  Int                         getPocResetIdc(  ) const                               { return m_pocResetIdc;                                         }
+  Void                        checkPocResetIdc( ) const                              { assert( !(getVPS()->getPocLsbNotPresentFlag( getLayerIdInVps() ) )  || !(getSlicePicOrderCntLsb() > 0 ) || !( getPocResetIdc() == 2) ); }
+
+  Void                        setPocResetPeriodId( Int  val )                        { m_pocResetPeriodId = val;                                     }
+  Int                         getPocResetPeriodId(  ) const                          { return m_pocResetPeriodId;                                    }
+
+  Void                        setFullPocResetFlag( Bool flag )                       { m_fullPocResetFlag = flag;                                    }
+  Bool                        getFullPocResetFlag(  ) const                          { return m_fullPocResetFlag;                                    }
+
+  Void                        setPocLsbVal( Int  val )                               { m_pocLsbVal = val;                                            }
+  Int                         getPocLsbVal(  )  const                                { return m_pocLsbVal;                                           }
+  Void                        checkPocLsbVal( ) const                                { assert( !(getVPS()->getPocLsbNotPresentFlag( getLayerIdInVps() ) )  || !getFullPocResetFlag() || ( getPocLsbVal() == 0 ) ); }
+
+  Void                        setPocMsbValPresentFlag( Bool flag )                   { m_pocMsbValPresentFlag = flag;                                }
+  Bool                        getPocMsbValPresentFlag(  )          const             { return m_pocMsbValPresentFlag;                                }
+
+  Void                        setPocMsbVal( Int  val )                               { m_pocMsbVal = val;                                            }
+  Int                         getPocMsbVal(  )         const                         { return m_pocMsbVal;                                           }
+
+  Bool                        getCraOrBlaPicFlag()       const                       { return ( getCraPicFlag() || getBlaPicFlag() );                }
+  Bool                        getPocMsbValRequiredFlag() const                       { return ( getCraOrBlaPicFlag() && ( getVPS()->getVpsPocLsbAlignedFlag() || getVPS()->getNumDirectRefLayers( getLayerIdInVps() ) == 0 ) );  }
+
+  UInt                        getPocLsbValLen() const                                { return getSPS()->getBitsForPOC();                             }; //log2_max_pic_order_cnt_lsb_minus4 + 4
+
+  Bool getBlaPicFlag() const
   {
     return  getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
@@ -2843,5 +3024,5 @@
     || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP;
   }
-  Bool getCraPicFlag       ()
+  Bool getCraPicFlag () const  
   {
     return getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
@@ -2849,77 +3030,81 @@
 
   // Additional variables derived in slice header semantics 
-
+#if NH_3D
+  Int                         getNumInterLayerRefPicsMinus1Len( ) const              { return gCeilLog2(  getVPS()->getNumRefListLayers( getLayerId() )); }
+  Int                         getInterLayerPredLayerIdcLen    ( ) const              { return gCeilLog2(  getVPS()->getNumRefListLayers( getLayerId() )); }
+#else
+  Int                         getNumInterLayerRefPicsMinus1Len( ) const              { return gCeilLog2(  getVPS()->getNumDirectRefLayers( getLayerId() )); }
+  Int                         getInterLayerPredLayerIdcLen    ( ) const              { return gCeilLog2(  getVPS()->getNumDirectRefLayers( getLayerId() )); }
+#endif
+
+  Int                         getRefLayerPicFlag( Int i ) const;
+  Int                         getRefLayerPicIdc ( Int j ) const;
+  Int                         getNumRefLayerPics( ) const;
+
+  Int                         getNumActiveRefLayerPics( ) const;
+
+  Int                         getNumActiveRefLayerPics0( ) const                     { return (Int) m_refPicSetInterLayer0->size();                  };
+  Int                         getNumActiveRefLayerPics1( ) const                     { return (Int) m_refPicSetInterLayer1->size();                  };
+
+  Int                         getRefPicLayerId             ( Int i ) const;
+
+  Void                        setRefPicSetInterLayer       ( std::vector<TComPic*>* refPicSetInterLayer0, std::vector<TComPic*>* refPicSetInterLayer1);
+  TComPic*                    getPicFromRefPicSetInterLayer ( Int setIdc, Int layerId ) const ;
+
+#if NH_3D
+  // 3D-HEVC tool parameters
+  Void                        deriveInCmpPredAndCpAvailFlag( );
+  Void                        init3dToolParameters();
+  Void                        checkInCompPredRefLayers();;
+
+  Bool                        getIvMvPredFlag           ( )                          { return m_ivMvPredFlag           ;                             };
+  Bool                        getIvMvScalingFlag        ( )                          { return m_ivMvScalingFlag        ;                             };
+  Bool                        getIvResPredFlag          ( )                          { return m_ivResPredFlag          ;                             };
+  Bool                        getDepthRefinementFlag    ( )                          { return m_depthRefinementFlag    ;                             };
+  Bool                        getViewSynthesisPredFlag  ( )                          { return m_viewSynthesisPredFlag  ;                             };
+  Bool                        getDepthBasedBlkPartFlag  ( )                          { return m_depthBasedBlkPartFlag  ;                             };
+  Bool                        getMpiFlag                ( )                          { return m_mpiFlag                ;                             };
+  Bool                        getIntraContourFlag       ( )                          { return m_intraContourFlag       ;                             };
+  Bool                        getIntraSdcWedgeFlag      ( )                          { return m_intraSdcWedgeFlag      ;                             };
+  Bool                        getQtPredFlag             ( )                          { return m_qtPredFlag             ;                             };
+  Bool                        getInterSdcFlag           ( )                          { return m_interSdcFlag           ;                             };
+  Bool                        getDepthIntraSkipFlag     ( )                          { return m_depthIntraSkipFlag     ;                             };
+
+  Int                         getMpiSubPbSize           ( )                          { return m_mpiSubPbSize           ;                             };
+  Int                         getSubPbSize              ( )                          { return m_subPbSize              ;                             };
+#endif
+  // Inference 
+  Bool                        inferPocMsbValPresentFlag();
+#endif
 #if H_3D
-  Int  getNumInterLayerRefPicsMinus1Len( ) { return gCeilLog2(  getVPS()->getNumRefListLayers( getLayerId() )); }
-  Int  getInterLayerPredLayerIdcLen    ( ) { return gCeilLog2(  getVPS()->getNumRefListLayers( getLayerId() )); }
-#else
-  Int  getNumInterLayerRefPicsMinus1Len( ) { return gCeilLog2(  getVPS()->getNumDirectRefLayers( getLayerId() )); }
-  Int  getInterLayerPredLayerIdcLen    ( ) { return gCeilLog2(  getVPS()->getNumDirectRefLayers( getLayerId() )); }
-#endif
-
-
-  Int  getRefLayerPicFlag( Int i ); 
-  Int  getRefLayerPicIdc ( Int j ); 
-  Int  getNumRefLayerPics( ); 
-
-  Int  getNumActiveRefLayerPics( );
-
-  Int  getNumActiveRefLayerPics0( )        { return (Int) m_refPicSetInterLayer0->size();  };
-  Int  getNumActiveRefLayerPics1( )        { return (Int) m_refPicSetInterLayer1->size();  };
-
-  Int  getRefPicLayerId               ( Int i );
-
-  Void     setRefPicSetInterLayer       ( std::vector<TComPic*>* refPicSetInterLayer0, std::vector<TComPic*>* refPicSetInterLayer1);
-  TComPic* getPicFromRefPicSetInterLayer( Int setIdc, Int layerId );
-
-
-#if H_3D
-  // 3D-HEVC tool parameters
-  Void deriveInCmpPredAndCpAvailFlag();
-  Void init3dToolParameters();   
-  Void checkInCompPredRefLayers();;
-
-  Bool getIvMvPredFlag           ( ) { return m_ivMvPredFlag           ; };
-  Bool getIvMvScalingFlag        ( ) { return m_ivMvScalingFlag        ; };
-  Bool getIvResPredFlag          ( ) { return m_ivResPredFlag          ; };
-  Bool getDepthRefinementFlag    ( ) { return m_depthRefinementFlag    ; };
-  Bool getViewSynthesisPredFlag  ( ) { return m_viewSynthesisPredFlag  ; };
-  Bool getDepthBasedBlkPartFlag  ( ) { return m_depthBasedBlkPartFlag  ; };
-  Bool getMpiFlag                ( ) { return m_mpiFlag                ; };
-  Bool getIntraContourFlag       ( ) { return m_intraContourFlag       ; };
-  Bool getIntraSdcWedgeFlag      ( ) { return m_intraSdcWedgeFlag      ; };
-  Bool getQtPredFlag             ( ) { return m_qtPredFlag             ; };
-  Bool getInterSdcFlag           ( ) { return m_interSdcFlag           ; };
-  Bool getDepthIntraSkipFlag     ( ) { return m_depthIntraSkipFlag     ; };
-
-  Int  getMpiSubPbSize           ( ) { return m_mpiSubPbSize           ; }; 
-  Int  getSubPbSize              ( ) { return m_subPbSize              ; }; 
-#endif
-
-
-  // Inference 
-  Bool inferPocMsbValPresentFlag();  
-#endif
-#if H_3D
-  Int  getDefaultRefViewIdx() { return m_iDefaultRefViewIdx; }
-  Void setDefaultRefViewIdx(Int iViewIdx) { m_iDefaultRefViewIdx = iViewIdx; }
-
-  Bool getDefaultRefViewIdxAvailableFlag() { return m_bDefaultRefViewIdxAvailableFlag; }
-  Void setDefaultRefViewIdxAvailableFlag(Bool bViewIdx) { m_bDefaultRefViewIdxAvailableFlag = bViewIdx; }
-  Void setDefaultRefView( );
+  Int                         getDefaultRefViewIdx()                                 { return m_iDefaultRefViewIdx;                                  }
+  Void                        setDefaultRefViewIdx(Int iViewIdx)                     { m_iDefaultRefViewIdx = iViewIdx;                              }
+
+  Bool                        getDefaultRefViewIdxAvailableFlag()                    { return m_bDefaultRefViewIdxAvailableFlag;                     }
+  Void                        setDefaultRefViewIdxAvailableFlag(Bool bViewIdx)       { m_bDefaultRefViewIdxAvailableFlag = bViewIdx;                 }
+  Void                        setDefaultRefView( );
 #endif
 protected:
-  TComPic*  xGetRefPic  (TComList<TComPic*>& rcListPic,
-                         Int                 poc);
-TComPic*  xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb);
-#if H_MV
-  TComPic*  xGetInterLayerRefPic( std::vector<TComPic*>& rcListIlPic, Int layerId );  
+  TComPic*                    xGetRefPic        (TComList<TComPic*>& rcListPic, Int poc);
+  TComPic*                    xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb);
+#if NH_MV
+  TComPic*                    xGetInterLayerRefPic( std::vector<TComPic*>& rcListIlPic, Int layerId );  
 #endif
 };// END CLASS DEFINITION TComSlice
 
+
+Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> &newData);
 
 template <class T> class ParameterSetMap
 {
 public:
+  template <class Tm>
+  struct MapData
+  {
+    Bool                  bChanged;
+    std::vector<UChar>   *pNaluData; // Can be null
+    Tm*                   parameterSet;
+  };
+
   ParameterSetMap(Int maxId)
   :m_maxId (maxId)
@@ -2928,43 +3113,72 @@
   ~ParameterSetMap()
   {
-    for (typename std::map<Int,T *>::iterator i = m_paramsetMap.begin(); i!= m_paramsetMap.end(); i++)
+    for (typename std::map<Int,MapData<T> >::iterator i = m_paramsetMap.begin(); i!= m_paramsetMap.end(); i++)
     {
-      delete (*i).second;
+      delete (*i).second.pNaluData;
+      delete (*i).second.parameterSet;
     }
   }
 
-  Void storePS(Int psId, T *ps)
+  Void storePS(Int psId, T *ps, const std::vector<UChar> &naluData)
   {
     assert ( psId < m_maxId );
     if ( m_paramsetMap.find(psId) != m_paramsetMap.end() )
     {
-      delete m_paramsetMap[psId];
+      MapData<T> &mapData=m_paramsetMap[psId];
+
+      // work out changed flag
+      calculateParameterSetChangedFlag(mapData.bChanged, mapData.pNaluData, naluData);
+      delete m_paramsetMap[psId].pNaluData;
+      delete m_paramsetMap[psId].parameterSet;
+
+      m_paramsetMap[psId].parameterSet = ps;
     }
-    m_paramsetMap[psId] = ps; 
+    else
+    {
+      m_paramsetMap[psId].parameterSet = ps;
+      m_paramsetMap[psId].bChanged = false;
+    }
+      m_paramsetMap[psId].pNaluData=new std::vector<UChar>;
+    *(m_paramsetMap[psId].pNaluData) = naluData;
   }
 
-  Void mergePSList(ParameterSetMap<T> &rPsList)
+  Void clearChangedFlag(Int psId)
   {
-    for (typename std::map<Int,T *>::iterator i = rPsList.m_paramsetMap.begin(); i!= rPsList.m_paramsetMap.end(); i++)
+    if ( m_paramsetMap.find(psId) != m_paramsetMap.end() )
     {
-      storePS(i->first, i->second);
+      m_paramsetMap[psId].bChanged=false;
     }
-    rPsList.m_paramsetMap.clear();
   }
 
+  Bool getChangedFlag(Int psId) const
+  {
+    const typename std::map<Int,MapData<T> >::const_iterator constit=m_paramsetMap.find(psId);
+    if ( constit != m_paramsetMap.end() )
+    {
+      return constit->second.bChanged;
+    }
+    return false;
+  }
 
   T* getPS(Int psId)
   {
-    return ( m_paramsetMap.find(psId) == m_paramsetMap.end() ) ? NULL : m_paramsetMap[psId];
+    typename std::map<Int,MapData<T> >::iterator it=m_paramsetMap.find(psId);
+    return ( it == m_paramsetMap.end() ) ? NULL : (it)->second.parameterSet;
+  }
+
+  const T* getPS(Int psId) const
+  {
+    typename std::map<Int,MapData<T> >::const_iterator it=m_paramsetMap.find(psId);
+    return ( it == m_paramsetMap.end() ) ? NULL : (it)->second.parameterSet;
   }
 
   T* getFirstPS()
   {
-    return (m_paramsetMap.begin() == m_paramsetMap.end() ) ? NULL : m_paramsetMap.begin()->second;
+    return (m_paramsetMap.begin() == m_paramsetMap.end() ) ? NULL : m_paramsetMap.begin()->second.parameterSet;
   }
 
 private:
-  std::map<Int,T *> m_paramsetMap;
-  Int               m_maxId;
+  std::map<Int,MapData<T> > m_paramsetMap;
+  Int                       m_maxId;
 };
 
@@ -2972,64 +3186,66 @@
 {
 public:
-  ParameterSetManager();
-  virtual ~ParameterSetManager();
-
-  //! store sequence parameter set and take ownership of it 
-  Void storeVPS(TComVPS *vps) { m_vpsMap.storePS( vps->getVPSId(), vps); };
-  //! get pointer to existing video parameter set  
-  TComVPS* getVPS(Int vpsId)  { return m_vpsMap.getPS(vpsId); };
-  TComVPS* getFirstVPS()      { return m_vpsMap.getFirstPS(); };
-  
-  //! store sequence parameter set and take ownership of it 
-  Void storeSPS(TComSPS *sps) { m_spsMap.storePS( sps->getSPSId(), sps); };
-  //! get pointer to existing sequence parameter set  
-  TComSPS* getSPS(Int spsId)  { return m_spsMap.getPS(spsId); };
-  TComSPS* getFirstSPS()      { return m_spsMap.getFirstPS(); };
-
-  //! store picture parameter set and take ownership of it 
-  Void storePPS(TComPPS *pps) { m_ppsMap.storePS( pps->getPPSId(), pps); };
-  //! get pointer to existing picture parameter set  
-  TComPPS* getPPS(Int ppsId)  { return m_ppsMap.getPS(ppsId); };
-  TComPPS* getFirstPPS()      { return m_ppsMap.getFirstPS(); };
+                 ParameterSetManager();
+  virtual        ~ParameterSetManager();
+
+  //! store sequence parameter set and take ownership of it
+  Void           storeVPS(TComVPS *vps, const std::vector<UChar> &naluData) { m_vpsMap.storePS( vps->getVPSId(), vps, naluData); };
+  //! get pointer to existing video parameter set
+  TComVPS*       getVPS(Int vpsId)                                           { return m_vpsMap.getPS(vpsId); };
+  Bool           getVPSChangedFlag(Int vpsId) const                          { return m_vpsMap.getChangedFlag(vpsId); }
+  Void           clearVPSChangedFlag(Int vpsId)                              { m_vpsMap.clearChangedFlag(vpsId); }
+  TComVPS*       getFirstVPS()                                               { return m_vpsMap.getFirstPS(); };
+
+  //! store sequence parameter set and take ownership of it
+  Void           storeSPS(TComSPS *sps, const std::vector<UChar> &naluData) { m_spsMap.storePS( sps->getSPSId(), sps, naluData); };
+  //! get pointer to existing sequence parameter set
+  TComSPS*       getSPS(Int spsId)                                           { return m_spsMap.getPS(spsId); };
+  Bool           getSPSChangedFlag(Int spsId) const                          { return m_spsMap.getChangedFlag(spsId); }
+  Void           clearSPSChangedFlag(Int spsId)                              { m_spsMap.clearChangedFlag(spsId); }
+  TComSPS*       getFirstSPS()                                               { return m_spsMap.getFirstPS(); };
+
+  //! store picture parameter set and take ownership of it
+  Void           storePPS(TComPPS *pps, const std::vector<UChar> &naluData) { m_ppsMap.storePS( pps->getPPSId(), pps, naluData); };
+  //! get pointer to existing picture parameter set
+  TComPPS*       getPPS(Int ppsId)                                           { return m_ppsMap.getPS(ppsId); };
+  Bool           getPPSChangedFlag(Int ppsId) const                          { return m_ppsMap.getChangedFlag(ppsId); }
+  Void           clearPPSChangedFlag(Int ppsId)                              { m_ppsMap.clearChangedFlag(ppsId); }
+  TComPPS*       getFirstPPS()                                               { return m_ppsMap.getFirstPS(); };
 
   //! activate a SPS from a active parameter sets SEI message
   //! \returns true, if activation is successful
-#if H_MV
-  Bool activateSPSWithSEI(Int SPSId, Int layerId );
+#if NH_MV
+  // Bool           activateSPSWithSEI(Int SPSId, Int layerId );
 #else
-  Bool activateSPSWithSEI(Int SPSId);
+  // Bool           activateSPSWithSEI(Int SPSId);
 #endif
 
   //! activate a PPS and depending on isIDR parameter also SPS and VPS
   //! \returns true, if activation is successful
-#if H_MV
-  Bool activatePPS(Int ppsId, Bool isIRAP, Int layerId );
+#if NH_MV
+  Bool           activatePPS(Int ppsId, Bool isIRAP, Int layerId );
 #else
-  Bool activatePPS(Int ppsId, Bool isIRAP);
-#endif
-
-  TComVPS* getActiveVPS(){ return m_vpsMap.getPS(m_activeVPSId); };
-#if H_MV
-  TComSPS* getActiveSPS( Int layerId ){ return m_spsMap.getPS( m_activeSPSId[ layerId ] ); };
-  TComPPS* getActivePPS( Int layerId ){ return m_ppsMap.getPS( m_activePPSId[ layerId ] ); };
-#else
-  TComSPS* getActiveSPS(){ return m_spsMap.getPS(m_activeSPSId); };
-  TComPPS* getActivePPS(){ return m_ppsMap.getPS(m_activePPSId); };
-#endif
+  Bool           activatePPS(Int ppsId, Bool isIRAP);
+#endif
+
+  const TComVPS* getActiveVPS()const { return m_vpsMap.getPS(m_activeVPSId); };
+
+#if NH_MV  
+  const TComSPS* getActiveSPS( Int layer )const { return m_spsMap.getPS(m_activeSPSId[layer]); };
+#else  
+  const TComSPS* getActiveSPS()const { return m_spsMap.getPS(m_activeSPSId); };
+#endif
+
 protected:
-  
   ParameterSetMap<TComVPS> m_vpsMap;
-  ParameterSetMap<TComSPS> m_spsMap; 
+  ParameterSetMap<TComSPS> m_spsMap;
   ParameterSetMap<TComPPS> m_ppsMap;
 
-  Int m_activeVPSId;
-#if H_MV
-  Int m_activeSPSId[ MAX_NUM_LAYERS ];
-  Int m_activePPSId[ MAX_NUM_LAYERS ];
-#else
-  Int m_activeSPSId;
-  Int m_activePPSId;
-#endif
-
+  Int m_activeVPSId; // -1 for nothing active
+#if NH_MV  
+  Int m_activeSPSId[ MAX_NUM_LAYERS ]; // -1 for nothing active
+#else  
+  Int m_activeSPSId; // -1 for nothing active
+#endif
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTU.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTU.cpp	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTU.cpp	(revision 1200)
@@ -0,0 +1,263 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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.
+ */
+
+
+#include "TComTU.h"
+#include "TComRom.h"
+#include "TComDataCU.h"
+#include "TComPic.h"
+
+//----------------------------------------------------------------------------------------------------------------------
+
+/*static*/ const UInt TComTU::NUMBER_OF_SECTIONS[TComTU::NUMBER_OF_SPLIT_MODES] = { 1, 2, 4 };
+
+static     const UInt         partIdxStepShift  [TComTU::NUMBER_OF_SPLIT_MODES] = { 0, 1, 2 };
+
+//----------------------------------------------------------------------------------------------------------------------
+
+TComTU::TComTU(TComDataCU *pcCU, const UInt absPartIdxCU, const UInt cuDepth, const UInt initTrDepthRelCU)
+  : mChromaFormat(pcCU->getSlice()->getSPS()->getChromaFormatIdc()),
+    mbProcessLastOfLevel(true), // does not matter. the top level is not 4 quadrants.
+    mCuDepth(cuDepth),
+    mSection(0),
+    mSplitMode(DONT_SPLIT),
+    mAbsPartIdxCU(absPartIdxCU),
+    mAbsPartIdxTURelCU(0),
+    mAbsPartIdxStep(pcCU->getPic()->getNumPartitionsInCtu() >> (pcCU->getDepth(absPartIdxCU)<<1)),
+    mpcCU(pcCU),
+    mLog2TrLumaSize(0),
+    mpParent(NULL)
+{
+  const TComSPS *pSPS=pcCU->getSlice()->getSPS();
+  mLog2TrLumaSize = g_aucConvertToBit[pSPS->getMaxCUWidth() >> (mCuDepth+initTrDepthRelCU)]+2;
+
+  const UInt baseOffset444=pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight()*absPartIdxCU;
+
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    mTrDepthRelCU[i] = initTrDepthRelCU;
+    const UInt csx=getComponentScaleX(ComponentID(i), mChromaFormat);
+    const UInt csy=getComponentScaleY(ComponentID(i), mChromaFormat);
+    mOrigWidth[i]=mRect[i].width = (i < getNumberValidComponents(mChromaFormat)) ? (pcCU->getWidth( absPartIdxCU) >> csx) : 0;
+    mRect[i].height              = (i < getNumberValidComponents(mChromaFormat)) ? (pcCU->getHeight(absPartIdxCU) >> csy) : 0;
+    mRect[i].x0=0;
+    mRect[i].y0=0;
+    mCodeAll[i]=true;
+    mOffsets[i]=baseOffset444>>(csx+csy);
+  }
+}
+
+
+
+TComTURecurse::TComTURecurse(      TComDataCU *pcCU,
+                             const UInt        absPartIdxCU)
+  : TComTU(pcCU, absPartIdxCU, pcCU->getDepth(absPartIdxCU), 0)
+{ }
+
+
+
+TComTU::TComTU(TComTU &parent, const Bool bProcessLastOfLevel, const TU_SPLIT_MODE splitMode, const Bool splitAtCurrentDepth, const ComponentID absPartIdxSourceComponent)
+  : mChromaFormat(parent.mChromaFormat),
+    mbProcessLastOfLevel(bProcessLastOfLevel),
+    mCuDepth(parent.mCuDepth),
+    mSection(0),
+    mSplitMode(splitMode),
+    mAbsPartIdxCU(parent.mAbsPartIdxCU),
+    mAbsPartIdxTURelCU(parent.GetRelPartIdxTU(absPartIdxSourceComponent)),
+    mAbsPartIdxStep(std::max<UInt>(1, (parent.GetAbsPartIdxNumParts(absPartIdxSourceComponent) >> partIdxStepShift[splitMode]))),
+    mpcCU(parent.mpcCU),
+    mLog2TrLumaSize(parent.mLog2TrLumaSize - ((splitMode != QUAD_SPLIT) ? 0 : 1)), //no change in width for vertical split
+    mpParent(&parent)
+{
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    mTrDepthRelCU[i] = parent.mTrDepthRelCU[i] + ((splitAtCurrentDepth || (splitMode == DONT_SPLIT)) ? 0 : 1);
+  }
+
+  if (mSplitMode==DONT_SPLIT)
+  {
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      mRect[i] = (parent.mRect[i]);
+      mOffsets[i]=parent.mOffsets[i];
+      mCodeAll[i]=true; // The 1 TU at this level is coded.
+      mOrigWidth[i]=mRect[i].width;
+    }
+    return;
+  }
+  else if (mSplitMode==VERTICAL_SPLIT)
+  {
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      mRect[i].x0 = (parent.mRect[i].x0);
+      mRect[i].y0 = (parent.mRect[i].y0);
+      mRect[i].width  = (parent.mRect[i].width);
+      mRect[i].height = (parent.mRect[i].height)>>1;
+      mOffsets[i]=parent.mOffsets[i];
+      mCodeAll[i]=true; // The 2 TUs at this level is coded.
+      mOrigWidth[i]=mRect[i].width;
+    }
+    return;
+  }
+
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    mRect[i].width = (parent.mRect[i].width >> 1);
+    mRect[i].height= (parent.mRect[i].height>> 1);
+    mRect[i].x0=parent.mRect[i].x0;
+    mRect[i].y0=parent.mRect[i].y0;
+    mOffsets[i]=parent.mOffsets[i];
+
+    if ((mRect[i].width < MIN_TU_SIZE || mRect[i].height < MIN_TU_SIZE) && mRect[i].width!=0)
+    {
+      const UInt numPels=mRect[i].width * mRect[i].height;
+      if (numPels < (MIN_TU_SIZE*MIN_TU_SIZE))
+      {
+        // this level doesn't have enough pixels to have 4 blocks of any relative dimension
+        mRect[i].width = parent.mRect[i].width;
+        mRect[i].height= parent.mRect[i].height;
+        mCodeAll[i]=false; // go up a level, so only process one entry of a quadrant
+        mTrDepthRelCU[i]--;
+      }
+      else if (mRect[i].width < mRect[i].height)
+      {
+        mRect[i].width=MIN_TU_SIZE;
+        mRect[i].height=numPels/MIN_TU_SIZE;
+        mCodeAll[i]=true;
+      }
+      else
+      {
+        mRect[i].height=MIN_TU_SIZE;
+        mRect[i].width=numPels/MIN_TU_SIZE;
+        mCodeAll[i]=true;
+      }
+    }
+    else
+    {
+      mCodeAll[i]=true;
+    }
+
+    mOrigWidth[i]=mRect[i].width;
+    if (!mCodeAll[i] && mbProcessLastOfLevel)
+    {
+      mRect[i].width=0;
+    }
+  }
+}
+
+Bool TComTURecurse::nextSection(const TComTU &parent)
+{
+  if (mSplitMode==DONT_SPLIT)
+  {
+    mSection++;
+    return false;
+  }
+  else
+  {
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      mOffsets[i]+=mRect[i].width*mRect[i].height;
+      if (mbProcessLastOfLevel)
+      {
+        mRect[i].width=mOrigWidth[i];
+      }
+      mRect[i].x0+=mRect[i].width;
+      const TComRectangle &parentRect=parent.getRect(ComponentID(i));
+      if (mRect[i].x0 >= parentRect.x0+parentRect.width)
+      {
+        mRect[i].x0=parentRect.x0;
+        mRect[i].y0+=mRect[i].height;
+      }
+      if (!mCodeAll[i])
+      {
+        if (!mbProcessLastOfLevel || mSection!=2)
+        {
+          mRect[i].width=0;
+        }
+      }
+    }
+    assert(mRect[COMPONENT_Cb].x0==mRect[COMPONENT_Cr].x0);
+    assert(mRect[COMPONENT_Cb].y0==mRect[COMPONENT_Cr].y0);
+    assert(mRect[COMPONENT_Cb].width==mRect[COMPONENT_Cr].width);
+    assert(mRect[COMPONENT_Cb].height==mRect[COMPONENT_Cr].height);
+
+    mAbsPartIdxTURelCU+=mAbsPartIdxStep;
+    mSection++;
+    return mSection< (1<<mSplitMode);
+  }
+}
+
+
+UInt TComTU::GetEquivalentLog2TrSize(const ComponentID compID)     const
+{
+  return g_aucConvertToBit[ getRect(compID).height ] + 2;
+}
+
+
+Bool TComTU::useDST(const ComponentID compID)
+{
+        TComDataCU *const pcCU       = getCU();
+  const UInt              absPartIdx = GetAbsPartIdxTU(compID);
+
+  return isLuma(compID) && pcCU->isIntra(absPartIdx);
+}
+
+
+Bool TComTU::isNonTransformedResidualRotated(const ComponentID compID)
+{
+  // rotation only for 4x4 intra, and is only used for non-transformed blocks (the latter is not checked here)
+  return    getCU()->getSlice()->getSPS()->getSpsRangeExtension().getTransformSkipRotationEnabledFlag()
+         && mRect[compID].width == 4
+         && getCU()->isIntra(GetAbsPartIdxTU());
+}
+
+
+UInt TComTU::getGolombRiceStatisticsIndex(const ComponentID compID)
+{
+        TComDataCU *const pcCU             = getCU();
+  const UInt              absPartIdx       = GetAbsPartIdxTU(compID);
+  const Bool              transformSkip    = pcCU->getTransformSkip(absPartIdx, compID);
+  const Bool              transquantBypass = pcCU->getCUTransquantBypass(absPartIdx);
+
+  //--------
+
+  const UInt channelTypeOffset    =  isChroma(compID)                   ? 2 : 0;
+  const UInt nonTransformedOffset = (transformSkip || transquantBypass) ? 1 : 0;
+
+  //--------
+
+  const UInt selectedIndex = channelTypeOffset + nonTransformedOffset;
+  assert(selectedIndex < RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS);
+
+  return selectedIndex;
+}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTU.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTU.h	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTU.h	(revision 1200)
@@ -0,0 +1,167 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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 __TCOMTU__
+#define __TCOMTU__
+
+class TComTU; // forward declaration
+
+#include "CommonDef.h"
+#include "TComRectangle.h"
+#include "TComChromaFormat.h"
+
+class TComDataCU; // forward declaration
+
+//----------------------------------------------------------------------------------------------------------------------
+
+
+class TComTU
+{
+  public:
+    typedef enum TU_SPLIT_MODE { DONT_SPLIT=0, VERTICAL_SPLIT=1, QUAD_SPLIT=2, NUMBER_OF_SPLIT_MODES=3 } SPLIT_MODE;
+
+    static const UInt NUMBER_OF_SECTIONS[NUMBER_OF_SPLIT_MODES];
+
+  protected:
+    ChromaFormat  mChromaFormat;
+    Bool          mbProcessLastOfLevel; // if true, then if size n/2 x n/2 is invalid, the nxn block for a channel is processed only for the last block, not the first.
+    UInt          mCuDepth;
+    UInt          mTrDepthRelCU[MAX_NUM_COMPONENT];
+    UInt          mSection;
+    TU_SPLIT_MODE mSplitMode;
+    TComRectangle mRect[MAX_NUM_COMPONENT];
+    Bool          mCodeAll[MAX_NUM_COMPONENT];
+    UInt          mOrigWidth[MAX_NUM_COMPONENT];
+    UInt          mOffsets[MAX_NUM_COMPONENT];
+    UInt          mAbsPartIdxCU;
+    UInt          mAbsPartIdxTURelCU;
+    UInt          mAbsPartIdxStep;
+    TComDataCU   *mpcCU;
+    UInt          mLog2TrLumaSize;
+    TComTU       *mpParent;
+
+    TComTU(const TComTU &);           // not defined - do not use
+    TComTU&operator=(const TComTU &); // not defined - do not use
+
+  public:
+    TComTU(      TComDataCU *pcCU,
+           const UInt        absPartIdxCU,
+           const UInt        cuDepth,
+           const UInt        initTrDepthRelCU);
+
+  protected:
+    TComTU(      TComTU        &parentLevel,
+           const Bool           bProcessLastOfLevel,
+           const TU_SPLIT_MODE  splitMode                 = QUAD_SPLIT,
+           const Bool           splitAtCurrentDepth       = false,
+           const ComponentID    absPartIdxSourceComponent = COMPONENT_Y
+           );
+
+  public:
+          TComTU *Parent()       { return mpParent; }
+    const TComTU *Parent() const { return mpParent; }
+
+    UInt getCoefficientOffset(const ComponentID compID)        const { return mOffsets[compID]; }
+
+    const TComRectangle &getRect(const ComponentID compID)     const { return mRect[compID];    }
+
+    Bool ProcessingAllQuadrants(const ComponentID compID)      const { return mCodeAll[compID]; }
+    Bool ProcessComponentSection(const ComponentID compID)     const { return mRect[compID].width != 0; }
+    Bool ProcessChannelSection(const ChannelType chType)       const { return mRect[chType].width != 0; }
+    UInt GetSectionNumber()                                    const { return mSection; }
+
+    UInt getCUDepth()                                          const { return mCuDepth; }
+
+    UInt GetTransformDepthTotal()                              const { return mCuDepth+GetTransformDepthRel(); }
+    UInt GetTransformDepthTotalAdj(const ComponentID compID)   const { return mCuDepth+GetTransformDepthRelAdj(compID); }
+
+    UInt GetTransformDepthRel()                                const { return mTrDepthRelCU[COMPONENT_Y]; }
+    UInt GetTransformDepthRelAdj(const ComponentID compID)     const { return mTrDepthRelCU[compID]; }
+    UInt GetTransformDepthRelAdj(const ChannelType chType)     const
+    {
+      assert(isLuma(chType) || (mTrDepthRelCU[COMPONENT_Cb] == mTrDepthRelCU[COMPONENT_Cr]));
+      return mTrDepthRelCU[isLuma(chType) ? COMPONENT_Y : COMPONENT_Cb];
+    }
+
+    UInt GetAbsPartIdxCU()                                     const { return mAbsPartIdxCU; }
+    UInt GetRelPartIdxTU()                                     const { return mAbsPartIdxTURelCU; }
+    UInt GetRelPartIdxTU(const ComponentID compID)             const { return ProcessingAllQuadrants(compID) ? mAbsPartIdxTURelCU : (mAbsPartIdxTURelCU & (~0x3)); }
+    UInt GetAbsPartIdxTU()                                     const { return GetAbsPartIdxCU() + GetRelPartIdxTU(); }
+    UInt GetAbsPartIdxTU(const ComponentID compID)             const { return GetAbsPartIdxCU() + GetRelPartIdxTU(compID); }
+    UInt GetAbsPartIdxNumParts()                               const { return mAbsPartIdxStep; }
+    UInt GetAbsPartIdxNumParts(const ComponentID compID)       const { return ProcessingAllQuadrants(compID) ? mAbsPartIdxStep : (mAbsPartIdxStep * NUMBER_OF_SECTIONS[mSplitMode]); }
+
+    ChromaFormat GetChromaFormat()                             const { return mChromaFormat; }
+
+    TComDataCU *getCU()                                              { return mpcCU; }
+    const TComDataCU *getCU()                                  const { return mpcCU; }
+    Bool IsLastSection() const { return mSection+1>=((1<<mSplitMode)); }
+
+    UInt GetLog2LumaTrSize()                                   const { return mLog2TrLumaSize; }
+    UInt GetEquivalentLog2TrSize(const ComponentID compID)     const;
+    TU_SPLIT_MODE GetSplitMode()                               const { return mSplitMode; }
+
+    Bool useDST(const ComponentID compID);
+    Bool isNonTransformedResidualRotated(const ComponentID compID);
+
+    UInt getGolombRiceStatisticsIndex(const ComponentID compID);
+};
+
+
+
+class TComTURecurse : public TComTU
+{
+  public:
+
+    TComTURecurse(      TComDataCU *pcCU,
+                  const UInt        absPartIdxCU,
+                  const UInt        forcedDepthOfCU)
+      : TComTU(pcCU, absPartIdxCU, forcedDepthOfCU, 0) { }
+
+    TComTURecurse(      TComDataCU *pcCU,
+                  const UInt        absPartIdxCU); // CU's depth is taken from CU->getDepth(idx)
+
+    TComTURecurse(      TComTU        &parentLevel,                            //Parent TU from which recursion children are derived
+                  const Bool           bProcessLastOfLevel,                    //If true (and the split results in a "step-up" for chroma), the chroma TU is colocated with the last luma TU instead of the first
+                  const TU_SPLIT_MODE  splitMode                 = QUAD_SPLIT, //DONT_SPLIT = create one new TU as a copy of its parent, VERTICAL_SPLIT = split the TU into top and bottom halves, QUAD_SPLIT = split the TU into four equal quadrants
+                  const Bool           splitAtCurrentDepth       = false,      //Set true to keep the current depth when applying a vertical or quad split
+                  const ComponentID    absPartIdxSourceComponent = COMPONENT_Y //Specifies which component of the parent TU should be used to initialise the absPartIdx of the first child and the absPartIdx step (this is needed when splitting a "stepped-up" chroma TU)
+                  )
+                  : TComTU(parentLevel, bProcessLastOfLevel, splitMode, splitAtCurrentDepth, absPartIdxSourceComponent) { }
+
+    Bool nextSection(const TComTU &parent); // returns true if there is another section to process, and prepares internal structures, else returns false
+};
+
+//----------------------------------------------------------------------------------------------------------------------
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,8 +38,11 @@
 #include <stdlib.h>
 #include <math.h>
+#include <limits>
 #include <memory.h>
 #include "TComTrQuant.h"
 #include "TComPic.h"
 #include "ContextTables.h"
+#include "TComTU.h"
+#include "Debug.h"
 
 typedef struct
@@ -61,17 +64,59 @@
 #define RDOQ_CHROMA                 1           ///< use of RDOQ in chroma
 
+
 // ====================================================================================================================
-// Tables
+// QpParam constructor
 // ====================================================================================================================
 
-// RDOQ parameter
-
-// ====================================================================================================================
-// Qp class member functions
-// ====================================================================================================================
-
-QpParam::QpParam()
-{
-}
+QpParam::QpParam(const Int           qpy,
+                 const ChannelType   chType,
+                 const Int           qpBdOffset,
+                 const Int           chromaQPOffset,
+                 const ChromaFormat  chFmt )
+{
+  Int baseQp;
+
+  if(isLuma(chType))
+  {
+    baseQp = qpy + qpBdOffset;
+  }
+  else
+  {
+    baseQp = Clip3( -qpBdOffset, (chromaQPMappingTableSize - 1), qpy + chromaQPOffset );
+
+    if(baseQp < 0)
+    {
+      baseQp = baseQp + qpBdOffset;
+    }
+    else
+    {
+      baseQp = getScaledChromaQP(baseQp, chFmt) + qpBdOffset;
+    }
+  }
+
+  Qp =baseQp;
+  per=baseQp/6;
+  rem=baseQp%6;
+}
+
+QpParam::QpParam(const TComDataCU &cu, const ComponentID compID)
+{
+  Int chromaQpOffset = 0;
+
+  if (isChroma(compID))
+  {
+    chromaQpOffset += cu.getSlice()->getPPS()->getQpOffset(compID);
+    chromaQpOffset += cu.getSlice()->getSliceChromaQpDelta(compID);
+
+    chromaQpOffset += cu.getSlice()->getPPS()->getPpsRangeExtension().getChromaQpOffsetListEntry(cu.getChromaQpAdj(0)).u.offset[Int(compID)-1];
+  }
+
+  *this = QpParam(cu.getQP( 0 ),
+                  toChannelType(compID),
+                  cu.getSlice()->getSPS()->getQpBDOffset(toChannelType(compID)),
+                  chromaQpOffset,
+                  cu.getPic()->getChromaFormat());
+}
+
 
 // ====================================================================================================================
@@ -81,9 +126,7 @@
 TComTrQuant::TComTrQuant()
 {
-  m_cQP.clear();
-  
   // allocate temporary buffers
-  m_plTempCoeff  = new Int[ MAX_CU_SIZE*MAX_CU_SIZE ];
-  
+  m_plTempCoeff  = new TCoeff[ MAX_CU_SIZE*MAX_CU_SIZE ];
+
   // allocate bit estimation class  (for RDOQ)
   m_pcEstBitsSbac = new estBitsSbacStruct;
@@ -99,5 +142,5 @@
     m_plTempCoeff = NULL;
   }
-  
+
   // delete bit estimation class
   if ( m_pcEstBitsSbac )
@@ -111,12 +154,14 @@
 Void TComTrQuant::storeSliceQpNext(TComSlice* pcSlice)
 {
+  // NOTE: does this work with negative QPs or when some blocks are transquant-bypass enabled?
+
   Int qpBase = pcSlice->getSliceQpBase();
   Int sliceQpused = pcSlice->getSliceQp();
   Int sliceQpnext;
   Double alpha = qpBase < 17 ? 0.5 : 1;
-  
+
   Int cnt=0;
   for(Int u=1; u<=LEVEL_RANGE; u++)
-  { 
+  {
     cnt += m_sliceNsamples[u] ;
   }
@@ -161,5 +206,5 @@
   }
 
-  m_qpDelta[qpBase] = sliceQpnext - qpBase; 
+  m_qpDelta[qpBase] = sliceQpnext - qpBase;
 }
 
@@ -173,5 +218,5 @@
 
 Void TComTrQuant::clearSliceARLCnt()
-{ 
+{
   memset(m_sliceSumC, 0, sizeof(Double)*(LEVEL_RANGE+1));
   memset(m_sliceNsamples, 0, sizeof(Int)*(LEVEL_RANGE+1));
@@ -180,37 +225,4 @@
 
 
-/** Set qP for Quantization.
- * \param qpy QPy
- * \param bLowpass
- * \param eSliceType
- * \param eTxtType
- * \param qpBdOffset
- * \param chromaQPOffset
- *
- * return void  
- */
-Void TComTrQuant::setQPforQuant( Int qpy, TextType eTxtType, Int qpBdOffset, Int chromaQPOffset)
-{
-  Int qpScaled;
-
-  if(eTxtType == TEXT_LUMA)
-  {
-    qpScaled = qpy + qpBdOffset;
-  }
-  else
-  {
-    qpScaled = Clip3( -qpBdOffset, 57, qpy + chromaQPOffset );
-
-    if(qpScaled < 0)
-    {
-      qpScaled = qpScaled + qpBdOffset;
-    }
-    else
-    {
-      qpScaled = g_aucChromaScale[ qpScaled ] + qpBdOffset;
-    }
-  }
-  m_cQP.setQpParam( qpScaled );
-}
 
 #if MATRIX_MULT
@@ -222,26 +234,27 @@
  *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
  */
-void xTr(Int bitDepth, Pel *block, Int *coeff, UInt uiStride, UInt uiTrSize, UInt uiMode)
-{
-  Int i,j,k,iSum;
-  Int tmp[32*32];
-  const Short *iT;
+Void xTr(Int bitDepth, Pel *block, TCoeff *coeff, UInt uiStride, UInt uiTrSize, Bool useDST, const Int maxLog2TrDynamicRange)
+{
+  UInt i,j,k;
+  TCoeff iSum;
+  TCoeff tmp[MAX_TU_SIZE * MAX_TU_SIZE];
+  const TMatrixCoeff *iT;
   UInt uiLog2TrSize = g_aucConvertToBit[ uiTrSize ] + 2;
 
   if (uiTrSize==4)
   {
-    iT  = g_aiT4[0];
+    iT  = (useDST ? g_as_DST_MAT_4[TRANSFORM_FORWARD][0] : g_aiT4[TRANSFORM_FORWARD][0]);
   }
   else if (uiTrSize==8)
   {
-    iT = g_aiT8[0];
+    iT = g_aiT8[TRANSFORM_FORWARD][0];
   }
   else if (uiTrSize==16)
   {
-    iT = g_aiT16[0];
+    iT = g_aiT16[TRANSFORM_FORWARD][0];
   }
   else if (uiTrSize==32)
   {
-    iT = g_aiT32[0];
+    iT = g_aiT32[TRANSFORM_FORWARD][0];
   }
   else
@@ -250,18 +263,13 @@
   }
 
-  Int shift_1st = uiLog2TrSize - 1 + bitDepth-8; // log2(N) - 1 + g_bitDepth-8
-  Int add_1st = 1<<(shift_1st-1);
-  Int shift_2nd = uiLog2TrSize + 6;
-  Int add_2nd = 1<<(shift_2nd-1);
+  const Int TRANSFORM_MATRIX_SHIFT = g_transformMatrixShift[TRANSFORM_FORWARD];
+
+  const Int shift_1st = (uiLog2TrSize +  bitDepth + TRANSFORM_MATRIX_SHIFT) - maxLog2TrDynamicRange;
+  const Int shift_2nd = uiLog2TrSize + TRANSFORM_MATRIX_SHIFT;
+  const Int add_1st = (shift_1st>0) ? (1<<(shift_1st-1)) : 0;
+  const Int add_2nd = 1<<(shift_2nd-1);
 
   /* Horizontal transform */
 
-  if (uiTrSize==4)
-  {
-    if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode])
-    {
-      iT  =  g_as_DST_MAT_4[0];
-    }
-  }
   for (i=0; i<uiTrSize; i++)
   {
@@ -276,19 +284,8 @@
     }
   }
-  
+
   /* Vertical transform */
-  if (uiTrSize==4)
-  {
-    if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode])
-    {
-      iT  =  g_as_DST_MAT_4[0];
-    }
-    else
-    {
-      iT  = g_aiT4[0];
-    }
-  }
   for (i=0; i<uiTrSize; i++)
-  {                 
+  {
     for (j=0; j<uiTrSize; j++)
     {
@@ -296,7 +293,7 @@
       for (k=0; k<uiTrSize; k++)
       {
-        iSum += iT[i*uiTrSize+k]*tmp[j*uiTrSize+k];        
-      }
-      coeff[i*uiTrSize+j] = (iSum + add_2nd)>>shift_2nd; 
+        iSum += iT[i*uiTrSize+k]*tmp[j*uiTrSize+k];
+      }
+      coeff[i*uiTrSize+j] = (iSum + add_2nd)>>shift_2nd;
     }
   }
@@ -310,25 +307,26 @@
  *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
  */
-void xITr(Int *coeff, Pel *block, UInt uiStride, UInt uiTrSize, UInt uiMode)
-{
-  Int i,j,k,iSum;
-  Int tmp[32*32];
-  const Short *iT;
-  
+Void xITr(Int bitDepth, TCoeff *coeff, Pel *block, UInt uiStride, UInt uiTrSize, Bool useDST, const Int maxLog2TrDynamicRange)
+{
+  UInt i,j,k;
+  TCoeff iSum;
+  TCoeff tmp[MAX_TU_SIZE * MAX_TU_SIZE];
+  const TMatrixCoeff *iT;
+
   if (uiTrSize==4)
   {
-    iT  = g_aiT4[0];
+    iT  = (useDST ? g_as_DST_MAT_4[TRANSFORM_INVERSE][0] : g_aiT4[TRANSFORM_INVERSE][0]);
   }
   else if (uiTrSize==8)
   {
-    iT = g_aiT8[0];
+    iT = g_aiT8[TRANSFORM_INVERSE][0];
   }
   else if (uiTrSize==16)
   {
-    iT = g_aiT16[0];
+    iT = g_aiT16[TRANSFORM_INVERSE][0];
   }
   else if (uiTrSize==32)
   {
-    iT = g_aiT32[0];
+    iT = g_aiT32[TRANSFORM_INVERSE][0];
   }
   else
@@ -336,59 +334,49 @@
     assert(0);
   }
-  
-  Int shift_1st = SHIFT_INV_1ST;
-  Int add_1st = 1<<(shift_1st-1);
-  Int shift_2nd = SHIFT_INV_2ND - g_bitDepth-8;
-  Int add_2nd = 1<<(shift_2nd-1);
-  if (uiTrSize==4)
-  {
-    if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode] ) // Check for DCT or DST
-    {
-      iT  =  g_as_DST_MAT_4[0];
-    }
-  }
-  
+
+  const Int TRANSFORM_MATRIX_SHIFT = g_transformMatrixShift[TRANSFORM_INVERSE];
+
+  const Int shift_1st = TRANSFORM_MATRIX_SHIFT + 1; //1 has been added to shift_1st at the expense of shift_2nd
+  const Int shift_2nd = (TRANSFORM_MATRIX_SHIFT + maxLog2TrDynamicRange - 1) - bitDepth;
+  const TCoeff clipMinimum = -(1 << maxLog2TrDynamicRange);
+  const TCoeff clipMaximum =  (1 << maxLog2TrDynamicRange) - 1;
+  assert(shift_2nd>=0);
+  const Int add_1st = 1<<(shift_1st-1);
+  const Int add_2nd = (shift_2nd>0) ? (1<<(shift_2nd-1)) : 0;
+
   /* Horizontal transform */
   for (i=0; i<uiTrSize; i++)
-  {    
+  {
     for (j=0; j<uiTrSize; j++)
     {
       iSum = 0;
       for (k=0; k<uiTrSize; k++)
-      {        
-        iSum += iT[k*uiTrSize+i]*coeff[k*uiTrSize+j]; 
-      }
-      tmp[i*uiTrSize+j] = Clip3(-32768, 32767, (iSum + add_1st)>>shift_1st); // Clipping is normative
-    }
-  }   
-  
-  if (uiTrSize==4)
-  {
-    if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode] )   // Check for DCT or DST
-    {
-      iT  =  g_as_DST_MAT_4[0];
-    }
-    else  
-    {
-      iT  = g_aiT4[0];
-    }
-  }
-  
+      {
+        iSum += iT[k*uiTrSize+i]*coeff[k*uiTrSize+j];
+      }
+
+      // Clipping here is not in the standard, but is used to protect the "Pel" data type into which the inverse-transformed samples will be copied
+      tmp[i*uiTrSize+j] = Clip3<TCoeff>(clipMinimum, clipMaximum, (iSum + add_1st)>>shift_1st);
+    }
+  }
+
   /* Vertical transform */
   for (i=0; i<uiTrSize; i++)
-  {   
+  {
     for (j=0; j<uiTrSize; j++)
     {
       iSum = 0;
       for (k=0; k<uiTrSize; k++)
-      {        
+      {
         iSum += iT[k*uiTrSize+j]*tmp[i*uiTrSize+k];
       }
-      block[i*uiStride+j] = Clip3(-32768, 32767, (iSum + add_2nd)>>shift_2nd); // Clipping is non-normative
-    }
-  }
-}
-
-#else //MATRIX_MULT
+
+      block[i*uiStride+j] = Clip3<TCoeff>(std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max(), (iSum + add_2nd)>>shift_2nd);
+    }
+  }
+}
+
+#endif //MATRIX_MULT
+
 
 /** 4x4 forward transform implemented using partial butterfly structure (1D)
@@ -396,14 +384,14 @@
  *  \param dst   output data (transform coefficients)
  *  \param shift specifies right shift after 1D transform
+ *  \param line
  */
-
-void partialButterfly4(Short *src,Short *dst,Int shift, Int line)
+Void partialButterfly4(TCoeff *src, TCoeff *dst, Int shift, Int line)
 {
   Int j;
-  Int E[2],O[2];
-  Int add = 1<<(shift-1);
+  TCoeff E[2],O[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
 
   for (j=0; j<line; j++)
-  {    
+  {
     /* E and O */
     E[0] = src[0] + src[3];
@@ -412,8 +400,8 @@
     O[1] = src[1] - src[2];
 
-    dst[0] = (g_aiT4[0][0]*E[0] + g_aiT4[0][1]*E[1] + add)>>shift;
-    dst[2*line] = (g_aiT4[2][0]*E[0] + g_aiT4[2][1]*E[1] + add)>>shift;
-    dst[line] = (g_aiT4[1][0]*O[0] + g_aiT4[1][1]*O[1] + add)>>shift;
-    dst[3*line] = (g_aiT4[3][0]*O[0] + g_aiT4[3][1]*O[1] + add)>>shift;
+    dst[0]      = (g_aiT4[TRANSFORM_FORWARD][0][0]*E[0] + g_aiT4[TRANSFORM_FORWARD][0][1]*E[1] + add)>>shift;
+    dst[2*line] = (g_aiT4[TRANSFORM_FORWARD][2][0]*E[0] + g_aiT4[TRANSFORM_FORWARD][2][1]*E[1] + add)>>shift;
+    dst[line]   = (g_aiT4[TRANSFORM_FORWARD][1][0]*O[0] + g_aiT4[TRANSFORM_FORWARD][1][1]*O[1] + add)>>shift;
+    dst[3*line] = (g_aiT4[TRANSFORM_FORWARD][3][0]*O[0] + g_aiT4[TRANSFORM_FORWARD][3][1]*O[1] + add)>>shift;
 
     src += 4;
@@ -422,64 +410,88 @@
 }
 
-// Fast DST Algorithm. Full matrix multiplication for DST and Fast DST algorithm 
+// Fast DST Algorithm. Full matrix multiplication for DST and Fast DST algorithm
 // give identical results
-void fastForwardDst(Short *block,Short *coeff,Int shift)  // input block, output coeff
-{
-  Int i, c[4];
-  Int rnd_factor = 1<<(shift-1);
+Void fastForwardDst(TCoeff *block, TCoeff *coeff, Int shift)  // input block, output coeff
+{
+  Int i;
+  TCoeff c[4];
+  TCoeff rnd_factor = (shift > 0) ? (1<<(shift-1)) : 0;
   for (i=0; i<4; i++)
   {
     // Intermediate Variables
-    c[0] = block[4*i+0] + block[4*i+3];
-    c[1] = block[4*i+1] + block[4*i+3];
-    c[2] = block[4*i+0] - block[4*i+1];
-    c[3] = 74* block[4*i+2];
-
-    coeff[   i] =  ( 29 * c[0] + 55 * c[1]         + c[3]               + rnd_factor ) >> shift;
-    coeff[ 4+i] =  ( 74 * (block[4*i+0]+ block[4*i+1] - block[4*i+3])   + rnd_factor ) >> shift;
-    coeff[ 8+i] =  ( 29 * c[2] + 55 * c[0]         - c[3]               + rnd_factor ) >> shift;
-    coeff[12+i] =  ( 55 * c[2] - 29 * c[1]         + c[3]               + rnd_factor ) >> shift;
-  }
-}
-
-void fastInverseDst(Short *tmp,Short *block,Int shift)  // input tmp, output block
-{
-  Int i, c[4];
-  Int rnd_factor = 1<<(shift-1);
+    c[0] = block[4*i+0];
+    c[1] = block[4*i+1];
+    c[2] = block[4*i+2];
+    c[3] = block[4*i+3];
+
+    for (Int row = 0; row < 4; row++)
+    {
+      TCoeff result = 0;
+      for (Int column = 0; column < 4; column++)
+      {
+        result += c[column] * g_as_DST_MAT_4[TRANSFORM_FORWARD][row][column]; // use the defined matrix, rather than hard-wired numbers
+      }
+
+      coeff[(row * 4) + i] = rightShift((result + rnd_factor), shift);
+    }
+  }
+}
+
+Void fastInverseDst(TCoeff *tmp, TCoeff *block, Int shift, const TCoeff outputMinimum, const TCoeff outputMaximum)  // input tmp, output block
+{
+  Int i;
+  TCoeff c[4];
+  TCoeff rnd_factor = (shift > 0) ? (1<<(shift-1)) : 0;
   for (i=0; i<4; i++)
-  {  
+  {
     // Intermediate Variables
-    c[0] = tmp[  i] + tmp[ 8+i];
-    c[1] = tmp[8+i] + tmp[12+i];
-    c[2] = tmp[  i] - tmp[12+i];
-    c[3] = 74* tmp[4+i];
-
-    block[4*i+0] = Clip3( -32768, 32767, ( 29 * c[0] + 55 * c[1]     + c[3]               + rnd_factor ) >> shift );
-    block[4*i+1] = Clip3( -32768, 32767, ( 55 * c[2] - 29 * c[1]     + c[3]               + rnd_factor ) >> shift );
-    block[4*i+2] = Clip3( -32768, 32767, ( 74 * (tmp[i] - tmp[8+i]  + tmp[12+i])      + rnd_factor ) >> shift );
-    block[4*i+3] = Clip3( -32768, 32767, ( 55 * c[0] + 29 * c[2]     - c[3]               + rnd_factor ) >> shift );
-  }
-}
-
-void partialButterflyInverse4(Short *src,Short *dst,Int shift, Int line)
+    c[0] = tmp[   i];
+    c[1] = tmp[4 +i];
+    c[2] = tmp[8 +i];
+    c[3] = tmp[12+i];
+
+    for (Int column = 0; column < 4; column++)
+    {
+      TCoeff &result = block[(i * 4) + column];
+
+      result = 0;
+      for (Int row = 0; row < 4; row++)
+      {
+        result += c[row] * g_as_DST_MAT_4[TRANSFORM_INVERSE][row][column]; // use the defined matrix, rather than hard-wired numbers
+      }
+
+      result = Clip3( outputMinimum, outputMaximum, rightShift((result + rnd_factor), shift));
+    }
+  }
+}
+
+/** 4x4 inverse transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (transform coefficients)
+ *  \param dst   output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ *  \param line
+ *  \param outputMinimum  minimum for clipping
+ *  \param outputMaximum  maximum for clipping
+ */
+Void partialButterflyInverse4(TCoeff *src, TCoeff *dst, Int shift, Int line, const TCoeff outputMinimum, const TCoeff outputMaximum)
 {
   Int j;
-  Int E[2],O[2];
-  Int add = 1<<(shift-1);
+  TCoeff E[2],O[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
 
   for (j=0; j<line; j++)
-  {    
-    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */    
-    O[0] = g_aiT4[1][0]*src[line] + g_aiT4[3][0]*src[3*line];
-    O[1] = g_aiT4[1][1]*src[line] + g_aiT4[3][1]*src[3*line];
-    E[0] = g_aiT4[0][0]*src[0] + g_aiT4[2][0]*src[2*line];
-    E[1] = g_aiT4[0][1]*src[0] + g_aiT4[2][1]*src[2*line];
+  {
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
+    O[0] = g_aiT4[TRANSFORM_INVERSE][1][0]*src[line] + g_aiT4[TRANSFORM_INVERSE][3][0]*src[3*line];
+    O[1] = g_aiT4[TRANSFORM_INVERSE][1][1]*src[line] + g_aiT4[TRANSFORM_INVERSE][3][1]*src[3*line];
+    E[0] = g_aiT4[TRANSFORM_INVERSE][0][0]*src[0]    + g_aiT4[TRANSFORM_INVERSE][2][0]*src[2*line];
+    E[1] = g_aiT4[TRANSFORM_INVERSE][0][1]*src[0]    + g_aiT4[TRANSFORM_INVERSE][2][1]*src[2*line];
 
     /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
-    dst[0] = Clip3( -32768, 32767, (E[0] + O[0] + add)>>shift );
-    dst[1] = Clip3( -32768, 32767, (E[1] + O[1] + add)>>shift );
-    dst[2] = Clip3( -32768, 32767, (E[1] - O[1] + add)>>shift );
-    dst[3] = Clip3( -32768, 32767, (E[0] - O[0] + add)>>shift );
-            
+    dst[0] = Clip3( outputMinimum, outputMaximum, (E[0] + O[0] + add)>>shift );
+    dst[1] = Clip3( outputMinimum, outputMaximum, (E[1] + O[1] + add)>>shift );
+    dst[2] = Clip3( outputMinimum, outputMaximum, (E[1] - O[1] + add)>>shift );
+    dst[3] = Clip3( outputMinimum, outputMaximum, (E[0] - O[0] + add)>>shift );
+
     src   ++;
     dst += 4;
@@ -487,14 +499,19 @@
 }
 
-
-void partialButterfly8(Short *src,Short *dst,Int shift, Int line)
+/** 8x8 forward transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (residual)
+ *  \param dst   output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ *  \param line
+ */
+Void partialButterfly8(TCoeff *src, TCoeff *dst, Int shift, Int line)
 {
   Int j,k;
-  Int E[4],O[4];
-  Int EE[2],EO[2];
-  Int add = 1<<(shift-1);
+  TCoeff E[4],O[4];
+  TCoeff EE[2],EO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
 
   for (j=0; j<line; j++)
-  {  
+  {
     /* E and O*/
     for (k=0;k<4;k++)
@@ -502,20 +519,20 @@
       E[k] = src[k] + src[7-k];
       O[k] = src[k] - src[7-k];
-    }    
+    }
     /* EE and EO */
-    EE[0] = E[0] + E[3];    
+    EE[0] = E[0] + E[3];
     EO[0] = E[0] - E[3];
     EE[1] = E[1] + E[2];
     EO[1] = E[1] - E[2];
 
-    dst[0] = (g_aiT8[0][0]*EE[0] + g_aiT8[0][1]*EE[1] + add)>>shift;
-    dst[4*line] = (g_aiT8[4][0]*EE[0] + g_aiT8[4][1]*EE[1] + add)>>shift; 
-    dst[2*line] = (g_aiT8[2][0]*EO[0] + g_aiT8[2][1]*EO[1] + add)>>shift;
-    dst[6*line] = (g_aiT8[6][0]*EO[0] + g_aiT8[6][1]*EO[1] + add)>>shift; 
-
-    dst[line] = (g_aiT8[1][0]*O[0] + g_aiT8[1][1]*O[1] + g_aiT8[1][2]*O[2] + g_aiT8[1][3]*O[3] + add)>>shift;
-    dst[3*line] = (g_aiT8[3][0]*O[0] + g_aiT8[3][1]*O[1] + g_aiT8[3][2]*O[2] + g_aiT8[3][3]*O[3] + add)>>shift;
-    dst[5*line] = (g_aiT8[5][0]*O[0] + g_aiT8[5][1]*O[1] + g_aiT8[5][2]*O[2] + g_aiT8[5][3]*O[3] + add)>>shift;
-    dst[7*line] = (g_aiT8[7][0]*O[0] + g_aiT8[7][1]*O[1] + g_aiT8[7][2]*O[2] + g_aiT8[7][3]*O[3] + add)>>shift;
+    dst[0]      = (g_aiT8[TRANSFORM_FORWARD][0][0]*EE[0] + g_aiT8[TRANSFORM_FORWARD][0][1]*EE[1] + add)>>shift;
+    dst[4*line] = (g_aiT8[TRANSFORM_FORWARD][4][0]*EE[0] + g_aiT8[TRANSFORM_FORWARD][4][1]*EE[1] + add)>>shift;
+    dst[2*line] = (g_aiT8[TRANSFORM_FORWARD][2][0]*EO[0] + g_aiT8[TRANSFORM_FORWARD][2][1]*EO[1] + add)>>shift;
+    dst[6*line] = (g_aiT8[TRANSFORM_FORWARD][6][0]*EO[0] + g_aiT8[TRANSFORM_FORWARD][6][1]*EO[1] + add)>>shift;
+
+    dst[line]   = (g_aiT8[TRANSFORM_FORWARD][1][0]*O[0] + g_aiT8[TRANSFORM_FORWARD][1][1]*O[1] + g_aiT8[TRANSFORM_FORWARD][1][2]*O[2] + g_aiT8[TRANSFORM_FORWARD][1][3]*O[3] + add)>>shift;
+    dst[3*line] = (g_aiT8[TRANSFORM_FORWARD][3][0]*O[0] + g_aiT8[TRANSFORM_FORWARD][3][1]*O[1] + g_aiT8[TRANSFORM_FORWARD][3][2]*O[2] + g_aiT8[TRANSFORM_FORWARD][3][3]*O[3] + add)>>shift;
+    dst[5*line] = (g_aiT8[TRANSFORM_FORWARD][5][0]*O[0] + g_aiT8[TRANSFORM_FORWARD][5][1]*O[1] + g_aiT8[TRANSFORM_FORWARD][5][2]*O[2] + g_aiT8[TRANSFORM_FORWARD][5][3]*O[3] + add)>>shift;
+    dst[7*line] = (g_aiT8[TRANSFORM_FORWARD][7][0]*O[0] + g_aiT8[TRANSFORM_FORWARD][7][1]*O[1] + g_aiT8[TRANSFORM_FORWARD][7][2]*O[2] + g_aiT8[TRANSFORM_FORWARD][7][3]*O[3] + add)>>shift;
 
     src += 8;
@@ -524,26 +541,34 @@
 }
 
-
-void partialButterflyInverse8(Short *src,Short *dst,Int shift, Int line)
+/** 8x8 inverse transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (transform coefficients)
+ *  \param dst   output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ *  \param line
+ *  \param outputMinimum  minimum for clipping
+ *  \param outputMaximum  maximum for clipping
+ */
+Void partialButterflyInverse8(TCoeff *src, TCoeff *dst, Int shift, Int line, const TCoeff outputMinimum, const TCoeff outputMaximum)
 {
   Int j,k;
-  Int E[4],O[4];
-  Int EE[2],EO[2];
-  Int add = 1<<(shift-1);
-
-  for (j=0; j<line; j++) 
-  {    
+  TCoeff E[4],O[4];
+  TCoeff EE[2],EO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  for (j=0; j<line; j++)
+  {
     /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
     for (k=0;k<4;k++)
     {
-      O[k] = g_aiT8[ 1][k]*src[line] + g_aiT8[ 3][k]*src[3*line] + g_aiT8[ 5][k]*src[5*line] + g_aiT8[ 7][k]*src[7*line];
-    }
-
-    EO[0] = g_aiT8[2][0]*src[ 2*line ] + g_aiT8[6][0]*src[ 6*line ];
-    EO[1] = g_aiT8[2][1]*src[ 2*line ] + g_aiT8[6][1]*src[ 6*line ];
-    EE[0] = g_aiT8[0][0]*src[ 0      ] + g_aiT8[4][0]*src[ 4*line ];
-    EE[1] = g_aiT8[0][1]*src[ 0      ] + g_aiT8[4][1]*src[ 4*line ];
-
-    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */ 
+      O[k] = g_aiT8[TRANSFORM_INVERSE][ 1][k]*src[line]   + g_aiT8[TRANSFORM_INVERSE][ 3][k]*src[3*line] +
+             g_aiT8[TRANSFORM_INVERSE][ 5][k]*src[5*line] + g_aiT8[TRANSFORM_INVERSE][ 7][k]*src[7*line];
+    }
+
+    EO[0] = g_aiT8[TRANSFORM_INVERSE][2][0]*src[ 2*line ] + g_aiT8[TRANSFORM_INVERSE][6][0]*src[ 6*line ];
+    EO[1] = g_aiT8[TRANSFORM_INVERSE][2][1]*src[ 2*line ] + g_aiT8[TRANSFORM_INVERSE][6][1]*src[ 6*line ];
+    EE[0] = g_aiT8[TRANSFORM_INVERSE][0][0]*src[ 0      ] + g_aiT8[TRANSFORM_INVERSE][4][0]*src[ 4*line ];
+    EE[1] = g_aiT8[TRANSFORM_INVERSE][0][1]*src[ 0      ] + g_aiT8[TRANSFORM_INVERSE][4][1]*src[ 4*line ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
     E[0] = EE[0] + EO[0];
     E[3] = EE[0] - EO[0];
@@ -552,7 +577,7 @@
     for (k=0;k<4;k++)
     {
-      dst[ k   ] = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
-      dst[ k+4 ] = Clip3( -32768, 32767, (E[3-k] - O[3-k] + add)>>shift );
-    }   
+      dst[ k   ] = Clip3( outputMinimum, outputMaximum, (E[k] + O[k] + add)>>shift );
+      dst[ k+4 ] = Clip3( outputMinimum, outputMaximum, (E[3-k] - O[3-k] + add)>>shift );
+    }
     src ++;
     dst += 8;
@@ -560,15 +585,20 @@
 }
 
-
-void partialButterfly16(Short *src,Short *dst,Int shift, Int line)
+/** 16x16 forward transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (residual)
+ *  \param dst   output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ *  \param line
+ */
+Void partialButterfly16(TCoeff *src, TCoeff *dst, Int shift, Int line)
 {
   Int j,k;
-  Int E[8],O[8];
-  Int EE[4],EO[4];
-  Int EEE[2],EEO[2];
-  Int add = 1<<(shift-1);
-
-  for (j=0; j<line; j++) 
-  {    
+  TCoeff E[8],O[8];
+  TCoeff EE[4],EO[4];
+  TCoeff EEE[2],EEO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  for (j=0; j<line; j++)
+  {
     /* E and O*/
     for (k=0;k<8;k++)
@@ -576,5 +606,5 @@
       E[k] = src[k] + src[15-k];
       O[k] = src[k] - src[15-k];
-    } 
+    }
     /* EE and EO */
     for (k=0;k<4;k++)
@@ -584,90 +614,108 @@
     }
     /* EEE and EEO */
-    EEE[0] = EE[0] + EE[3];    
+    EEE[0] = EE[0] + EE[3];
     EEO[0] = EE[0] - EE[3];
     EEE[1] = EE[1] + EE[2];
     EEO[1] = EE[1] - EE[2];
 
-    dst[ 0      ] = (g_aiT16[ 0][0]*EEE[0] + g_aiT16[ 0][1]*EEE[1] + add)>>shift;        
-    dst[ 8*line ] = (g_aiT16[ 8][0]*EEE[0] + g_aiT16[ 8][1]*EEE[1] + add)>>shift;    
-    dst[ 4*line ] = (g_aiT16[ 4][0]*EEO[0] + g_aiT16[ 4][1]*EEO[1] + add)>>shift;        
-    dst[ 12*line] = (g_aiT16[12][0]*EEO[0] + g_aiT16[12][1]*EEO[1] + add)>>shift;
+    dst[ 0      ] = (g_aiT16[TRANSFORM_FORWARD][ 0][0]*EEE[0] + g_aiT16[TRANSFORM_FORWARD][ 0][1]*EEE[1] + add)>>shift;
+    dst[ 8*line ] = (g_aiT16[TRANSFORM_FORWARD][ 8][0]*EEE[0] + g_aiT16[TRANSFORM_FORWARD][ 8][1]*EEE[1] + add)>>shift;
+    dst[ 4*line ] = (g_aiT16[TRANSFORM_FORWARD][ 4][0]*EEO[0] + g_aiT16[TRANSFORM_FORWARD][ 4][1]*EEO[1] + add)>>shift;
+    dst[ 12*line] = (g_aiT16[TRANSFORM_FORWARD][12][0]*EEO[0] + g_aiT16[TRANSFORM_FORWARD][12][1]*EEO[1] + add)>>shift;
 
     for (k=2;k<16;k+=4)
     {
-      dst[ k*line ] = (g_aiT16[k][0]*EO[0] + g_aiT16[k][1]*EO[1] + g_aiT16[k][2]*EO[2] + g_aiT16[k][3]*EO[3] + add)>>shift;      
+      dst[ k*line ] = (g_aiT16[TRANSFORM_FORWARD][k][0]*EO[0] + g_aiT16[TRANSFORM_FORWARD][k][1]*EO[1] +
+                       g_aiT16[TRANSFORM_FORWARD][k][2]*EO[2] + g_aiT16[TRANSFORM_FORWARD][k][3]*EO[3] + add)>>shift;
     }
 
     for (k=1;k<16;k+=2)
     {
-      dst[ k*line ] = (g_aiT16[k][0]*O[0] + g_aiT16[k][1]*O[1] + g_aiT16[k][2]*O[2] + g_aiT16[k][3]*O[3] + 
-        g_aiT16[k][4]*O[4] + g_aiT16[k][5]*O[5] + g_aiT16[k][6]*O[6] + g_aiT16[k][7]*O[7] + add)>>shift;
+      dst[ k*line ] = (g_aiT16[TRANSFORM_FORWARD][k][0]*O[0] + g_aiT16[TRANSFORM_FORWARD][k][1]*O[1] +
+                       g_aiT16[TRANSFORM_FORWARD][k][2]*O[2] + g_aiT16[TRANSFORM_FORWARD][k][3]*O[3] +
+                       g_aiT16[TRANSFORM_FORWARD][k][4]*O[4] + g_aiT16[TRANSFORM_FORWARD][k][5]*O[5] +
+                       g_aiT16[TRANSFORM_FORWARD][k][6]*O[6] + g_aiT16[TRANSFORM_FORWARD][k][7]*O[7] + add)>>shift;
     }
 
     src += 16;
-    dst ++; 
-
-  }
-}
-
-
-void partialButterflyInverse16(Short *src,Short *dst,Int shift, Int line)
+    dst ++;
+
+  }
+}
+
+/** 16x16 inverse transform implemented using partial butterfly structure (1D)
+ *  \param src            input data (transform coefficients)
+ *  \param dst            output data (residual)
+ *  \param shift          specifies right shift after 1D transform
+ *  \param line
+ *  \param outputMinimum  minimum for clipping
+ *  \param outputMaximum  maximum for clipping
+ */
+Void partialButterflyInverse16(TCoeff *src, TCoeff *dst, Int shift, Int line, const TCoeff outputMinimum, const TCoeff outputMaximum)
 {
   Int j,k;
-  Int E[8],O[8];
-  Int EE[4],EO[4];
-  Int EEE[2],EEO[2];
-  Int add = 1<<(shift-1);
+  TCoeff E[8],O[8];
+  TCoeff EE[4],EO[4];
+  TCoeff EEE[2],EEO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
 
   for (j=0; j<line; j++)
-  {    
+  {
     /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
     for (k=0;k<8;k++)
     {
-      O[k] = g_aiT16[ 1][k]*src[ line] + g_aiT16[ 3][k]*src[ 3*line] + g_aiT16[ 5][k]*src[ 5*line] + g_aiT16[ 7][k]*src[ 7*line] + 
-        g_aiT16[ 9][k]*src[ 9*line] + g_aiT16[11][k]*src[11*line] + g_aiT16[13][k]*src[13*line] + g_aiT16[15][k]*src[15*line];
+      O[k] = g_aiT16[TRANSFORM_INVERSE][ 1][k]*src[ line]   + g_aiT16[TRANSFORM_INVERSE][ 3][k]*src[ 3*line] +
+             g_aiT16[TRANSFORM_INVERSE][ 5][k]*src[ 5*line] + g_aiT16[TRANSFORM_INVERSE][ 7][k]*src[ 7*line] +
+             g_aiT16[TRANSFORM_INVERSE][ 9][k]*src[ 9*line] + g_aiT16[TRANSFORM_INVERSE][11][k]*src[11*line] +
+             g_aiT16[TRANSFORM_INVERSE][13][k]*src[13*line] + g_aiT16[TRANSFORM_INVERSE][15][k]*src[15*line];
     }
     for (k=0;k<4;k++)
     {
-      EO[k] = g_aiT16[ 2][k]*src[ 2*line] + g_aiT16[ 6][k]*src[ 6*line] + g_aiT16[10][k]*src[10*line] + g_aiT16[14][k]*src[14*line];
-    }
-    EEO[0] = g_aiT16[4][0]*src[ 4*line ] + g_aiT16[12][0]*src[ 12*line ];
-    EEE[0] = g_aiT16[0][0]*src[ 0      ] + g_aiT16[ 8][0]*src[ 8*line  ];
-    EEO[1] = g_aiT16[4][1]*src[ 4*line ] + g_aiT16[12][1]*src[ 12*line ];
-    EEE[1] = g_aiT16[0][1]*src[ 0      ] + g_aiT16[ 8][1]*src[ 8*line  ];
-
-    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */ 
+      EO[k] = g_aiT16[TRANSFORM_INVERSE][ 2][k]*src[ 2*line] + g_aiT16[TRANSFORM_INVERSE][ 6][k]*src[ 6*line] +
+              g_aiT16[TRANSFORM_INVERSE][10][k]*src[10*line] + g_aiT16[TRANSFORM_INVERSE][14][k]*src[14*line];
+    }
+    EEO[0] = g_aiT16[TRANSFORM_INVERSE][4][0]*src[ 4*line ] + g_aiT16[TRANSFORM_INVERSE][12][0]*src[ 12*line ];
+    EEE[0] = g_aiT16[TRANSFORM_INVERSE][0][0]*src[ 0      ] + g_aiT16[TRANSFORM_INVERSE][ 8][0]*src[ 8*line  ];
+    EEO[1] = g_aiT16[TRANSFORM_INVERSE][4][1]*src[ 4*line ] + g_aiT16[TRANSFORM_INVERSE][12][1]*src[ 12*line ];
+    EEE[1] = g_aiT16[TRANSFORM_INVERSE][0][1]*src[ 0      ] + g_aiT16[TRANSFORM_INVERSE][ 8][1]*src[ 8*line  ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
     for (k=0;k<2;k++)
     {
       EE[k] = EEE[k] + EEO[k];
       EE[k+2] = EEE[1-k] - EEO[1-k];
-    }    
+    }
     for (k=0;k<4;k++)
     {
       E[k] = EE[k] + EO[k];
       E[k+4] = EE[3-k] - EO[3-k];
-    }    
+    }
     for (k=0;k<8;k++)
     {
-      dst[k]   = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
-      dst[k+8] = Clip3( -32768, 32767, (E[7-k] - O[7-k] + add)>>shift );
-    }   
-    src ++; 
+      dst[k]   = Clip3( outputMinimum, outputMaximum, (E[k] + O[k] + add)>>shift );
+      dst[k+8] = Clip3( outputMinimum, outputMaximum, (E[7-k] - O[7-k] + add)>>shift );
+    }
+    src ++;
     dst += 16;
   }
 }
 
-
-void partialButterfly32(Short *src,Short *dst,Int shift, Int line)
+/** 32x32 forward transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (residual)
+ *  \param dst   output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ *  \param line
+ */
+Void partialButterfly32(TCoeff *src, TCoeff *dst, Int shift, Int line)
 {
   Int j,k;
-  Int E[16],O[16];
-  Int EE[8],EO[8];
-  Int EEE[4],EEO[4];
-  Int EEEE[2],EEEO[2];
-  Int add = 1<<(shift-1);
+  TCoeff E[16],O[16];
+  TCoeff EE[8],EO[8];
+  TCoeff EEE[4],EEO[4];
+  TCoeff EEEE[2],EEEO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
 
   for (j=0; j<line; j++)
-  {    
+  {
     /* E and O*/
     for (k=0;k<16;k++)
@@ -675,5 +723,5 @@
       E[k] = src[k] + src[31-k];
       O[k] = src[k] - src[31-k];
-    } 
+    }
     /* EE and EO */
     for (k=0;k<8;k++)
@@ -689,29 +737,37 @@
     }
     /* EEEE and EEEO */
-    EEEE[0] = EEE[0] + EEE[3];    
+    EEEE[0] = EEE[0] + EEE[3];
     EEEO[0] = EEE[0] - EEE[3];
     EEEE[1] = EEE[1] + EEE[2];
     EEEO[1] = EEE[1] - EEE[2];
 
-    dst[ 0       ] = (g_aiT32[ 0][0]*EEEE[0] + g_aiT32[ 0][1]*EEEE[1] + add)>>shift;
-    dst[ 16*line ] = (g_aiT32[16][0]*EEEE[0] + g_aiT32[16][1]*EEEE[1] + add)>>shift;
-    dst[ 8*line  ] = (g_aiT32[ 8][0]*EEEO[0] + g_aiT32[ 8][1]*EEEO[1] + add)>>shift; 
-    dst[ 24*line ] = (g_aiT32[24][0]*EEEO[0] + g_aiT32[24][1]*EEEO[1] + add)>>shift;
+    dst[ 0       ] = (g_aiT32[TRANSFORM_FORWARD][ 0][0]*EEEE[0] + g_aiT32[TRANSFORM_FORWARD][ 0][1]*EEEE[1] + add)>>shift;
+    dst[ 16*line ] = (g_aiT32[TRANSFORM_FORWARD][16][0]*EEEE[0] + g_aiT32[TRANSFORM_FORWARD][16][1]*EEEE[1] + add)>>shift;
+    dst[ 8*line  ] = (g_aiT32[TRANSFORM_FORWARD][ 8][0]*EEEO[0] + g_aiT32[TRANSFORM_FORWARD][ 8][1]*EEEO[1] + add)>>shift;
+    dst[ 24*line ] = (g_aiT32[TRANSFORM_FORWARD][24][0]*EEEO[0] + g_aiT32[TRANSFORM_FORWARD][24][1]*EEEO[1] + add)>>shift;
     for (k=4;k<32;k+=8)
     {
-      dst[ k*line ] = (g_aiT32[k][0]*EEO[0] + g_aiT32[k][1]*EEO[1] + g_aiT32[k][2]*EEO[2] + g_aiT32[k][3]*EEO[3] + add)>>shift;
-    }       
+      dst[ k*line ] = (g_aiT32[TRANSFORM_FORWARD][k][0]*EEO[0] + g_aiT32[TRANSFORM_FORWARD][k][1]*EEO[1] +
+                       g_aiT32[TRANSFORM_FORWARD][k][2]*EEO[2] + g_aiT32[TRANSFORM_FORWARD][k][3]*EEO[3] + add)>>shift;
+    }
     for (k=2;k<32;k+=4)
     {
-      dst[ k*line ] = (g_aiT32[k][0]*EO[0] + g_aiT32[k][1]*EO[1] + g_aiT32[k][2]*EO[2] + g_aiT32[k][3]*EO[3] + 
-        g_aiT32[k][4]*EO[4] + g_aiT32[k][5]*EO[5] + g_aiT32[k][6]*EO[6] + g_aiT32[k][7]*EO[7] + add)>>shift;
-    }       
+      dst[ k*line ] = (g_aiT32[TRANSFORM_FORWARD][k][0]*EO[0] + g_aiT32[TRANSFORM_FORWARD][k][1]*EO[1] +
+                       g_aiT32[TRANSFORM_FORWARD][k][2]*EO[2] + g_aiT32[TRANSFORM_FORWARD][k][3]*EO[3] +
+                       g_aiT32[TRANSFORM_FORWARD][k][4]*EO[4] + g_aiT32[TRANSFORM_FORWARD][k][5]*EO[5] +
+                       g_aiT32[TRANSFORM_FORWARD][k][6]*EO[6] + g_aiT32[TRANSFORM_FORWARD][k][7]*EO[7] + add)>>shift;
+    }
     for (k=1;k<32;k+=2)
     {
-      dst[ k*line ] = (g_aiT32[k][ 0]*O[ 0] + g_aiT32[k][ 1]*O[ 1] + g_aiT32[k][ 2]*O[ 2] + g_aiT32[k][ 3]*O[ 3] + 
-        g_aiT32[k][ 4]*O[ 4] + g_aiT32[k][ 5]*O[ 5] + g_aiT32[k][ 6]*O[ 6] + g_aiT32[k][ 7]*O[ 7] +
-        g_aiT32[k][ 8]*O[ 8] + g_aiT32[k][ 9]*O[ 9] + g_aiT32[k][10]*O[10] + g_aiT32[k][11]*O[11] + 
-        g_aiT32[k][12]*O[12] + g_aiT32[k][13]*O[13] + g_aiT32[k][14]*O[14] + g_aiT32[k][15]*O[15] + add)>>shift;
-    }
+      dst[ k*line ] = (g_aiT32[TRANSFORM_FORWARD][k][ 0]*O[ 0] + g_aiT32[TRANSFORM_FORWARD][k][ 1]*O[ 1] +
+                       g_aiT32[TRANSFORM_FORWARD][k][ 2]*O[ 2] + g_aiT32[TRANSFORM_FORWARD][k][ 3]*O[ 3] +
+                       g_aiT32[TRANSFORM_FORWARD][k][ 4]*O[ 4] + g_aiT32[TRANSFORM_FORWARD][k][ 5]*O[ 5] +
+                       g_aiT32[TRANSFORM_FORWARD][k][ 6]*O[ 6] + g_aiT32[TRANSFORM_FORWARD][k][ 7]*O[ 7] +
+                       g_aiT32[TRANSFORM_FORWARD][k][ 8]*O[ 8] + g_aiT32[TRANSFORM_FORWARD][k][ 9]*O[ 9] +
+                       g_aiT32[TRANSFORM_FORWARD][k][10]*O[10] + g_aiT32[TRANSFORM_FORWARD][k][11]*O[11] +
+                       g_aiT32[TRANSFORM_FORWARD][k][12]*O[12] + g_aiT32[TRANSFORM_FORWARD][k][13]*O[13] +
+                       g_aiT32[TRANSFORM_FORWARD][k][14]*O[14] + g_aiT32[TRANSFORM_FORWARD][k][15]*O[15] + add)>>shift;
+    }
+
     src += 32;
     dst ++;
@@ -719,37 +775,51 @@
 }
 
-
-void partialButterflyInverse32(Short *src,Short *dst,Int shift, Int line)
+/** 32x32 inverse transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (transform coefficients)
+ *  \param dst   output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ *  \param line
+ *  \param outputMinimum  minimum for clipping
+ *  \param outputMaximum  maximum for clipping
+ */
+Void partialButterflyInverse32(TCoeff *src, TCoeff *dst, Int shift, Int line, const TCoeff outputMinimum, const TCoeff outputMaximum)
 {
   Int j,k;
-  Int E[16],O[16];
-  Int EE[8],EO[8];
-  Int EEE[4],EEO[4];
-  Int EEEE[2],EEEO[2];
-  Int add = 1<<(shift-1);
+  TCoeff E[16],O[16];
+  TCoeff EE[8],EO[8];
+  TCoeff EEE[4],EEO[4];
+  TCoeff EEEE[2],EEEO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
 
   for (j=0; j<line; j++)
-  {    
+  {
     /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
     for (k=0;k<16;k++)
     {
-      O[k] = g_aiT32[ 1][k]*src[ line  ] + g_aiT32[ 3][k]*src[ 3*line  ] + g_aiT32[ 5][k]*src[ 5*line  ] + g_aiT32[ 7][k]*src[ 7*line  ] + 
-        g_aiT32[ 9][k]*src[ 9*line  ] + g_aiT32[11][k]*src[ 11*line ] + g_aiT32[13][k]*src[ 13*line ] + g_aiT32[15][k]*src[ 15*line ] + 
-        g_aiT32[17][k]*src[ 17*line ] + g_aiT32[19][k]*src[ 19*line ] + g_aiT32[21][k]*src[ 21*line ] + g_aiT32[23][k]*src[ 23*line ] + 
-        g_aiT32[25][k]*src[ 25*line ] + g_aiT32[27][k]*src[ 27*line ] + g_aiT32[29][k]*src[ 29*line ] + g_aiT32[31][k]*src[ 31*line ];
+      O[k] = g_aiT32[TRANSFORM_INVERSE][ 1][k]*src[ line    ] + g_aiT32[TRANSFORM_INVERSE][ 3][k]*src[ 3*line  ] +
+             g_aiT32[TRANSFORM_INVERSE][ 5][k]*src[ 5*line  ] + g_aiT32[TRANSFORM_INVERSE][ 7][k]*src[ 7*line  ] +
+             g_aiT32[TRANSFORM_INVERSE][ 9][k]*src[ 9*line  ] + g_aiT32[TRANSFORM_INVERSE][11][k]*src[ 11*line ] +
+             g_aiT32[TRANSFORM_INVERSE][13][k]*src[ 13*line ] + g_aiT32[TRANSFORM_INVERSE][15][k]*src[ 15*line ] +
+             g_aiT32[TRANSFORM_INVERSE][17][k]*src[ 17*line ] + g_aiT32[TRANSFORM_INVERSE][19][k]*src[ 19*line ] +
+             g_aiT32[TRANSFORM_INVERSE][21][k]*src[ 21*line ] + g_aiT32[TRANSFORM_INVERSE][23][k]*src[ 23*line ] +
+             g_aiT32[TRANSFORM_INVERSE][25][k]*src[ 25*line ] + g_aiT32[TRANSFORM_INVERSE][27][k]*src[ 27*line ] +
+             g_aiT32[TRANSFORM_INVERSE][29][k]*src[ 29*line ] + g_aiT32[TRANSFORM_INVERSE][31][k]*src[ 31*line ];
     }
     for (k=0;k<8;k++)
     {
-      EO[k] = g_aiT32[ 2][k]*src[ 2*line  ] + g_aiT32[ 6][k]*src[ 6*line  ] + g_aiT32[10][k]*src[ 10*line ] + g_aiT32[14][k]*src[ 14*line ] + 
-        g_aiT32[18][k]*src[ 18*line ] + g_aiT32[22][k]*src[ 22*line ] + g_aiT32[26][k]*src[ 26*line ] + g_aiT32[30][k]*src[ 30*line ];
+      EO[k] = g_aiT32[TRANSFORM_INVERSE][ 2][k]*src[ 2*line  ] + g_aiT32[TRANSFORM_INVERSE][ 6][k]*src[ 6*line  ] +
+              g_aiT32[TRANSFORM_INVERSE][10][k]*src[ 10*line ] + g_aiT32[TRANSFORM_INVERSE][14][k]*src[ 14*line ] +
+              g_aiT32[TRANSFORM_INVERSE][18][k]*src[ 18*line ] + g_aiT32[TRANSFORM_INVERSE][22][k]*src[ 22*line ] +
+              g_aiT32[TRANSFORM_INVERSE][26][k]*src[ 26*line ] + g_aiT32[TRANSFORM_INVERSE][30][k]*src[ 30*line ];
     }
     for (k=0;k<4;k++)
     {
-      EEO[k] = g_aiT32[4][k]*src[ 4*line ] + g_aiT32[12][k]*src[ 12*line ] + g_aiT32[20][k]*src[ 20*line ] + g_aiT32[28][k]*src[ 28*line ];
-    }
-    EEEO[0] = g_aiT32[8][0]*src[ 8*line ] + g_aiT32[24][0]*src[ 24*line ];
-    EEEO[1] = g_aiT32[8][1]*src[ 8*line ] + g_aiT32[24][1]*src[ 24*line ];
-    EEEE[0] = g_aiT32[0][0]*src[ 0      ] + g_aiT32[16][0]*src[ 16*line ];    
-    EEEE[1] = g_aiT32[0][1]*src[ 0      ] + g_aiT32[16][1]*src[ 16*line ];
+      EEO[k] = g_aiT32[TRANSFORM_INVERSE][ 4][k]*src[  4*line ] + g_aiT32[TRANSFORM_INVERSE][12][k]*src[ 12*line ] +
+               g_aiT32[TRANSFORM_INVERSE][20][k]*src[ 20*line ] + g_aiT32[TRANSFORM_INVERSE][28][k]*src[ 28*line ];
+    }
+    EEEO[0] = g_aiT32[TRANSFORM_INVERSE][8][0]*src[ 8*line ] + g_aiT32[TRANSFORM_INVERSE][24][0]*src[ 24*line ];
+    EEEO[1] = g_aiT32[TRANSFORM_INVERSE][8][1]*src[ 8*line ] + g_aiT32[TRANSFORM_INVERSE][24][1]*src[ 24*line ];
+    EEEE[0] = g_aiT32[TRANSFORM_INVERSE][0][0]*src[ 0      ] + g_aiT32[TRANSFORM_INVERSE][16][0]*src[ 16*line ];
+    EEEE[1] = g_aiT32[TRANSFORM_INVERSE][0][1]*src[ 0      ] + g_aiT32[TRANSFORM_INVERSE][16][1]*src[ 16*line ];
 
     /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
@@ -757,19 +827,19 @@
     EEE[3] = EEEE[0] - EEEO[0];
     EEE[1] = EEEE[1] + EEEO[1];
-    EEE[2] = EEEE[1] - EEEO[1];    
+    EEE[2] = EEEE[1] - EEEO[1];
     for (k=0;k<4;k++)
     {
       EE[k] = EEE[k] + EEO[k];
       EE[k+4] = EEE[3-k] - EEO[3-k];
-    }    
+    }
     for (k=0;k<8;k++)
     {
       E[k] = EE[k] + EO[k];
       E[k+8] = EE[7-k] - EO[7-k];
-    }    
+    }
     for (k=0;k<16;k++)
     {
-      dst[k]    = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
-      dst[k+16] = Clip3( -32768, 32767, (E[15-k] - O[15-k] + add)>>shift );
+      dst[k]    = Clip3( outputMinimum, outputMaximum, (E[k] + O[k] + add)>>shift );
+      dst[k+16] = Clip3( outputMinimum, outputMaximum, (E[15-k] - O[15-k] + add)>>shift );
     }
     src ++;
@@ -779,106 +849,166 @@
 
 /** MxN forward transform (2D)
-*  \param block input data (residual)
-*  \param coeff output data (transform coefficients)
-*  \param iWidth input data (width of transform)
-*  \param iHeight input data (height of transform)
+*  \param bitDepth              [in]  bit depth
+*  \param block                 [in]  residual block
+*  \param coeff                 [out] transform coefficients
+*  \param iWidth                [in]  width of transform
+*  \param iHeight               [in]  height of transform
+*  \param useDST                [in]
+*  \param maxLog2TrDynamicRange [in]
+
 */
-void xTrMxN(Int bitDepth, Short *block,Short *coeff, Int iWidth, Int iHeight, UInt uiMode)
-{
-  Int shift_1st = g_aucConvertToBit[iWidth]  + 1 + bitDepth-8; // log2(iWidth) - 1 + g_bitDepth - 8
-  Int shift_2nd = g_aucConvertToBit[iHeight]  + 8;                   // log2(iHeight) + 6
-
-  Short tmp[ 64 * 64 ];
-
-  if( iWidth == 4 && iHeight == 4)
-  {
-    if (uiMode != REG_DCT)
-    {
-      fastForwardDst(block,tmp,shift_1st); // Forward DST BY FAST ALGORITHM, block input, tmp output
-      fastForwardDst(tmp,coeff,shift_2nd); // Forward DST BY FAST ALGORITHM, tmp input, coeff output
-    }
-    else
-    {
-      partialButterfly4(block, tmp, shift_1st, iHeight);
-      partialButterfly4(tmp, coeff, shift_2nd, iWidth);
-    }
-
-  }
-  else if( iWidth == 8 && iHeight == 8)
-  {
-    partialButterfly8( block, tmp, shift_1st, iHeight );
-    partialButterfly8( tmp, coeff, shift_2nd, iWidth );
-  }
-  else if( iWidth == 16 && iHeight == 16)
-  {
-    partialButterfly16( block, tmp, shift_1st, iHeight );
-    partialButterfly16( tmp, coeff, shift_2nd, iWidth );
-  }
-  else if( iWidth == 32 && iHeight == 32)
-  {
-    partialButterfly32( block, tmp, shift_1st, iHeight );
-    partialButterfly32( tmp, coeff, shift_2nd, iWidth );
-  }
-}
+Void xTrMxN(Int bitDepth, TCoeff *block, TCoeff *coeff, Int iWidth, Int iHeight, Bool useDST, const Int maxLog2TrDynamicRange)
+{
+  const Int TRANSFORM_MATRIX_SHIFT = g_transformMatrixShift[TRANSFORM_FORWARD];
+
+  const Int shift_1st = ((g_aucConvertToBit[iWidth] + 2) +  bitDepth + TRANSFORM_MATRIX_SHIFT) - maxLog2TrDynamicRange;
+  const Int shift_2nd = (g_aucConvertToBit[iHeight] + 2) + TRANSFORM_MATRIX_SHIFT;
+
+  assert(shift_1st >= 0);
+  assert(shift_2nd >= 0);
+
+  TCoeff tmp[ MAX_TU_SIZE * MAX_TU_SIZE ];
+
+  switch (iWidth)
+  {
+    case 4:
+      {
+        if ((iHeight == 4) && useDST)    // Check for DCT or DST
+        {
+           fastForwardDst( block, tmp, shift_1st );
+        }
+        else
+        {
+          partialButterfly4 ( block, tmp, shift_1st, iHeight );
+        }
+      }
+      break;
+
+    case 8:     partialButterfly8 ( block, tmp, shift_1st, iHeight );  break;
+    case 16:    partialButterfly16( block, tmp, shift_1st, iHeight );  break;
+    case 32:    partialButterfly32( block, tmp, shift_1st, iHeight );  break;
+    default:
+      assert(0); exit (1); break;
+  }
+
+  switch (iHeight)
+  {
+    case 4:
+      {
+        if ((iWidth == 4) && useDST)    // Check for DCT or DST
+        {
+          fastForwardDst( tmp, coeff, shift_2nd );
+        }
+        else
+        {
+          partialButterfly4 ( tmp, coeff, shift_2nd, iWidth );
+        }
+      }
+      break;
+
+    case 8:     partialButterfly8 ( tmp, coeff, shift_2nd, iWidth );    break;
+    case 16:    partialButterfly16( tmp, coeff, shift_2nd, iWidth );    break;
+    case 32:    partialButterfly32( tmp, coeff, shift_2nd, iWidth );    break;
+    default:
+      assert(0); exit (1); break;
+  }
+}
+
+
 /** MxN inverse transform (2D)
-*  \param coeff input data (transform coefficients)
-*  \param block output data (residual)
-*  \param iWidth input data (width of transform)
-*  \param iHeight input data (height of transform)
+*  \param bitDepth              [in]  bit depth
+*  \param coeff                 [in]  transform coefficients
+*  \param block                 [out] residual block
+*  \param iWidth                [in]  width of transform
+*  \param iHeight               [in]  height of transform
+*  \param useDST                [in]
+*  \param maxLog2TrDynamicRange [in]
 */
-void xITrMxN(Int bitDepth, Short *coeff,Short *block, Int iWidth, Int iHeight, UInt uiMode)
-{
-  Int shift_1st = SHIFT_INV_1ST;
-  Int shift_2nd = SHIFT_INV_2ND - (bitDepth-8);
-
-  Short tmp[ 64*64];
-  if( iWidth == 4 && iHeight == 4)
-  {
-    if (uiMode != REG_DCT)
-    {
-      fastInverseDst(coeff,tmp,shift_1st);    // Inverse DST by FAST Algorithm, coeff input, tmp output
-      fastInverseDst(tmp,block,shift_2nd); // Inverse DST by FAST Algorithm, tmp input, coeff output
-    }
-    else
-    {
-      partialButterflyInverse4(coeff,tmp,shift_1st,iWidth);
-      partialButterflyInverse4(tmp,block,shift_2nd,iHeight);
-    }
-  }
-  else if( iWidth == 8 && iHeight == 8)
-  {
-    partialButterflyInverse8(coeff,tmp,shift_1st,iWidth);
-    partialButterflyInverse8(tmp,block,shift_2nd,iHeight);
-  }
-  else if( iWidth == 16 && iHeight == 16)
-  {
-    partialButterflyInverse16(coeff,tmp,shift_1st,iWidth);
-    partialButterflyInverse16(tmp,block,shift_2nd,iHeight);
-  }
-  else if( iWidth == 32 && iHeight == 32)
-  {
-    partialButterflyInverse32(coeff,tmp,shift_1st,iWidth);
-    partialButterflyInverse32(tmp,block,shift_2nd,iHeight);
-  }
-}
-
-#endif //MATRIX_MULT
-
-// To minimize the distortion only. No rate is considered. 
-Void TComTrQuant::signBitHidingHDQ( TCoeff* pQCoef, TCoeff* pCoef, UInt const *scan, Int* deltaU, Int width, Int height )
-{
+Void xITrMxN(Int bitDepth, TCoeff *coeff, TCoeff *block, Int iWidth, Int iHeight, Bool useDST, const Int maxLog2TrDynamicRange)
+{
+  const Int TRANSFORM_MATRIX_SHIFT = g_transformMatrixShift[TRANSFORM_INVERSE];
+
+  Int shift_1st = TRANSFORM_MATRIX_SHIFT + 1; //1 has been added to shift_1st at the expense of shift_2nd
+  Int shift_2nd = (TRANSFORM_MATRIX_SHIFT + maxLog2TrDynamicRange - 1) - bitDepth;
+  const TCoeff clipMinimum = -(1 << maxLog2TrDynamicRange);
+  const TCoeff clipMaximum =  (1 << maxLog2TrDynamicRange) - 1;
+
+  assert(shift_1st >= 0);
+  assert(shift_2nd >= 0);
+
+  TCoeff tmp[MAX_TU_SIZE * MAX_TU_SIZE];
+
+  switch (iHeight)
+  {
+    case 4:
+      {
+        if ((iWidth == 4) && useDST)    // Check for DCT or DST
+        {
+          fastInverseDst( coeff, tmp, shift_1st, clipMinimum, clipMaximum);
+        }
+        else
+        {
+          partialButterflyInverse4 ( coeff, tmp, shift_1st, iWidth, clipMinimum, clipMaximum);
+        }
+      }
+      break;
+
+    case  8: partialButterflyInverse8 ( coeff, tmp, shift_1st, iWidth, clipMinimum, clipMaximum); break;
+    case 16: partialButterflyInverse16( coeff, tmp, shift_1st, iWidth, clipMinimum, clipMaximum); break;
+    case 32: partialButterflyInverse32( coeff, tmp, shift_1st, iWidth, clipMinimum, clipMaximum); break;
+
+    default:
+      assert(0); exit (1); break;
+  }
+
+  switch (iWidth)
+  {
+    // Clipping here is not in the standard, but is used to protect the "Pel" data type into which the inverse-transformed samples will be copied
+    case 4:
+      {
+        if ((iHeight == 4) && useDST)    // Check for DCT or DST
+        {
+          fastInverseDst( tmp, block, shift_2nd, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max() );
+        }
+        else
+        {
+          partialButterflyInverse4 ( tmp, block, shift_2nd, iHeight, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max());
+        }
+      }
+      break;
+
+    case  8: partialButterflyInverse8 ( tmp, block, shift_2nd, iHeight, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max()); break;
+    case 16: partialButterflyInverse16( tmp, block, shift_2nd, iHeight, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max()); break;
+    case 32: partialButterflyInverse32( tmp, block, shift_2nd, iHeight, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max()); break;
+
+    default:
+      assert(0); exit (1); break;
+  }
+}
+
+
+// To minimize the distortion only. No rate is considered.
+Void TComTrQuant::signBitHidingHDQ( TCoeff* pQCoef, TCoeff* pCoef, TCoeff* deltaU, const TUEntropyCodingParameters &codingParameters, const Int maxLog2TrDynamicRange )
+{
+  const UInt width     = codingParameters.widthInGroups  << MLS_CG_LOG2_WIDTH;
+  const UInt height    = codingParameters.heightInGroups << MLS_CG_LOG2_HEIGHT;
+  const UInt groupSize = 1 << MLS_CG_SIZE;
+
+  const TCoeff entropyCodingMinimum = -(1 << maxLog2TrDynamicRange);
+  const TCoeff entropyCodingMaximum =  (1 << maxLog2TrDynamicRange) - 1;
+
   Int lastCG = -1;
   Int absSum = 0 ;
   Int n ;
 
-  for( Int subSet = (width*height-1) >> LOG2_SCAN_SET_SIZE; subSet >= 0; subSet-- )
-  {
-    Int  subPos     = subSet << LOG2_SCAN_SET_SIZE;
-    Int  firstNZPosInCG=SCAN_SET_SIZE , lastNZPosInCG=-1 ;
+  for( Int subSet = (width*height-1) >> MLS_CG_SIZE; subSet >= 0; subSet-- )
+  {
+    Int  subPos = subSet << MLS_CG_SIZE;
+    Int  firstNZPosInCG=groupSize , lastNZPosInCG=-1 ;
     absSum = 0 ;
 
-    for(n = SCAN_SET_SIZE-1; n >= 0; --n )
-    {
-      if( pQCoef[ scan[ n + subPos ]] )
+    for(n = groupSize-1; n >= 0; --n )
+    {
+      if( pQCoef[ codingParameters.scan[ n + subPos ]] )
       {
         lastNZPosInCG = n;
@@ -887,7 +1017,7 @@
     }
 
-    for(n = 0; n <SCAN_SET_SIZE; n++ )
-    {
-      if( pQCoef[ scan[ n + subPos ]] )
+    for(n = 0; n <groupSize; n++ )
+    {
+      if( pQCoef[ codingParameters.scan[ n + subPos ]] )
       {
         firstNZPosInCG = n;
@@ -898,39 +1028,41 @@
     for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
     {
-      absSum += pQCoef[ scan[ n + subPos ]];
-    }
-
-    if(lastNZPosInCG>=0 && lastCG==-1) 
-    {
-      lastCG = 1 ; 
+      absSum += Int(pQCoef[ codingParameters.scan[ n + subPos ]]);
+    }
+
+    if(lastNZPosInCG>=0 && lastCG==-1)
+    {
+      lastCG = 1 ;
     }
 
     if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
     {
-      UInt signbit = (pQCoef[scan[subPos+firstNZPosInCG]]>0?0:1) ;
+      UInt signbit = (pQCoef[codingParameters.scan[subPos+firstNZPosInCG]]>0?0:1) ;
       if( signbit!=(absSum&0x1) )  //compare signbit with sum_parity
       {
-        Int minCostInc = MAX_INT,  minPos =-1, finalChange=0, curCost=MAX_INT, curChange=0;
-        
-        for( n = (lastCG==1?lastNZPosInCG:SCAN_SET_SIZE-1) ; n >= 0; --n )
-        {
-          UInt blkPos   = scan[ n+subPos ];
+        TCoeff curCost    = std::numeric_limits<TCoeff>::max();
+        TCoeff minCostInc = std::numeric_limits<TCoeff>::max();
+        Int minPos =-1, finalChange=0, curChange=0;
+
+        for( n = (lastCG==1?lastNZPosInCG:groupSize-1) ; n >= 0; --n )
+        {
+          UInt blkPos   = codingParameters.scan[ n+subPos ];
           if(pQCoef[ blkPos ] != 0 )
           {
             if(deltaU[blkPos]>0)
             {
-              curCost = - deltaU[blkPos]; 
+              curCost = - deltaU[blkPos];
               curChange=1 ;
             }
-            else 
+            else
             {
               //curChange =-1;
               if(n==firstNZPosInCG && abs(pQCoef[blkPos])==1)
               {
-                curCost=MAX_INT ; 
+                curCost = std::numeric_limits<TCoeff>::max();
               }
               else
               {
-                curCost = deltaU[blkPos]; 
+                curCost = deltaU[blkPos];
                 curChange =-1;
               }
@@ -944,8 +1076,8 @@
               if(thisSignBit != signbit )
               {
-                curCost = MAX_INT;
+                curCost = std::numeric_limits<TCoeff>::max();
               }
               else
-              { 
+              {
                 curCost = - (deltaU[blkPos])  ;
                 curChange = 1 ;
@@ -967,5 +1099,5 @@
         } //CG loop
 
-        if(pQCoef[minPos] == 32767 || pQCoef[minPos] == -32768)
+        if(pQCoef[minPos] == entropyCodingMaximum || pQCoef[minPos] == entropyCodingMinimum)
         {
           finalChange = -1;
@@ -974,13 +1106,13 @@
         if(pCoef[minPos]>=0)
         {
-          pQCoef[minPos] += finalChange ; 
-        }
-        else 
-        { 
+          pQCoef[minPos] += finalChange ;
+        }
+        else
+        {
           pQCoef[minPos] -= finalChange ;
-        }  
+        }
       } // Hide
     }
-    if(lastCG==1) 
+    if(lastCG==1)
     {
       lastCG=0 ;
@@ -991,179 +1123,269 @@
 }
 
-Void TComTrQuant::xQuant( TComDataCU* pcCU, 
-                          Int*        pSrc, 
-                          TCoeff*     pDes, 
+
+Void TComTrQuant::xQuant(       TComTU       &rTu,
+                                TCoeff      * pSrc,
+                                TCoeff      * pDes,
 #if ADAPTIVE_QP_SELECTION
-                          Int*&       pArlDes,
-#endif
-                          Int         iWidth, 
-                          Int         iHeight, 
-                          UInt&       uiAcSum, 
-                          TextType    eTType, 
-                          UInt        uiAbsPartIdx )
-{
-  Int*   piCoef    = pSrc;
+                                TCoeff      *pArlDes,
+#endif
+                                TCoeff       &uiAbsSum,
+                          const ComponentID   compID,
+                          const QpParam      &cQP )
+{
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt uiWidth        = rect.width;
+  const UInt uiHeight       = rect.height;
+  TComDataCU* pcCU          = rTu.getCU();
+  const UInt uiAbsPartIdx   = rTu.GetAbsPartIdxTU();
+  const Int channelBitDepth = pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+
+  TCoeff* piCoef    = pSrc;
   TCoeff* piQCoef   = pDes;
 #if ADAPTIVE_QP_SELECTION
-  Int*   piArlCCoef = pArlDes;
-#endif
-  Int   iAdd = 0;
- 
-  Bool useRDOQ = pcCU->getTransformSkip(uiAbsPartIdx,eTType) ? m_useRDOQTS:m_useRDOQ;
-  if ( useRDOQ && (eTType == TEXT_LUMA || RDOQ_CHROMA))
-  {
+  TCoeff* piArlCCoef = pArlDes;
+#endif
+
+  const Bool useTransformSkip      = pcCU->getTransformSkip(uiAbsPartIdx, compID);
+  const Int  maxLog2TrDynamicRange = pcCU->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(compID));
+
+  Bool useRDOQ = useTransformSkip ? m_useRDOQTS : m_useRDOQ;
+  if ( useRDOQ && (isLuma(compID) || RDOQ_CHROMA) )
+  {
+#if T0196_SELECTIVE_RDOQ
+    if ( !m_useSelectiveRDOQ || xNeedRDOQ( rTu, piCoef, compID, cQP ) )
+    {
+#endif
 #if ADAPTIVE_QP_SELECTION
-    xRateDistOptQuant( pcCU, piCoef, pDes, pArlDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+      xRateDistOptQuant( rTu, piCoef, pDes, pArlDes, uiAbsSum, compID, cQP );
 #else
-    xRateDistOptQuant( pcCU, piCoef, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+      xRateDistOptQuant( rTu, piCoef, pDes, uiAbsSum, compID, cQP );
+#endif
+#if T0196_SELECTIVE_RDOQ
+    }
+    else
+    {
+      memset( pDes, 0, sizeof( TCoeff ) * uiWidth *uiHeight );
+      uiAbsSum = 0;
+    }
 #endif
   }
   else
   {
-    const UInt   log2BlockSize   = g_aucConvertToBit[ iWidth ] + 2;
-
-    UInt scanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, iWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
-    const UInt *scan = g_auiSigLastScan[ scanIdx ][ log2BlockSize - 1 ];
-    
-    Int deltaU[32*32] ;
+    TUEntropyCodingParameters codingParameters;
+    getTUEntropyCodingParameters(codingParameters, rTu, compID);
+
+    const TCoeff entropyCodingMinimum = -(1 << maxLog2TrDynamicRange);
+    const TCoeff entropyCodingMaximum =  (1 << maxLog2TrDynamicRange) - 1;
+
+    TCoeff deltaU[MAX_TU_SIZE * MAX_TU_SIZE];
+
+    const UInt uiLog2TrSize = rTu.GetEquivalentLog2TrSize(compID);
+
+    Int scalingListType = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+    assert(scalingListType < SCALING_LIST_NUM);
+    Int *piQuantCoeff = getQuantCoeff(scalingListType, cQP.rem, uiLog2TrSize-2);
+
+    const Bool enableScalingLists             = getUseScalingList(uiWidth, uiHeight, (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0));
+    const Int  defaultQuantisationCoefficient = g_quantScales[cQP.rem];
+
+    /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be
+     * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the
+     * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller)
+     * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result
+     */
+
+    // Represents scaling through forward transform
+    Int iTransformShift = getTransformShift(channelBitDepth, uiLog2TrSize, maxLog2TrDynamicRange);
+    if (useTransformSkip && pcCU->getSlice()->getSPS()->getSpsRangeExtension().getExtendedPrecisionProcessingFlag())
+    {
+      iTransformShift = std::max<Int>(0, iTransformShift);
+    }
+
+    const Int iQBits = QUANT_SHIFT + cQP.per + iTransformShift;
+    // QBits will be OK for any internal bit depth as the reduction in transform shift is balanced by an increase in Qp_per due to QpBDOffset
 
 #if ADAPTIVE_QP_SELECTION
-    QpParam cQpBase;
-    Int iQpBase = pcCU->getSlice()->getSliceQpBase();
-
-    Int qpScaled;
-    Int qpBDOffset = (eTType == TEXT_LUMA)? pcCU->getSlice()->getSPS()->getQpBDOffsetY() : pcCU->getSlice()->getSPS()->getQpBDOffsetC();
-
-    if(eTType == TEXT_LUMA)
-    {
-      qpScaled = iQpBase + qpBDOffset;
-    }
-    else
-    {
-      Int chromaQPOffset;
-      if(eTType == TEXT_CHROMA_U)
-      {
-        chromaQPOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
-      }
-      else
-      {
-        chromaQPOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
-      }
-      iQpBase = iQpBase + chromaQPOffset;
-      
-      qpScaled = Clip3( -qpBDOffset, 57, iQpBase);
-
-      if(qpScaled < 0)
-      {
-        qpScaled = qpScaled +  qpBDOffset;
-      }
-      else
-      {
-        qpScaled = g_aucChromaScale[ qpScaled ] + qpBDOffset;
-      }
-    }
-    cQpBase.setQpParam(qpScaled);
-#endif
-
-    UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
-    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
-    assert(scalingListType < SCALING_LIST_NUM);
-    Int *piQuantCoeff = 0;
-    piQuantCoeff = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2);
-
-    UInt uiBitDepth = eTType == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
-    Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+    Int iQBitsC = MAX_INT;
+    Int iAddC   = MAX_INT;
+
+    if (m_bUseAdaptQpSelect)
+    {
+      iQBitsC = iQBits - ARL_C_PRECISION;
+      iAddC   = 1 << (iQBitsC-1);
+    }
+#endif
+
+    const Int iAdd   = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
+    const Int qBits8 = iQBits - 8;
+
+    for( Int uiBlockPos = 0; uiBlockPos < uiWidth*uiHeight; uiBlockPos++ )
+    {
+      const TCoeff iLevel   = piCoef[uiBlockPos];
+      const TCoeff iSign    = (iLevel < 0 ? -1: 1);
+
+      const Int64  tmpLevel = (Int64)abs(iLevel) * (enableScalingLists ? piQuantCoeff[uiBlockPos] : defaultQuantisationCoefficient);
 
 #if ADAPTIVE_QP_SELECTION
-    Int iQBits = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift;
-    iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
-    Int iQBitsC = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift - ARL_C_PRECISION;  
-    Int iAddC   = 1 << (iQBitsC-1);
-#else
-    Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
-    iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
-#endif
-
-    Int qBits8 = iQBits-8;
-    for( Int n = 0; n < iWidth*iHeight; n++ )
-    {
-      Int iLevel;
-      Int  iSign;
-      UInt uiBlockPos = n;
-      iLevel  = piCoef[uiBlockPos];
-      iSign   = (iLevel < 0 ? -1: 1);      
-
-#if ADAPTIVE_QP_SELECTION
-      Int64 tmpLevel = (Int64)abs(iLevel) * piQuantCoeff[uiBlockPos];
       if( m_bUseAdaptQpSelect )
       {
-        piArlCCoef[uiBlockPos] = (Int)((tmpLevel + iAddC ) >> iQBitsC);
-      }
-      iLevel = (Int)((tmpLevel + iAdd ) >> iQBits);
-      deltaU[uiBlockPos] = (Int)((tmpLevel - (iLevel<<iQBits) )>> qBits8);
-#else
-      iLevel = ((Int64)abs(iLevel) * piQuantCoeff[uiBlockPos] + iAdd ) >> iQBits;
-      deltaU[uiBlockPos] = (Int)( ((Int64)abs(piCoef[uiBlockPos]) * piQuantCoeff[uiBlockPos] - (iLevel<<iQBits) )>> qBits8 );
-#endif
-      uiAcSum += iLevel;
-      iLevel *= iSign;        
-      piQCoef[uiBlockPos] = Clip3( -32768, 32767, iLevel );
+        piArlCCoef[uiBlockPos] = (TCoeff)((tmpLevel + iAddC ) >> iQBitsC);
+      }
+#endif
+
+      const TCoeff quantisedMagnitude = TCoeff((tmpLevel + iAdd ) >> iQBits);
+      deltaU[uiBlockPos] = (TCoeff)((tmpLevel - (quantisedMagnitude<<iQBits) )>> qBits8);
+
+      uiAbsSum += quantisedMagnitude;
+      const TCoeff quantisedCoefficient = quantisedMagnitude * iSign;
+
+      piQCoef[uiBlockPos] = Clip3<TCoeff>( entropyCodingMinimum, entropyCodingMaximum, quantisedCoefficient );
     } // for n
+
     if( pcCU->getSlice()->getPPS()->getSignHideFlag() )
     {
-      if(uiAcSum>=2)
-      {
-        signBitHidingHDQ( piQCoef, piCoef, scan, deltaU, iWidth, iHeight ) ;
+      if(uiAbsSum >= 2) //this prevents TUs with only one coefficient of value 1 from being tested
+      {
+        signBitHidingHDQ( piQCoef, piCoef, deltaU, codingParameters, maxLog2TrDynamicRange ) ;
       }
     }
   } //if RDOQ
   //return;
-
-}
-
-Void TComTrQuant::xDeQuant(Int bitDepth, const TCoeff* pSrc, Int* pDes, Int iWidth, Int iHeight, Int scalingListType )
-{
-  
-  const TCoeff* piQCoef   = pSrc;
-  Int*   piCoef    = pDes;
-  
-  if ( iWidth > (Int)m_uiMaxTrSize )
-  {
-    iWidth  = m_uiMaxTrSize;
-    iHeight = m_uiMaxTrSize;
-  }
-  
-  Int iShift,iAdd,iCoeffQ;
-  UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
-
-  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - bitDepth - uiLog2TrSize;
-
-  iShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - iTransformShift;
-
-  TCoeff clipQCoef;
-
-  if(getUseScalingList())
-  {
-    iShift += 4;
-    Int *piDequantCoef = getDequantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2);
-
-    if(iShift > m_cQP.m_iPer)
-    {
-      iAdd = 1 << (iShift - m_cQP.m_iPer - 1);
-      
-      for( Int n = 0; n < iWidth*iHeight; n++ )
-      {
-        clipQCoef = Clip3( -32768, 32767, piQCoef[n] );
-        iCoeffQ = ((clipQCoef * piDequantCoef[n]) + iAdd ) >> (iShift -  m_cQP.m_iPer);
-        piCoef[n] = Clip3(-32768,32767,iCoeffQ);
+}
+
+#if T0196_SELECTIVE_RDOQ
+Bool TComTrQuant::xNeedRDOQ( TComTU &rTu, TCoeff * pSrc, const ComponentID compID, const QpParam &cQP )
+{
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt uiWidth        = rect.width;
+  const UInt uiHeight       = rect.height;
+  TComDataCU* pcCU          = rTu.getCU();
+  const UInt uiAbsPartIdx   = rTu.GetAbsPartIdxTU();
+  const Int channelBitDepth = pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+
+  TCoeff* piCoef    = pSrc;
+
+  const Bool useTransformSkip      = pcCU->getTransformSkip(uiAbsPartIdx, compID);
+  const Int  maxLog2TrDynamicRange = pcCU->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(compID));
+
+  const UInt uiLog2TrSize = rTu.GetEquivalentLog2TrSize(compID);
+
+  Int scalingListType = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+  assert(scalingListType < SCALING_LIST_NUM);
+  Int *piQuantCoeff = getQuantCoeff(scalingListType, cQP.rem, uiLog2TrSize-2);
+
+  const Bool enableScalingLists             = getUseScalingList(uiWidth, uiHeight, (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0));
+  const Int  defaultQuantisationCoefficient = g_quantScales[cQP.rem];
+
+  /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be
+    * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the
+    * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller)
+    * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result
+    */
+
+  // Represents scaling through forward transform
+  Int iTransformShift = getTransformShift(channelBitDepth, uiLog2TrSize, maxLog2TrDynamicRange);
+  if (useTransformSkip && pcCU->getSlice()->getSPS()->getSpsRangeExtension().getExtendedPrecisionProcessingFlag())
+  {
+    iTransformShift = std::max<Int>(0, iTransformShift);
+  }
+
+  const Int iQBits = QUANT_SHIFT + cQP.per + iTransformShift;
+  // QBits will be OK for any internal bit depth as the reduction in transform shift is balanced by an increase in Qp_per due to QpBDOffset
+
+  // iAdd is different from the iAdd used in normal quantization
+  const Int iAdd   = (compID == COMPONENT_Y ? 171 : 256) << (iQBits-9);
+
+  for( Int uiBlockPos = 0; uiBlockPos < uiWidth*uiHeight; uiBlockPos++ )
+  {
+    const TCoeff iLevel   = piCoef[uiBlockPos];
+    const Int64  tmpLevel = (Int64)abs(iLevel) * (enableScalingLists ? piQuantCoeff[uiBlockPos] : defaultQuantisationCoefficient);
+    const TCoeff quantisedMagnitude = TCoeff((tmpLevel + iAdd ) >> iQBits);
+
+    if ( quantisedMagnitude != 0 )
+    {
+      return true;
+    }
+  } // for n
+  return false;
+}
+#endif
+
+Void TComTrQuant::xDeQuant(       TComTU        &rTu,
+                            const TCoeff       * pSrc,
+                                  TCoeff       * pDes,
+                            const ComponentID    compID,
+                            const QpParam       &cQP )
+{
+  assert(compID<MAX_NUM_COMPONENT);
+
+        TComDataCU          *pcCU               = rTu.getCU();
+  const UInt                 uiAbsPartIdx       = rTu.GetAbsPartIdxTU();
+  const TComRectangle       &rect               = rTu.getRect(compID);
+  const UInt                 uiWidth            = rect.width;
+  const UInt                 uiHeight           = rect.height;
+  const TCoeff        *const piQCoef            = pSrc;
+        TCoeff        *const piCoef             = pDes;
+  const UInt                 uiLog2TrSize       = rTu.GetEquivalentLog2TrSize(compID);
+  const UInt                 numSamplesInBlock  = uiWidth*uiHeight;
+  const Int                  maxLog2TrDynamicRange  = pcCU->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(compID));
+  const TCoeff               transformMinimum   = -(1 << maxLog2TrDynamicRange);
+  const TCoeff               transformMaximum   =  (1 << maxLog2TrDynamicRange) - 1;
+  const Bool                 enableScalingLists = getUseScalingList(uiWidth, uiHeight, (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0));
+  const Int                  scalingListType    = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+#if O0043_BEST_EFFORT_DECODING
+  const Int                  channelBitDepth    = pcCU->getSlice()->getSPS()->getStreamBitDepth(toChannelType(compID));
+#else
+  const Int                  channelBitDepth    = pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+#endif
+
+  assert (scalingListType < SCALING_LIST_NUM);
+  assert ( uiWidth <= m_uiMaxTrSize );
+
+  // Represents scaling through forward transform
+  const Bool bClipTransformShiftTo0 = (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0) && pcCU->getSlice()->getSPS()->getSpsRangeExtension().getExtendedPrecisionProcessingFlag();
+  const Int  originalTransformShift = getTransformShift(channelBitDepth, uiLog2TrSize, maxLog2TrDynamicRange);
+  const Int  iTransformShift        = bClipTransformShiftTo0 ? std::max<Int>(0, originalTransformShift) : originalTransformShift;
+
+  const Int QP_per = cQP.per;
+  const Int QP_rem = cQP.rem;
+
+  const Int rightShift = (IQUANT_SHIFT - (iTransformShift + QP_per)) + (enableScalingLists ? LOG2_SCALING_LIST_NEUTRAL_VALUE : 0);
+
+  if(enableScalingLists)
+  {
+    //from the dequantisation equation:
+    //iCoeffQ                         = ((Intermediate_Int(clipQCoef) * piDequantCoef[deQuantIdx]) + iAdd ) >> rightShift
+    //(sizeof(Intermediate_Int) * 8)  =              inputBitDepth    +    dequantCoefBits                   - rightShift
+    const UInt             dequantCoefBits     = 1 + IQUANT_SHIFT + SCALING_LIST_BITS;
+    const UInt             targetInputBitDepth = std::min<UInt>((maxLog2TrDynamicRange + 1), (((sizeof(Intermediate_Int) * 8) + rightShift) - dequantCoefBits));
+
+    const Intermediate_Int inputMinimum        = -(1 << (targetInputBitDepth - 1));
+    const Intermediate_Int inputMaximum        =  (1 << (targetInputBitDepth - 1)) - 1;
+
+    Int *piDequantCoef = getDequantCoeff(scalingListType,QP_rem,uiLog2TrSize-2);
+
+    if(rightShift > 0)
+    {
+      const Intermediate_Int iAdd = 1 << (rightShift - 1);
+
+      for( Int n = 0; n < numSamplesInBlock; n++ )
+      {
+        const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, piQCoef[n]));
+        const Intermediate_Int iCoeffQ   = ((Intermediate_Int(clipQCoef) * piDequantCoef[n]) + iAdd ) >> rightShift;
+
+        piCoef[n] = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
       }
     }
     else
     {
-      for( Int n = 0; n < iWidth*iHeight; n++ )
-      {
-        clipQCoef = Clip3( -32768, 32767, piQCoef[n] );
-        iCoeffQ   = Clip3( -32768, 32767, clipQCoef * piDequantCoef[n] ); // Clip to avoid possible overflow in following shift left operation
-        piCoef[n] = Clip3( -32768, 32767, iCoeffQ << ( m_cQP.m_iPer - iShift ) );
+      const Int leftShift = -rightShift;
+
+      for( Int n = 0; n < numSamplesInBlock; n++ )
+      {
+        const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, piQCoef[n]));
+        const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * piDequantCoef[n]) << leftShift;
+
+        piCoef[n] = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
       }
     }
@@ -1171,22 +1393,52 @@
   else
   {
-    iAdd = 1 << (iShift-1);
-    Int scale = g_invQuantScales[m_cQP.m_iRem] << m_cQP.m_iPer;
-
-    for( Int n = 0; n < iWidth*iHeight; n++ )
-    {
-      clipQCoef = Clip3( -32768, 32767, piQCoef[n] );
-      iCoeffQ = ( clipQCoef * scale + iAdd ) >> iShift;
-      piCoef[n] = Clip3(-32768,32767,iCoeffQ);
-    }
-  }
-}
-
-Void TComTrQuant::init( UInt uiMaxTrSize,
-                       Bool bUseRDOQ,  
-                       Bool bUseRDOQTS,
-                       Bool bEnc, Bool useTransformSkipFast
+    const Int scale     =  g_invQuantScales[QP_rem];
+    const Int scaleBits =     (IQUANT_SHIFT + 1)   ;
+
+    //from the dequantisation equation:
+    //iCoeffQ                         = Intermediate_Int((Int64(clipQCoef) * scale + iAdd) >> rightShift);
+    //(sizeof(Intermediate_Int) * 8)  =                    inputBitDepth   + scaleBits      - rightShift
+    const UInt             targetInputBitDepth = std::min<UInt>((maxLog2TrDynamicRange + 1), (((sizeof(Intermediate_Int) * 8) + rightShift) - scaleBits));
+    const Intermediate_Int inputMinimum        = -(1 << (targetInputBitDepth - 1));
+    const Intermediate_Int inputMaximum        =  (1 << (targetInputBitDepth - 1)) - 1;
+
+    if (rightShift > 0)
+    {
+      const Intermediate_Int iAdd = 1 << (rightShift - 1);
+
+      for( Int n = 0; n < numSamplesInBlock; n++ )
+      {
+        const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, piQCoef[n]));
+        const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * scale + iAdd) >> rightShift;
+
+        piCoef[n] = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+      }
+    }
+    else
+    {
+      const Int leftShift = -rightShift;
+
+      for( Int n = 0; n < numSamplesInBlock; n++ )
+      {
+        const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, piQCoef[n]));
+        const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * scale) << leftShift;
+
+        piCoef[n] = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+      }
+    }
+  }
+}
+
+
+Void TComTrQuant::init(   UInt  uiMaxTrSize,
+                          Bool  bUseRDOQ,
+                          Bool  bUseRDOQTS,
+#if T0196_SELECTIVE_RDOQ
+                          Bool  useSelectiveRDOQ,
+#endif
+                          Bool  bEnc,
+                          Bool  useTransformSkipFast
 #if ADAPTIVE_QP_SELECTION
-                       , Bool bUseAdaptQpSelect
+                        , Bool bUseAdaptQpSelect
 #endif
                        )
@@ -1194,6 +1446,9 @@
   m_uiMaxTrSize  = uiMaxTrSize;
   m_bEnc         = bEnc;
-  m_useRDOQ     = bUseRDOQ;
-  m_useRDOQTS     = bUseRDOQTS;
+  m_useRDOQ      = bUseRDOQ;
+  m_useRDOQTS    = bUseRDOQTS;
+#if T0196_SELECTIVE_RDOQ
+  m_useSelectiveRDOQ = useSelectiveRDOQ;
+#endif
 #if ADAPTIVE_QP_SELECTION
   m_bUseAdaptQpSelect = bUseAdaptQpSelect;
@@ -1202,126 +1457,479 @@
 }
 
-Void TComTrQuant::transformNxN( TComDataCU* pcCU, 
-                               Pel*        pcResidual, 
-                               UInt        uiStride, 
-                               TCoeff*     rpcCoeff, 
+
+Void TComTrQuant::transformNxN(       TComTU        & rTu,
+                                const ComponentID     compID,
+                                      Pel          *  pcResidual,
+                                const UInt            uiStride,
+                                      TCoeff       *  rpcCoeff,
 #if ADAPTIVE_QP_SELECTION
-                               Int*&       rpcArlCoeff, 
-#endif
-                               UInt        uiWidth, 
-                               UInt        uiHeight, 
-                               UInt&       uiAbsSum, 
-                               TextType    eTType, 
-                               UInt        uiAbsPartIdx,
-                               Bool        useTransformSkip
-                               )
-{
-  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
-  {
-    uiAbsSum=0;
-    for (UInt k = 0; k<uiHeight; k++)
-    {
-      for (UInt j = 0; j<uiWidth; j++)
-      {
-        rpcCoeff[k*uiWidth+j]= pcResidual[k*uiStride+j];
-        uiAbsSum += abs(pcResidual[k*uiStride+j]);
-      }
-    }
+                                      TCoeff       *  pcArlCoeff,
+#endif
+                                      TCoeff        & uiAbsSum,
+                                const QpParam       & cQP
+                              )
+{
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt uiWidth        = rect.width;
+  const UInt uiHeight       = rect.height;
+  TComDataCU* pcCU          = rTu.getCU();
+  const UInt uiAbsPartIdx   = rTu.GetAbsPartIdxTU();
+  const UInt uiOrgTrDepth   = rTu.GetTransformDepthRel();
+
+  uiAbsSum=0;
+
+  RDPCMMode rdpcmMode = RDPCM_OFF;
+  rdpcmNxN( rTu, compID, pcResidual, uiStride, cQP, rpcCoeff, uiAbsSum, rdpcmMode );
+
+  if (rdpcmMode == RDPCM_OFF)
+  {
+    uiAbsSum = 0;
+    //transform and quantise
+    if(pcCU->getCUTransquantBypass(uiAbsPartIdx))
+    {
+      const Bool rotateResidual = rTu.isNonTransformedResidualRotated(compID);
+      const UInt uiSizeMinus1   = (uiWidth * uiHeight) - 1;
+
+      for (UInt y = 0, coefficientIndex = 0; y<uiHeight; y++)
+      {
+        for (UInt x = 0; x<uiWidth; x++, coefficientIndex++)
+        {
+          const Pel currentSample = pcResidual[(y * uiStride) + x];
+
+          rpcCoeff[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] = currentSample;
+          uiAbsSum += TCoeff(abs(currentSample));
+        }
+      }
+    }
+    else
+    {
+#if DEBUG_TRANSFORM_AND_QUANTISE
+      std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU at input to transform\n";
+      printBlock(pcResidual, uiWidth, uiHeight, uiStride);
+#endif
+
+      assert( (pcCU->getSlice()->getSPS()->getMaxTrSize() >= uiWidth) );
+
+      if(pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0)
+      {
+        xTransformSkip( pcResidual, uiStride, m_plTempCoeff, rTu, compID );
+      }
+      else
+      {
+        const Int channelBitDepth=pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+        xT( channelBitDepth, rTu.useDST(compID), pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight, pcCU->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(compID)) );
+      }
+
+#if DEBUG_TRANSFORM_AND_QUANTISE
+      std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU between transform and quantiser\n";
+      printBlock(m_plTempCoeff, uiWidth, uiHeight, uiWidth);
+#endif
+
+      xQuant( rTu, m_plTempCoeff, rpcCoeff,
+
+#if ADAPTIVE_QP_SELECTION
+              pcArlCoeff,
+#endif
+              uiAbsSum, compID, cQP );
+
+#if DEBUG_TRANSFORM_AND_QUANTISE
+      std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU at output of quantiser\n";
+      printBlock(rpcCoeff, uiWidth, uiHeight, uiWidth);
+#endif
+    }
+  }
+
+    //set the CBF
+  pcCU->setCbfPartRange((((uiAbsSum > 0) ? 1 : 0) << uiOrgTrDepth), compID, uiAbsPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+}
+
+
+Void TComTrQuant::invTransformNxN(      TComTU        &rTu,
+                                  const ComponentID    compID,
+                                        Pel          *pcResidual,
+                                  const UInt           uiStride,
+                                        TCoeff       * pcCoeff,
+                                  const QpParam       &cQP
+                                        DEBUG_STRING_FN_DECLAREP(psDebug))
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt uiWidth = rect.width;
+  const UInt uiHeight = rect.height;
+
+  if (uiWidth != uiHeight) //for intra, the TU will have been split above this level, so this condition won't be true, hence this only affects inter
+  {
+    //------------------------------------------------
+
+    //recurse deeper
+
+    TComTURecurse subTURecurse(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+    do
+    {
+      //------------------
+
+      const UInt lineOffset = subTURecurse.GetSectionNumber() * subTURecurse.getRect(compID).height;
+
+      Pel    *subTUResidual     = pcResidual + (lineOffset * uiStride);
+      TCoeff *subTUCoefficients = pcCoeff     + (lineOffset * subTURecurse.getRect(compID).width);
+
+      invTransformNxN(subTURecurse, compID, subTUResidual, uiStride, subTUCoefficients, cQP DEBUG_STRING_PASS_INTO(psDebug));
+
+      //------------------
+
+    } while (subTURecurse.nextSection(rTu));
+
+    //------------------------------------------------
+
     return;
   }
-  UInt uiMode;  //luma intra pred
-  if(eTType == TEXT_LUMA && pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
-  {
-    uiMode = pcCU->getLumaIntraDir( uiAbsPartIdx );
+
+#if DEBUG_STRING
+  if (psDebug)
+  {
+    std::stringstream ss(stringstream::out);
+    printBlockToStream(ss, (compID==0)?"###InvTran ip Ch0: " : ((compID==1)?"###InvTran ip Ch1: ":"###InvTran ip Ch2: "), pcCoeff, uiWidth, uiHeight, uiWidth);
+    DEBUG_STRING_APPEND((*psDebug), ss.str())
+  }
+#endif
+
+  if(pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    const Bool rotateResidual = rTu.isNonTransformedResidualRotated(compID);
+    const UInt uiSizeMinus1   = (uiWidth * uiHeight) - 1;
+
+    for (UInt y = 0, coefficientIndex = 0; y<uiHeight; y++)
+    {
+      for (UInt x = 0; x<uiWidth; x++, coefficientIndex++)
+      {
+        pcResidual[(y * uiStride) + x] = Pel(pcCoeff[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex]);
+      }
+    }
   }
   else
   {
-    uiMode = REG_DCT;
-  }
-  
+#if DEBUG_TRANSFORM_AND_QUANTISE
+    std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU at input to dequantiser\n";
+    printBlock(pcCoeff, uiWidth, uiHeight, uiWidth);
+#endif
+
+    xDeQuant(rTu, pcCoeff, m_plTempCoeff, compID, cQP);
+
+#if DEBUG_TRANSFORM_AND_QUANTISE
+    std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU between dequantiser and inverse-transform\n";
+    printBlock(m_plTempCoeff, uiWidth, uiHeight, uiWidth);
+#endif
+
+#if DEBUG_STRING
+    if (psDebug)
+    {
+      std::stringstream ss(stringstream::out);
+      printBlockToStream(ss, "###InvTran deq: ", m_plTempCoeff, uiWidth, uiHeight, uiWidth);
+      (*psDebug)+=ss.str();
+    }
+#endif
+
+    if(pcCU->getTransformSkip(uiAbsPartIdx, compID))
+    {
+      xITransformSkip( m_plTempCoeff, pcResidual, uiStride, rTu, compID );
+
+#if DEBUG_STRING
+      if (psDebug)
+      {
+        std::stringstream ss(stringstream::out);
+        printBlockToStream(ss, "###InvTran resi: ", pcResidual, uiWidth, uiHeight, uiStride);
+        (*psDebug)+=ss.str();
+        (*psDebug)+="(<- was a Transform-skipped block)\n";
+      }
+#endif
+    }
+    else
+    {
+#if O0043_BEST_EFFORT_DECODING
+      const Int channelBitDepth = pcCU->getSlice()->getSPS()->getStreamBitDepth(toChannelType(compID));
+#else
+      const Int channelBitDepth = pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+#endif
+      xIT( channelBitDepth, rTu.useDST(compID), m_plTempCoeff, pcResidual, uiStride, uiWidth, uiHeight, pcCU->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(compID)) );
+
+#if DEBUG_STRING
+      if (psDebug)
+      {
+        std::stringstream ss(stringstream::out);
+        printBlockToStream(ss, "###InvTran resi: ", pcResidual, uiWidth, uiHeight, uiStride);
+        (*psDebug)+=ss.str();
+        (*psDebug)+="(<- was a Transformed block)\n";
+      }
+#endif
+    }
+
+#if DEBUG_TRANSFORM_AND_QUANTISE
+    std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU at output of inverse-transform\n";
+    printBlock(pcResidual, uiWidth, uiHeight, uiStride);
+    g_debugCounter++;
+#endif
+  }
+
+  invRdpcmNxN( rTu, compID, pcResidual, uiStride );
+}
+
+Void TComTrQuant::invRecurTransformNxN( const ComponentID compID,
+                                        TComYuv *pResidual,
+                                        TComTU &rTu)
+{
+  if (!rTu.ProcessComponentSection(compID))
+  {
+    return;
+  }
+
+  TComDataCU* pcCU = rTu.getCU();
+  UInt absPartIdxTU = rTu.GetAbsPartIdxTU();
+  UInt uiTrMode=rTu.GetTransformDepthRel();
+  if( (pcCU->getCbf(absPartIdxTU, compID, uiTrMode) == 0) && (isLuma(compID) || !pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag()) )
+  {
+    return;
+  }
+
+  if( uiTrMode == pcCU->getTransformIdx( absPartIdxTU ) )
+  {
+    const TComRectangle &tuRect      = rTu.getRect(compID);
+    const Int            uiStride    = pResidual->getStride( compID );
+          Pel           *rpcResidual = pResidual->getAddr( compID );
+          UInt           uiAddr      = (tuRect.x0 + uiStride*tuRect.y0);
+          Pel           *pResi       = rpcResidual + uiAddr;
+          TCoeff        *pcCoeff     = pcCU->getCoeff(compID) + rTu.getCoefficientOffset(compID);
+
+    const QpParam cQP(*pcCU, compID);
+
+    if(pcCU->getCbf(absPartIdxTU, compID, uiTrMode) != 0)
+    {
+      DEBUG_STRING_NEW(sTemp)
+#if DEBUG_STRING
+      std::string *psDebug=((DebugOptionList::DebugString_InvTran.getInt()&(pcCU->isIntra(absPartIdxTU)?1:(pcCU->isInter(absPartIdxTU)?2:4)))!=0) ? &sTemp : 0;
+#endif
+
+      invTransformNxN( rTu, compID, pResi, uiStride, pcCoeff, cQP DEBUG_STRING_PASS_INTO(psDebug) );
+
+#if DEBUG_STRING
+      if (psDebug != 0)
+      {
+        std::cout << (*psDebug);
+      }
+#endif
+    }
+
+    if (isChroma(compID) && (pcCU->getCrossComponentPredictionAlpha(absPartIdxTU, compID) != 0))
+    {
+      const Pel *piResiLuma = pResidual->getAddr( COMPONENT_Y );
+      const Int  strideLuma = pResidual->getStride( COMPONENT_Y );
+      const Int  tuWidth    = rTu.getRect( compID ).width;
+      const Int  tuHeight   = rTu.getRect( compID ).height;
+
+      if(pcCU->getCbf(absPartIdxTU, COMPONENT_Y, uiTrMode) != 0)
+      {
+        pResi = rpcResidual + uiAddr;
+        const Pel *pResiLuma = piResiLuma + uiAddr;
+
+        crossComponentPrediction( rTu, compID, pResiLuma, pResi, pResi, tuWidth, tuHeight, strideLuma, uiStride, uiStride, true );
+      }
+    }
+  }
+  else
+  {
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      invRecurTransformNxN( compID, pResidual, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
+  }
+}
+
+Void TComTrQuant::applyForwardRDPCM( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride, const QpParam& cQP, TCoeff* pcCoeff, TCoeff &uiAbsSum, const RDPCMMode mode )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  const Bool bLossless      = pcCU->getCUTransquantBypass( uiAbsPartIdx );
+  const UInt uiWidth        = rTu.getRect(compID).width;
+  const UInt uiHeight       = rTu.getRect(compID).height;
+  const Bool rotateResidual = rTu.isNonTransformedResidualRotated(compID);
+  const UInt uiSizeMinus1   = (uiWidth * uiHeight) - 1;
+
+  UInt uiX = 0;
+  UInt uiY = 0;
+
+        UInt &majorAxis             = (mode == RDPCM_VER) ? uiX      : uiY;
+        UInt &minorAxis             = (mode == RDPCM_VER) ? uiY      : uiX;
+  const UInt  majorAxisLimit        = (mode == RDPCM_VER) ? uiWidth  : uiHeight;
+  const UInt  minorAxisLimit        = (mode == RDPCM_VER) ? uiHeight : uiWidth;
+
+  const Bool bUseHalfRoundingPoint  = (mode != RDPCM_OFF);
+
   uiAbsSum = 0;
-  assert( (pcCU->getSlice()->getSPS()->getMaxTrSize() >= uiWidth) );
-  Int bitDepth = eTType == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
-  if(useTransformSkip)
-  {
-    xTransformSkip(bitDepth, pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight );
-  }
-  else
-  {
-    xT(bitDepth, uiMode, pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight );
-  }
-  xQuant( pcCU, m_plTempCoeff, rpcCoeff,
-#if ADAPTIVE_QP_SELECTION
-       rpcArlCoeff,
-#endif
-       uiWidth, uiHeight, uiAbsSum, eTType, uiAbsPartIdx );
-}
-
-Void TComTrQuant::invtransformNxN( Bool transQuantBypass, TextType eText, UInt uiMode,Pel* rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight,  Int scalingListType, Bool useTransformSkip )
-{
-  if(transQuantBypass)
-  {
-    for (UInt k = 0; k<uiHeight; k++)
-    {
-      for (UInt j = 0; j<uiWidth; j++)
-      {
-        rpcResidual[k*uiStride+j] = pcCoeff[k*uiWidth+j];
-      }
-    } 
-    return;
-  }
-  Int bitDepth = eText == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
-  xDeQuant(bitDepth, pcCoeff, m_plTempCoeff, uiWidth, uiHeight, scalingListType);
-  if(useTransformSkip == true)
-  {
-    xITransformSkip(bitDepth, m_plTempCoeff, rpcResidual, uiStride, uiWidth, uiHeight );
-  }
-  else
-  {
-    xIT(bitDepth, uiMode, m_plTempCoeff, rpcResidual, uiStride, uiWidth, uiHeight );
-  }
-}
-
-Void TComTrQuant::invRecurTransformNxN( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eTxt, Pel* rpcResidual, UInt uiAddr, UInt uiStride, UInt uiWidth, UInt uiHeight, UInt uiMaxTrMode, UInt uiTrMode, TCoeff* rpcCoeff )
-{
-  if( !pcCU->getCbf(uiAbsPartIdx, eTxt, uiTrMode) )
-  {
-    return;
-  }  
-  const UInt stopTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
-  
-  if( uiTrMode == stopTrMode )
-  {
-    UInt uiDepth      = pcCU->getDepth( uiAbsPartIdx ) + uiTrMode;
-    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
-    if( eTxt != TEXT_LUMA && uiLog2TrSize == 2 )
-    {
-      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
-      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
-      {
-        return;
-      }
-      uiWidth  <<= 1;
-      uiHeight <<= 1;
-    }
-    Pel* pResi = rpcResidual + uiAddr;
-    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTxt];
-    assert(scalingListType < SCALING_LIST_NUM);
-    invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eTxt, REG_DCT, pResi, uiStride, rpcCoeff, uiWidth, uiHeight, scalingListType, pcCU->getTransformSkip(uiAbsPartIdx, eTxt) );
-  }
-  else
-  {
-    uiTrMode++;
-    uiWidth  >>= 1;
-    uiHeight >>= 1;
-    Int trWidth = uiWidth, trHeight = uiHeight;
-    UInt uiAddrOffset = trHeight * uiStride;
-    UInt uiCoefOffset = trWidth * trHeight;
-    UInt uiPartOffset = pcCU->getTotalNumPart() >> ( uiTrMode << 1 );
-    {
-      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr                         , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
-      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + trWidth               , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
-      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + uiAddrOffset          , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
-      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + uiAddrOffset + trWidth, uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff );
+
+  for ( majorAxis = 0; majorAxis < majorAxisLimit; majorAxis++ )
+  {
+    TCoeff accumulatorValue = 0; // 32-bit accumulator
+    for ( minorAxis = 0; minorAxis < minorAxisLimit; minorAxis++ )
+    {
+      const UInt sampleIndex      = (uiY * uiWidth) + uiX;
+      const UInt coefficientIndex = (rotateResidual ? (uiSizeMinus1-sampleIndex) : sampleIndex);
+      const Pel  currentSample    = pcResidual[(uiY * uiStride) + uiX];
+      const TCoeff encoderSideDelta = TCoeff(currentSample) - accumulatorValue;
+
+      Pel reconstructedDelta;
+      if ( bLossless )
+      {
+        pcCoeff[coefficientIndex] = encoderSideDelta;
+        reconstructedDelta        = (Pel) encoderSideDelta;
+      }
+      else
+      {
+        transformSkipQuantOneSample(rTu, compID, encoderSideDelta, pcCoeff, coefficientIndex, cQP, bUseHalfRoundingPoint);
+        invTrSkipDeQuantOneSample  (rTu, compID, pcCoeff[coefficientIndex], reconstructedDelta, cQP, coefficientIndex);
+      }
+
+      uiAbsSum += abs(pcCoeff[coefficientIndex]);
+
+      if (mode != RDPCM_OFF)
+      {
+        accumulatorValue += reconstructedDelta;
+      }
+    }
+  }
+}
+
+Void TComTrQuant::rdpcmNxN   ( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride, const QpParam& cQP, TCoeff* pcCoeff, TCoeff &uiAbsSum, RDPCMMode& rdpcmMode )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  if (!pcCU->isRDPCMEnabled(uiAbsPartIdx) || ((pcCU->getTransformSkip(uiAbsPartIdx, compID) == 0) && !pcCU->getCUTransquantBypass(uiAbsPartIdx)))
+  {
+    rdpcmMode = RDPCM_OFF;
+  }
+  else if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    const ChromaFormat chFmt = pcCU->getPic()->getPicYuvOrg()->getChromaFormat();
+    const ChannelType chType = toChannelType(compID);
+    const UInt uiChPredMode  = pcCU->getIntraDir( chType, uiAbsPartIdx );
+    const TComSPS *sps=pcCU->getSlice()->getSPS();
+    const UInt partsPerMinCU = 1<<(2*(sps->getMaxTotalCUDepth() - sps->getLog2DiffMaxMinCodingBlockSize()));
+    const UInt uiChCodedMode = (uiChPredMode==DM_CHROMA_IDX && isChroma(compID)) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt, partsPerMinCU)) : uiChPredMode;
+    const UInt uiChFinalMode = ((chFmt == CHROMA_422)       && isChroma(compID)) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;
+
+    if (uiChFinalMode == VER_IDX || uiChFinalMode == HOR_IDX)
+    {
+      rdpcmMode = (uiChFinalMode == VER_IDX) ? RDPCM_VER : RDPCM_HOR;
+      applyForwardRDPCM( rTu, compID, pcResidual, uiStride, cQP, pcCoeff, uiAbsSum, rdpcmMode );
+    }
+    else
+    {
+      rdpcmMode = RDPCM_OFF;
+    }
+  }
+  else // not intra, need to select the best mode
+  {
+    const UInt uiWidth  = rTu.getRect(compID).width;
+    const UInt uiHeight = rTu.getRect(compID).height;
+
+    RDPCMMode bestMode   = NUMBER_OF_RDPCM_MODES;
+    TCoeff    bestAbsSum = std::numeric_limits<TCoeff>::max();
+    TCoeff    bestCoefficients[MAX_TU_SIZE * MAX_TU_SIZE];
+
+    for (UInt modeIndex = 0; modeIndex < NUMBER_OF_RDPCM_MODES; modeIndex++)
+    {
+      const RDPCMMode mode = RDPCMMode(modeIndex);
+
+      TCoeff currAbsSum = 0;
+
+      applyForwardRDPCM( rTu, compID, pcResidual, uiStride, cQP, pcCoeff, currAbsSum, mode );
+
+      if (currAbsSum < bestAbsSum)
+      {
+        bestMode   = mode;
+        bestAbsSum = currAbsSum;
+        if (mode != RDPCM_OFF)
+        {
+          memcpy(bestCoefficients, pcCoeff, (uiWidth * uiHeight * sizeof(TCoeff)));
+        }
+      }
+    }
+
+    rdpcmMode = bestMode;
+    uiAbsSum  = bestAbsSum;
+
+    if (rdpcmMode != RDPCM_OFF) //the TU is re-transformed and quantised if DPCM_OFF is returned, so there is no need to preserve it here
+    {
+      memcpy(pcCoeff, bestCoefficients, (uiWidth * uiHeight * sizeof(TCoeff)));
+    }
+  }
+
+  pcCU->setExplicitRdpcmModePartRange(rdpcmMode, compID, uiAbsPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+}
+
+Void TComTrQuant::invRdpcmNxN( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  if (pcCU->isRDPCMEnabled( uiAbsPartIdx ) && ((pcCU->getTransformSkip(uiAbsPartIdx, compID ) != 0) || pcCU->getCUTransquantBypass(uiAbsPartIdx)))
+  {
+    const UInt uiWidth  = rTu.getRect(compID).width;
+    const UInt uiHeight = rTu.getRect(compID).height;
+
+    RDPCMMode rdpcmMode = RDPCM_OFF;
+
+    if ( pcCU->isIntra( uiAbsPartIdx ) )
+    {
+      const ChromaFormat chFmt = pcCU->getPic()->getPicYuvRec()->getChromaFormat();
+      const ChannelType chType = toChannelType(compID);
+      const UInt uiChPredMode  = pcCU->getIntraDir( chType, uiAbsPartIdx );
+      const TComSPS *sps=pcCU->getSlice()->getSPS();
+      const UInt partsPerMinCU = 1<<(2*(sps->getMaxTotalCUDepth() - sps->getLog2DiffMaxMinCodingBlockSize()));
+      const UInt uiChCodedMode = (uiChPredMode==DM_CHROMA_IDX && isChroma(compID)) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt, partsPerMinCU)) : uiChPredMode;
+      const UInt uiChFinalMode = ((chFmt == CHROMA_422)       && isChroma(compID)) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;
+
+      if (uiChFinalMode == VER_IDX || uiChFinalMode == HOR_IDX)
+      {
+        rdpcmMode = (uiChFinalMode == VER_IDX) ? RDPCM_VER : RDPCM_HOR;
+      }
+    }
+    else  // not intra case
+    {
+      rdpcmMode = RDPCMMode(pcCU->getExplicitRdpcmMode( compID, uiAbsPartIdx ));
+    }
+
+    const TCoeff pelMin=(TCoeff) std::numeric_limits<Pel>::min();
+    const TCoeff pelMax=(TCoeff) std::numeric_limits<Pel>::max();
+    if (rdpcmMode == RDPCM_VER)
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        Pel *pcCurResidual = pcResidual+uiX;
+        TCoeff accumulator = *pcCurResidual; // 32-bit accumulator
+        pcCurResidual+=uiStride;
+        for( UInt uiY = 1; uiY < uiHeight; uiY++, pcCurResidual+=uiStride )
+        {
+          accumulator += *(pcCurResidual);
+          *pcCurResidual = (Pel)Clip3<TCoeff>(pelMin, pelMax, accumulator);
+        }
+      }
+    }
+    else if (rdpcmMode == RDPCM_HOR)
+    {
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        Pel *pcCurResidual = pcResidual+uiY*uiStride;
+        TCoeff accumulator = *pcCurResidual;
+        pcCurResidual++;
+        for( UInt uiX = 1; uiX < uiWidth; uiX++, pcCurResidual++ )
+        {
+          accumulator += *(pcCurResidual);
+          *pcCurResidual = (Pel)Clip3<TCoeff>(pelMin, pelMax, accumulator);
+        }
+      }
     }
   }
@@ -1332,141 +1940,174 @@
 // ------------------------------------------------------------------------------------------------
 
-/** Wrapper function between HM interface and core NxN forward transform (2D) 
+/** Wrapper function between HM interface and core NxN forward transform (2D)
+ *  \param channelBitDepth bit depth of channel
+ *  \param useDST
  *  \param piBlkResi input data (residual)
+ *  \param uiStride stride of input residual data
  *  \param psCoeff output data (transform coefficients)
- *  \param uiStride stride of input residual data
- *  \param iSize transform size (iSize x iSize)
- *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ *  \param iWidth transform width
+ *  \param iHeight transform height
+ *  \param maxLog2TrDynamicRange
  */
-Void TComTrQuant::xT(Int bitDepth, UInt uiMode, Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int iWidth, Int iHeight )
-{
-#if MATRIX_MULT  
-  Int iSize = iWidth;
-  xTr(bitDepth, piBlkResi,psCoeff,uiStride,(UInt)iSize,uiMode);
-#else
-  Int j;
-  Short block[ 32 * 32 ];
-  Short coeff[ 32 * 32 ];
-      for (j = 0; j < iHeight; j++)
-      {    
-        memcpy( block + j * iWidth, piBlkResi + j * uiStride, iWidth * sizeof( Short ) );
-      }
-    xTrMxN(bitDepth, block, coeff, iWidth, iHeight, uiMode );
-    for ( j = 0; j < iHeight * iWidth; j++ )
-    {    
-      psCoeff[ j ] = coeff[ j ];
-    }
-#endif  
-}
-
-
-/** Wrapper function between HM interface and core NxN inverse transform (2D) 
+Void TComTrQuant::xT( const Int channelBitDepth, Bool useDST, Pel* piBlkResi, UInt uiStride, TCoeff* psCoeff, Int iWidth, Int iHeight, const Int maxLog2TrDynamicRange )
+{
+#if MATRIX_MULT
+  if( iWidth == iHeight)
+  {
+    xTr(channelBitDepth, piBlkResi, psCoeff, uiStride, (UInt)iWidth, useDST, maxLog2TrDynamicRange);
+    return;
+  }
+#endif
+
+  TCoeff block[ MAX_TU_SIZE * MAX_TU_SIZE ];
+  TCoeff coeff[ MAX_TU_SIZE * MAX_TU_SIZE ];
+
+  for (Int y = 0; y < iHeight; y++)
+  {
+    for (Int x = 0; x < iWidth; x++)
+    {
+      block[(y * iWidth) + x] = piBlkResi[(y * uiStride) + x];
+    }
+  }
+
+  xTrMxN( channelBitDepth, block, coeff, iWidth, iHeight, useDST, maxLog2TrDynamicRange );
+
+  memcpy(psCoeff, coeff, (iWidth * iHeight * sizeof(TCoeff)));
+}
+
+/** Wrapper function between HM interface and core NxN inverse transform (2D)
+ *  \param channelBitDepth bit depth of channel
+ *  \param useDST
  *  \param plCoef input data (transform coefficients)
  *  \param pResidual output data (residual)
  *  \param uiStride stride of input residual data
- *  \param iSize transform size (iSize x iSize)
- *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ *  \param iWidth transform width
+ *  \param iHeight transform height
+ *  \param maxLog2TrDynamicRange
  */
-Void TComTrQuant::xIT(Int bitDepth, UInt uiMode, Int* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight )
-{
-#if MATRIX_MULT  
-  Int iSize = iWidth;
-  xITr(bitDepth, plCoef,pResidual,uiStride,(UInt)iSize,uiMode);
-#else
-  Int j;
-  {
-    Short block[ 32 * 32 ];
-    Short coeff[ 32 * 32 ];
-    for ( j = 0; j < iHeight * iWidth; j++ )
-    {    
-      coeff[j] = (Short)plCoef[j];
-    }
-    xITrMxN(bitDepth, coeff, block, iWidth, iHeight, uiMode );
-    {
-      for ( j = 0; j < iHeight; j++ )
-      {    
-        memcpy( pResidual + j * uiStride, block + j * iWidth, iWidth * sizeof(Short) );
-      }
-    }
-    return ;
-  }
-#endif  
-}
- 
+Void TComTrQuant::xIT( const Int channelBitDepth, Bool useDST, TCoeff* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight, const Int maxLog2TrDynamicRange )
+{
+#if MATRIX_MULT
+  if( iWidth == iHeight )
+  {
+    xITr(channelBitDepth, plCoef, pResidual, uiStride, (UInt)iWidth, useDST, maxLog2TrDynamicRange);
+    return;
+  }
+#endif
+
+  TCoeff block[ MAX_TU_SIZE * MAX_TU_SIZE ];
+  TCoeff coeff[ MAX_TU_SIZE * MAX_TU_SIZE ];
+
+  memcpy(coeff, plCoef, (iWidth * iHeight * sizeof(TCoeff)));
+
+  xITrMxN( channelBitDepth, coeff, block, iWidth, iHeight, useDST, maxLog2TrDynamicRange );
+
+  for (Int y = 0; y < iHeight; y++)
+  {
+    for (Int x = 0; x < iWidth; x++)
+    {
+      pResidual[(y * uiStride) + x] = Pel(block[(y * iWidth) + x]);
+    }
+  }
+}
+
 /** Wrapper function between HM interface and core 4x4 transform skipping
  *  \param piBlkResi input data (residual)
+ *  \param uiStride stride of input residual data
  *  \param psCoeff output data (transform coefficients)
- *  \param uiStride stride of input residual data
- *  \param iSize transform size (iSize x iSize)
+ *  \param rTu reference to transform data
+ *  \param component colour component
  */
-Void TComTrQuant::xTransformSkip(Int bitDepth, Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int width, Int height )
-{
-  assert( width == height );
-  UInt uiLog2TrSize = g_aucConvertToBit[ width ] + 2;
-  Int  shift = MAX_TR_DYNAMIC_RANGE - bitDepth - uiLog2TrSize;
-  UInt transformSkipShift;
-  Int  j,k;
-  if(shift >= 0)
-  {
-    transformSkipShift = shift;
-    for (j = 0; j < height; j++)
-    {    
-      for(k = 0; k < width; k ++)
-      {
-        psCoeff[j*height + k] = piBlkResi[j * uiStride + k] << transformSkipShift;      
-      }
-    }
-  }
-  else
-  {
-    //The case when uiBitDepth > 13
-    Int offset;
-    transformSkipShift = -shift;
-    offset = (1 << (transformSkipShift - 1));
-    for (j = 0; j < height; j++)
-    {    
-      for(k = 0; k < width; k ++)
-      {
-        psCoeff[j*height + k] = (piBlkResi[j * uiStride + k] + offset) >> transformSkipShift;      
-      }
-    }
-  }
-}
-
-/** Wrapper function between HM interface and core NxN transform skipping 
+Void TComTrQuant::xTransformSkip( Pel* piBlkResi, UInt uiStride, TCoeff* psCoeff, TComTU &rTu, const ComponentID component )
+{
+  const TComRectangle &rect = rTu.getRect(component);
+  const Int width           = rect.width;
+  const Int height          = rect.height;
+  const Int maxLog2TrDynamicRange = rTu.getCU()->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(component));
+  const Int channelBitDepth = rTu.getCU()->getSlice()->getSPS()->getBitDepth(toChannelType(component));
+
+  Int iTransformShift = getTransformShift(channelBitDepth, rTu.GetEquivalentLog2TrSize(component), maxLog2TrDynamicRange);
+  if (rTu.getCU()->getSlice()->getSPS()->getSpsRangeExtension().getExtendedPrecisionProcessingFlag())
+  {
+    iTransformShift = std::max<Int>(0, iTransformShift);
+  }
+
+  const Bool rotateResidual = rTu.isNonTransformedResidualRotated(component);
+  const UInt uiSizeMinus1   = (width * height) - 1;
+
+  if (iTransformShift >= 0)
+  {
+    for (UInt y = 0, coefficientIndex = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++, coefficientIndex++)
+      {
+        psCoeff[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] = TCoeff(piBlkResi[(y * uiStride) + x]) << iTransformShift;
+      }
+    }
+  }
+  else //for very high bit depths
+  {
+    iTransformShift = -iTransformShift;
+    const TCoeff offset = 1 << (iTransformShift - 1);
+
+    for (UInt y = 0, coefficientIndex = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++, coefficientIndex++)
+      {
+        psCoeff[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] = (TCoeff(piBlkResi[(y * uiStride) + x]) + offset) >> iTransformShift;
+      }
+    }
+  }
+}
+
+/** Wrapper function between HM interface and core NxN transform skipping
  *  \param plCoef input data (coefficients)
  *  \param pResidual output data (residual)
  *  \param uiStride stride of input residual data
- *  \param iSize transform size (iSize x iSize)
+ *  \param rTu reference to transform data
+ *  \param component colour component ID
  */
-Void TComTrQuant::xITransformSkip(Int bitDepth, Int* plCoef, Pel* pResidual, UInt uiStride, Int width, Int height )
-{
-  assert( width == height );
-  UInt uiLog2TrSize = g_aucConvertToBit[ width ] + 2;
-  Int  shift = MAX_TR_DYNAMIC_RANGE - bitDepth - uiLog2TrSize;
-  UInt transformSkipShift; 
-  Int  j,k;
-  if(shift > 0)
-  {
-    Int offset;
-    transformSkipShift = shift;
-    offset = (1 << (transformSkipShift -1));
-    for ( j = 0; j < height; j++ )
-    {    
-      for(k = 0; k < width; k ++)
-      {
-        pResidual[j * uiStride + k] =  (plCoef[j*width+k] + offset) >> transformSkipShift;
-      } 
-    }
-  }
-  else
-  {
-    //The case when uiBitDepth >= 13
-    transformSkipShift = - shift;
-    for ( j = 0; j < height; j++ )
-    {    
-      for(k = 0; k < width; k ++)
-      {
-        pResidual[j * uiStride + k] =  plCoef[j*width+k] << transformSkipShift;
+Void TComTrQuant::xITransformSkip( TCoeff* plCoef, Pel* pResidual, UInt uiStride, TComTU &rTu, const ComponentID component )
+{
+  const TComRectangle &rect = rTu.getRect(component);
+  const Int width           = rect.width;
+  const Int height          = rect.height;
+  const Int maxLog2TrDynamicRange = rTu.getCU()->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(component));
+#if O0043_BEST_EFFORT_DECODING
+  const Int channelBitDepth = rTu.getCU()->getSlice()->getSPS()->getStreamBitDepth(toChannelType(component));
+#else
+  const Int channelBitDepth = rTu.getCU()->getSlice()->getSPS()->getBitDepth(toChannelType(component));
+#endif
+
+  Int iTransformShift = getTransformShift(channelBitDepth, rTu.GetEquivalentLog2TrSize(component), maxLog2TrDynamicRange);
+  if (rTu.getCU()->getSlice()->getSPS()->getSpsRangeExtension().getExtendedPrecisionProcessingFlag())
+  {
+    iTransformShift = std::max<Int>(0, iTransformShift);
+  }
+
+  const Bool rotateResidual = rTu.isNonTransformedResidualRotated(component);
+  const UInt uiSizeMinus1   = (width * height) - 1;
+
+  if (iTransformShift >= 0)
+  {
+    const TCoeff offset = iTransformShift==0 ? 0 : (1 << (iTransformShift - 1));
+
+    for (UInt y = 0, coefficientIndex = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++, coefficientIndex++)
+      {
+        pResidual[(y * uiStride) + x] =  Pel((plCoef[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] + offset) >> iTransformShift);
+      }
+    }
+  }
+  else //for very high bit depths
+  {
+    iTransformShift = -iTransformShift;
+
+    for (UInt y = 0, coefficientIndex = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++, coefficientIndex++)
+      {
+        pResidual[(y * uiStride) + x] = Pel(plCoef[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] << iTransformShift);
       }
     }
@@ -1475,86 +2116,104 @@
 
 /** RDOQ with CABAC
- * \param pcCU pointer to coding unit structure
+ * \param rTu reference to transform data
  * \param plSrcCoeff pointer to input buffer
  * \param piDstCoeff reference to pointer to output buffer
- * \param uiWidth block width
- * \param uiHeight block height
+ * \param piArlDstCoeff
  * \param uiAbsSum reference to absolute sum of quantized transform coefficient
- * \param eTType plane type / luminance or chrominance
- * \param uiAbsPartIdx absolute partition index
- * \returns Void
+ * \param compID colour component ID
+ * \param cQP reference to quantization parameters
+
  * Rate distortion optimized quantization for entropy
  * coding engines using probability models like CABAC
  */
-Void TComTrQuant::xRateDistOptQuant                 ( TComDataCU*                     pcCU,
-                                                      Int*                            plSrcCoeff,
-                                                      TCoeff*                         piDstCoeff,
+Void TComTrQuant::xRateDistOptQuant                 (       TComTU       &rTu,
+                                                            TCoeff      * plSrcCoeff,
+                                                            TCoeff      * piDstCoeff,
 #if ADAPTIVE_QP_SELECTION
-                                                      Int*&                           piArlDstCoeff,
-#endif
-                                                      UInt                            uiWidth,
-                                                      UInt                            uiHeight,
-                                                      UInt&                           uiAbsSum,
-                                                      TextType                        eTType,
-                                                      UInt                            uiAbsPartIdx )
-{
-  UInt uiLog2TrSize = g_aucConvertToBit[ uiWidth ] + 2;
-  
-  UInt uiBitDepth = eTType == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
-  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
-  UInt       uiGoRiceParam       = 0;
-  Double     d64BlockUncodedCost = 0;
-  const UInt uiLog2BlkSize       = g_aucConvertToBit[ uiWidth ] + 2;
-  const UInt uiMaxNumCoeff       = uiWidth * uiHeight;
-  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
+                                                            TCoeff      * piArlDstCoeff,
+#endif
+                                                            TCoeff       &uiAbsSum,
+                                                      const ComponentID   compID,
+                                                      const QpParam      &cQP  )
+{
+  const TComRectangle  & rect             = rTu.getRect(compID);
+  const UInt             uiWidth          = rect.width;
+  const UInt             uiHeight         = rect.height;
+        TComDataCU    *  pcCU             = rTu.getCU();
+  const UInt             uiAbsPartIdx     = rTu.GetAbsPartIdxTU();
+  const ChannelType      channelType      = toChannelType(compID);
+  const UInt             uiLog2TrSize     = rTu.GetEquivalentLog2TrSize(compID);
+
+  const Bool             extendedPrecision = pcCU->getSlice()->getSPS()->getSpsRangeExtension().getExtendedPrecisionProcessingFlag();
+  const Int              maxLog2TrDynamicRange = pcCU->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(compID));
+  const Int              channelBitDepth = rTu.getCU()->getSlice()->getSPS()->getBitDepth(channelType);
+
+  /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be
+   * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the
+   * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller)
+   * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result
+   */
+
+  // Represents scaling through forward transform
+  Int iTransformShift = getTransformShift(channelBitDepth, uiLog2TrSize, maxLog2TrDynamicRange);
+  if ((pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0) && extendedPrecision)
+  {
+    iTransformShift = std::max<Int>(0, iTransformShift);
+  }
+
+  const Bool bUseGolombRiceParameterAdaptation = pcCU->getSlice()->getSPS()->getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag();
+  const UInt initialGolombRiceParameter        = m_pcEstBitsSbac->golombRiceAdaptationStatistics[rTu.getGolombRiceStatisticsIndex(compID)] / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+        UInt uiGoRiceParam                     = initialGolombRiceParameter;
+  Double     d64BlockUncodedCost               = 0;
+  const UInt uiLog2BlockWidth                  = g_aucConvertToBit[ uiWidth  ] + 2;
+  const UInt uiLog2BlockHeight                 = g_aucConvertToBit[ uiHeight ] + 2;
+  const UInt uiMaxNumCoeff                     = uiWidth * uiHeight;
+  assert(compID<MAX_NUM_COMPONENT);
+
+  Int scalingListType = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
   assert(scalingListType < SCALING_LIST_NUM);
-  
-  Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
-  Double *pdErrScaleOrg = getErrScaleCoeff(scalingListType,uiLog2TrSize-2,m_cQP.m_iRem);
-  Int *piQCoefOrg = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2);
-  Int *piQCoef = piQCoefOrg;
-  Double *pdErrScale = pdErrScaleOrg;
+
+#if ADAPTIVE_QP_SELECTION
+  memset(piArlDstCoeff, 0, sizeof(TCoeff) *  uiMaxNumCoeff);
+#endif
+
+  Double pdCostCoeff [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  Double pdCostSig   [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  Double pdCostCoeff0[ MAX_TU_SIZE * MAX_TU_SIZE ];
+  memset( pdCostCoeff, 0, sizeof(Double) *  uiMaxNumCoeff );
+  memset( pdCostSig,   0, sizeof(Double) *  uiMaxNumCoeff );
+  Int rateIncUp   [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  Int rateIncDown [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  Int sigRateDelta[ MAX_TU_SIZE * MAX_TU_SIZE ];
+  TCoeff deltaU   [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  memset( rateIncUp,    0, sizeof(Int   ) *  uiMaxNumCoeff );
+  memset( rateIncDown,  0, sizeof(Int   ) *  uiMaxNumCoeff );
+  memset( sigRateDelta, 0, sizeof(Int   ) *  uiMaxNumCoeff );
+  memset( deltaU,       0, sizeof(TCoeff) *  uiMaxNumCoeff );
+
+  const Int iQBits = QUANT_SHIFT + cQP.per + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+  const Double *const pdErrScale = getErrScaleCoeff(scalingListType, (uiLog2TrSize-2), cQP.rem);
+  const Int    *const piQCoef    = getQuantCoeff(scalingListType, cQP.rem, (uiLog2TrSize-2));
+
+  const Bool   enableScalingLists             = getUseScalingList(uiWidth, uiHeight, (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0));
+  const Int    defaultQuantisationCoefficient = g_quantScales[cQP.rem];
+  const Double defaultErrorScale              = getErrScaleCoeffNoScalingList(scalingListType, (uiLog2TrSize-2), cQP.rem);
+
+  const TCoeff entropyCodingMinimum = -(1 << maxLog2TrDynamicRange);
+  const TCoeff entropyCodingMaximum =  (1 << maxLog2TrDynamicRange) - 1;
+
 #if ADAPTIVE_QP_SELECTION
   Int iQBitsC = iQBits - ARL_C_PRECISION;
   Int iAddC =  1 << (iQBitsC-1);
 #endif
-  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
-  
-#if ADAPTIVE_QP_SELECTION
-  memset(piArlDstCoeff, 0, sizeof(Int) *  uiMaxNumCoeff);
-#endif
-  
-  Double pdCostCoeff [ 32 * 32 ];
-  Double pdCostSig   [ 32 * 32 ];
-  Double pdCostCoeff0[ 32 * 32 ];
-  ::memset( pdCostCoeff, 0, sizeof(Double) *  uiMaxNumCoeff );
-  ::memset( pdCostSig,   0, sizeof(Double) *  uiMaxNumCoeff );
-  Int rateIncUp   [ 32 * 32 ];
-  Int rateIncDown [ 32 * 32 ];
-  Int sigRateDelta[ 32 * 32 ];
-  Int deltaU      [ 32 * 32 ];
-  ::memset( rateIncUp,    0, sizeof(Int) *  uiMaxNumCoeff );
-  ::memset( rateIncDown,  0, sizeof(Int) *  uiMaxNumCoeff );
-  ::memset( sigRateDelta, 0, sizeof(Int) *  uiMaxNumCoeff );
-  ::memset( deltaU,       0, sizeof(Int) *  uiMaxNumCoeff );
-  
-  const UInt * scanCG;
-  {
-    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize > 3 ? uiLog2BlkSize-2-1 : 0  ];
-    if( uiLog2BlkSize == 3 )
-    {
-      scanCG = g_sigLastScan8x8[ uiScanIdx ];
-    }
-    else if( uiLog2BlkSize == 5 )
-    {
-      scanCG = g_sigLastScanCG32x32;
-    }
-  }
-  const UInt uiCGSize = (1 << MLS_CG_SIZE);         // 16
+
+  TUEntropyCodingParameters codingParameters;
+  getTUEntropyCodingParameters(codingParameters, rTu, compID);
+  const UInt uiCGSize = (1 << MLS_CG_SIZE);
+
   Double pdCostCoeffGroupSig[ MLS_GRP_NUM ];
   UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
-  UInt uiNumBlkSide = uiWidth / MLS_CG_SIZE;
   Int iCGLastScanPos = -1;
-  
+
   UInt    uiCtxSet            = 0;
   Int     c1                  = 1;
@@ -1562,85 +2221,95 @@
   Double  d64BaseCost         = 0;
   Int     iLastScanPos        = -1;
-  
+
   UInt    c1Idx     = 0;
   UInt    c2Idx     = 0;
   Int     baseLevel;
-  
-  const UInt *scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize - 1 ];
-  
-  ::memset( pdCostCoeffGroupSig,   0, sizeof(Double) * MLS_GRP_NUM );
-  ::memset( uiSigCoeffGroupFlag,   0, sizeof(UInt) * MLS_GRP_NUM );
-  
+
+  memset( pdCostCoeffGroupSig,   0, sizeof(Double) * MLS_GRP_NUM );
+  memset( uiSigCoeffGroupFlag,   0, sizeof(UInt) * MLS_GRP_NUM );
+
   UInt uiCGNum = uiWidth * uiHeight >> MLS_CG_SIZE;
   Int iScanPos;
-  coeffGroupRDStats rdStats;     
-  
+  coeffGroupRDStats rdStats;
+
+  const UInt significanceMapContextOffset = getSignificanceMapContextOffset(compID);
+
   for (Int iCGScanPos = uiCGNum-1; iCGScanPos >= 0; iCGScanPos--)
   {
-    UInt uiCGBlkPos = scanCG[ iCGScanPos ];
-    UInt uiCGPosY   = uiCGBlkPos / uiNumBlkSide;
-    UInt uiCGPosX   = uiCGBlkPos - (uiCGPosY * uiNumBlkSide);
-    ::memset( &rdStats, 0, sizeof (coeffGroupRDStats));
-    
-    const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiWidth, uiHeight);
+    UInt uiCGBlkPos = codingParameters.scanCG[ iCGScanPos ];
+    UInt uiCGPosY   = uiCGBlkPos / codingParameters.widthInGroups;
+    UInt uiCGPosX   = uiCGBlkPos - (uiCGPosY * codingParameters.widthInGroups);
+
+    memset( &rdStats, 0, sizeof (coeffGroupRDStats));
+
+    const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups);
+
     for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
     {
       iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
       //===== quantization =====
-      UInt    uiBlkPos          = scan[iScanPos];
+      UInt    uiBlkPos          = codingParameters.scan[iScanPos];
       // set coeff
-      Int uiQ  = piQCoef[uiBlkPos];
-      Double dTemp = pdErrScale[uiBlkPos];
-      Int lLevelDouble          = plSrcCoeff[ uiBlkPos ];
-      lLevelDouble              = (Int)min<Int64>((Int64)abs((Int)lLevelDouble) * uiQ , MAX_INT - (1 << (iQBits - 1)));
+
+      const Int    quantisationCoefficient = (enableScalingLists) ? piQCoef   [uiBlkPos] : defaultQuantisationCoefficient;
+      const Double errorScale              = (enableScalingLists) ? pdErrScale[uiBlkPos] : defaultErrorScale;
+
+      const Int64  tmpLevel                = Int64(abs(plSrcCoeff[ uiBlkPos ])) * quantisationCoefficient;
+
+      const Intermediate_Int lLevelDouble  = (Intermediate_Int)min<Int64>(tmpLevel, std::numeric_limits<Intermediate_Int>::max() - (Intermediate_Int(1) << (iQBits - 1)));
+
 #if ADAPTIVE_QP_SELECTION
       if( m_bUseAdaptQpSelect )
       {
-        piArlDstCoeff[uiBlkPos]   = (Int)(( lLevelDouble + iAddC) >> iQBitsC );
-      }
-#endif
-      UInt uiMaxAbsLevel        = (lLevelDouble + (1 << (iQBits - 1))) >> iQBits;
-      
-      Double dErr               = Double( lLevelDouble );
-      pdCostCoeff0[ iScanPos ]  = dErr * dErr * dTemp;
+        piArlDstCoeff[uiBlkPos]   = (TCoeff)(( lLevelDouble + iAddC) >> iQBitsC );
+      }
+#endif
+      const UInt uiMaxAbsLevel  = std::min<UInt>(UInt(entropyCodingMaximum), UInt((lLevelDouble + (Intermediate_Int(1) << (iQBits - 1))) >> iQBits));
+
+      const Double dErr         = Double( lLevelDouble );
+      pdCostCoeff0[ iScanPos ]  = dErr * dErr * errorScale;
       d64BlockUncodedCost      += pdCostCoeff0[ iScanPos ];
       piDstCoeff[ uiBlkPos ]    = uiMaxAbsLevel;
-      
+
       if ( uiMaxAbsLevel > 0 && iLastScanPos < 0 )
       {
         iLastScanPos            = iScanPos;
-        uiCtxSet                = (iScanPos < SCAN_SET_SIZE || eTType!=TEXT_LUMA) ? 0 : 2;
+        uiCtxSet                = getContextSetIndex(compID, (iScanPos >> MLS_CG_SIZE), 0);
         iCGLastScanPos          = iCGScanPos;
       }
-      
+
       if ( iLastScanPos >= 0 )
       {
         //===== coefficient level estimation =====
         UInt  uiLevel;
-        UInt  uiOneCtx         = 4 * uiCtxSet + c1;
-        UInt  uiAbsCtx         = uiCtxSet + c2;
-        
+        UInt  uiOneCtx         = (NUM_ONE_FLAG_CTX_PER_SET * uiCtxSet) + c1;
+        UInt  uiAbsCtx         = (NUM_ABS_FLAG_CTX_PER_SET * uiCtxSet) + c2;
+
         if( iScanPos == iLastScanPos )
         {
-          uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ], 
-                                                lLevelDouble, uiMaxAbsLevel, 0, uiOneCtx, uiAbsCtx, uiGoRiceParam, 
-                                                c1Idx, c2Idx, iQBits, dTemp, 1 );
+          uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
+                                                  lLevelDouble, uiMaxAbsLevel, significanceMapContextOffset, uiOneCtx, uiAbsCtx, uiGoRiceParam,
+                                                  c1Idx, c2Idx, iQBits, errorScale, 1, extendedPrecision, maxLog2TrDynamicRange
+                                                  );
         }
         else
         {
-          UInt   uiPosY        = uiBlkPos >> uiLog2BlkSize;
-          UInt   uiPosX        = uiBlkPos - ( uiPosY << uiLog2BlkSize );
-          UShort uiCtxSig      = getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, uiLog2BlkSize, eTType );
+          UShort uiCtxSig      = significanceMapContextOffset + getSigCtxInc( patternSigCtx, codingParameters, iScanPos, uiLog2BlockWidth, uiLog2BlockHeight, channelType );
+
           uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
-                                                lLevelDouble, uiMaxAbsLevel, uiCtxSig, uiOneCtx, uiAbsCtx, uiGoRiceParam, 
-                                                c1Idx, c2Idx, iQBits, dTemp, 0 );
+                                                  lLevelDouble, uiMaxAbsLevel, uiCtxSig, uiOneCtx, uiAbsCtx, uiGoRiceParam,
+                                                  c1Idx, c2Idx, iQBits, errorScale, 0, extendedPrecision, maxLog2TrDynamicRange
+                                                  );
+
           sigRateDelta[ uiBlkPos ] = m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 1 ] - m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 0 ];
         }
-        deltaU[ uiBlkPos ]        = (lLevelDouble - ((Int)uiLevel << iQBits)) >> (iQBits-8);
+
+        deltaU[ uiBlkPos ]        = TCoeff((lLevelDouble - (Intermediate_Int(uiLevel) << iQBits)) >> (iQBits-8));
+
         if( uiLevel > 0 )
         {
-          Int rateNow = xGetICRate( uiLevel, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx );
-          rateIncUp   [ uiBlkPos ] = xGetICRate( uiLevel+1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx ) - rateNow;
-          rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx ) - rateNow;
+          Int rateNow = xGetICRate( uiLevel, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange );
+          rateIncUp   [ uiBlkPos ] = xGetICRate( uiLevel+1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange ) - rateNow;
+          rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange ) - rateNow;
         }
         else // uiLevel == 0
@@ -1650,12 +2319,11 @@
         piDstCoeff[ uiBlkPos ] = uiLevel;
         d64BaseCost           += pdCostCoeff [ iScanPos ];
-        
-        
+
         baseLevel = (c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
         if( uiLevel >= baseLevel )
         {
-          if(uiLevel  > 3*(1<<uiGoRiceParam))
+          if (uiLevel > 3*(1<<uiGoRiceParam))
           {
-            uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+            uiGoRiceParam = bUseGolombRiceParameterAdaptation ? (uiGoRiceParam + 1) : (std::min<UInt>((uiGoRiceParam + 1), 4));
           }
         }
@@ -1664,9 +2332,9 @@
           c1Idx ++;
         }
-        
+
         //===== update bin model =====
         if( uiLevel > 1 )
         {
-          c1 = 0; 
+          c1 = 0;
           c2 += (c2 < 2);
           c2Idx ++;
@@ -1676,19 +2344,14 @@
           c1++;
         }
-        
+
         //===== context set update =====
-        if( ( iScanPos % SCAN_SET_SIZE == 0 ) && ( iScanPos > 0 ) )
-        {
+        if( ( iScanPos % uiCGSize == 0 ) && ( iScanPos > 0 ) )
+        {
+          uiCtxSet          = getContextSetIndex(compID, ((iScanPos - 1) >> MLS_CG_SIZE), (c1 == 0)); //(iScanPos - 1) because we do this **before** entering the final group
+          c1                = 1;
           c2                = 0;
-          uiGoRiceParam     = 0;
-          
-          c1Idx   = 0;
-          c2Idx   = 0; 
-          uiCtxSet          = (iScanPos == SCAN_SET_SIZE || eTType!=TEXT_LUMA) ? 0 : 2;
-          if( c1 == 0 )
-          {
-            uiCtxSet++;
-          }
-          c1 = 1;
+          c1Idx             = 0;
+          c2Idx             = 0;
+          uiGoRiceParam     = initialGolombRiceParameter;
         }
       }
@@ -1713,6 +2376,6 @@
       }
     } //end for (iScanPosinCG)
-    
-    if (iCGLastScanPos >= 0) 
+
+    if (iCGLastScanPos >= 0)
     {
       if( iCGScanPos )
@@ -1720,13 +2383,13 @@
         if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
         {
-          UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiWidth, uiHeight);
-          d64BaseCost += xGetRateSigCoeffGroup(0, uiCtxSig) - rdStats.d64SigCost;;  
-          pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig);  
-        } 
+          UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups );
+          d64BaseCost += xGetRateSigCoeffGroup(0, uiCtxSig) - rdStats.d64SigCost;;
+          pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig);
+        }
         else
         {
           if (iCGScanPos < iCGLastScanPos) //skip the last coefficient group, which will be handled together with last position below.
           {
-            if ( rdStats.iNNZbeforePos0 == 0 ) 
+            if ( rdStats.iNNZbeforePos0 == 0 )
             {
               d64BaseCost -= rdStats.d64SigCost_0;
@@ -1735,21 +2398,22 @@
             // rd-cost if SigCoeffGroupFlag = 0, initialization
             Double d64CostZeroCG = d64BaseCost;
-            
+
             // add SigCoeffGroupFlag cost to total cost
-            UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiWidth, uiHeight);
+            UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups );
+
             if (iCGScanPos < iCGLastScanPos)
             {
-              d64BaseCost  += xGetRateSigCoeffGroup(1, uiCtxSig); 
-              d64CostZeroCG += xGetRateSigCoeffGroup(0, uiCtxSig);  
-              pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(1, uiCtxSig); 
+              d64BaseCost  += xGetRateSigCoeffGroup(1, uiCtxSig);
+              d64CostZeroCG += xGetRateSigCoeffGroup(0, uiCtxSig);
+              pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(1, uiCtxSig);
             }
-            
+
             // try to convert the current coeff group from non-zero to all-zero
             d64CostZeroCG += rdStats.d64UncodedDist;  // distortion for resetting non-zero levels to zero levels
             d64CostZeroCG -= rdStats.d64CodedLevelandDist;   // distortion and level cost for keeping all non-zero levels
             d64CostZeroCG -= rdStats.d64SigCost;     // sig cost for all coeffs, including zero levels and non-zerl levels
-            
+
             // if we can save cost, change this block to all-zero block
-            if ( d64CostZeroCG < d64BaseCost )      
+            if ( d64CostZeroCG < d64BaseCost )
             {
               uiSigCoeffGroupFlag[ uiCGBlkPos ] = 0;
@@ -1757,12 +2421,12 @@
               if (iCGScanPos < iCGLastScanPos)
               {
-                pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig); 
+                pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig);
               }
-              // reset coeffs to 0 in this block                
+              // reset coeffs to 0 in this block
               for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
               {
                 iScanPos      = iCGScanPos*uiCGSize + iScanPosinCG;
-                UInt uiBlkPos = scan[ iScanPos ];
-                
+                UInt uiBlkPos = codingParameters.scan[ iScanPos ];
+
                 if (piDstCoeff[ uiBlkPos ])
                 {
@@ -1772,5 +2436,5 @@
                 }
               }
-            } // end if ( d64CostAllZeros < d64BaseCost )      
+            } // end if ( d64CostAllZeros < d64BaseCost )
           }
         } // end if if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
@@ -1782,5 +2446,5 @@
     }
   } //end for (iCGScanPos)
-  
+
   //===== estimate last position =====
   if ( iLastScanPos < 0 )
@@ -1788,9 +2452,9 @@
     return;
   }
-  
+
   Double  d64BestCost         = 0;
   Int     ui16CtxCbf          = 0;
   Int     iBestLastIdxP1      = 0;
-  if( !pcCU->isIntra( uiAbsPartIdx ) && eTType == TEXT_LUMA && pcCU->getTransformIdx( uiAbsPartIdx ) == 0 )
+  if( !pcCU->isIntra( uiAbsPartIdx ) && isLuma(compID) && pcCU->getTransformIdx( uiAbsPartIdx ) == 0 )
   {
     ui16CtxCbf   = 0;
@@ -1800,32 +2464,37 @@
   else
   {
-    ui16CtxCbf   = pcCU->getCtxQtCbf( eTType, pcCU->getTransformIdx( uiAbsPartIdx ) );
-    ui16CtxCbf   = ( eTType ? TEXT_CHROMA : eTType ) * NUM_QT_CBF_CTX + ui16CtxCbf;
+    ui16CtxCbf   = pcCU->getCtxQtCbf( rTu, channelType );
+    ui16CtxCbf  += getCBFContextOffset(compID);
     d64BestCost  = d64BlockUncodedCost + xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 0 ] );
     d64BaseCost += xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 1 ] );
   }
-  
+
+
   Bool bFoundLast = false;
   for (Int iCGScanPos = iCGLastScanPos; iCGScanPos >= 0; iCGScanPos--)
   {
-    UInt uiCGBlkPos = scanCG[ iCGScanPos ];
-    
-    d64BaseCost -= pdCostCoeffGroupSig [ iCGScanPos ]; 
+    UInt uiCGBlkPos = codingParameters.scanCG[ iCGScanPos ];
+
+    d64BaseCost -= pdCostCoeffGroupSig [ iCGScanPos ];
     if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
-    {     
+    {
       for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
       {
         iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
-        if (iScanPos > iLastScanPos) continue;
-        UInt   uiBlkPos     = scan[iScanPos];
-        
+
+        if (iScanPos > iLastScanPos)
+        {
+          continue;
+        }
+        UInt   uiBlkPos     = codingParameters.scan[iScanPos];
+
         if( piDstCoeff[ uiBlkPos ] )
         {
-          UInt   uiPosY       = uiBlkPos >> uiLog2BlkSize;
-          UInt   uiPosX       = uiBlkPos - ( uiPosY << uiLog2BlkSize );
-          
-          Double d64CostLast= uiScanIdx == SCAN_VER ? xGetRateLast( uiPosY, uiPosX ) : xGetRateLast( uiPosX, uiPosY );
+          UInt   uiPosY       = uiBlkPos >> uiLog2BlockWidth;
+          UInt   uiPosX       = uiBlkPos - ( uiPosY << uiLog2BlockWidth );
+
+          Double d64CostLast= codingParameters.scanType == SCAN_VER ? xGetRateLast( uiPosY, uiPosX, compID ) : xGetRateLast( uiPosX, uiPosY, compID );
           Double totalCost = d64BaseCost + d64CostLast - pdCostSig[ iScanPos ];
-          
+
           if( totalCost < d64BestCost )
           {
@@ -1845,5 +2514,5 @@
           d64BaseCost      -= pdCostSig[ iScanPos ];
         }
-      } //end for 
+      } //end for
       if (bFoundLast)
       {
@@ -1851,39 +2520,42 @@
       }
     } // end if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
-  } // end for 
-  
+  } // end for
+
+
   for ( Int scanPos = 0; scanPos < iBestLastIdxP1; scanPos++ )
   {
-    Int blkPos = scan[ scanPos ];
-    Int level  = piDstCoeff[ blkPos ];
+    Int blkPos = codingParameters.scan[ scanPos ];
+    TCoeff level = piDstCoeff[ blkPos ];
     uiAbsSum += level;
     piDstCoeff[ blkPos ] = ( plSrcCoeff[ blkPos ] < 0 ) ? -level : level;
   }
-  
+
   //===== clean uncoded coefficients =====
   for ( Int scanPos = iBestLastIdxP1; scanPos <= iLastScanPos; scanPos++ )
   {
-    piDstCoeff[ scan[ scanPos ] ] = 0;
-  }
-  
+    piDstCoeff[ codingParameters.scan[ scanPos ] ] = 0;
+  }
+
+
   if( pcCU->getSlice()->getPPS()->getSignHideFlag() && uiAbsSum>=2)
   {
-    Int64 rdFactor = (Int64) (
-                     g_invQuantScales[m_cQP.rem()] * g_invQuantScales[m_cQP.rem()] * (1<<(2*m_cQP.m_iPer))
-                   / m_dLambda / 16 / (1<<DISTORTION_PRECISION_ADJUSTMENT(2*(uiBitDepth-8)))
-                   + 0.5);
+    const Double inverseQuantScale = Double(g_invQuantScales[cQP.rem]);
+    Int64 rdFactor = (Int64)(inverseQuantScale * inverseQuantScale * (1 << (2 * cQP.per))
+                             / m_dLambda / 16 / (1 << (2 * DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth - 8)))
+                             + 0.5);
+
     Int lastCG = -1;
     Int absSum = 0 ;
     Int n ;
-    
-    for( Int subSet = (uiWidth*uiHeight-1) >> LOG2_SCAN_SET_SIZE; subSet >= 0; subSet-- )
-    {
-      Int  subPos     = subSet << LOG2_SCAN_SET_SIZE;
-      Int  firstNZPosInCG=SCAN_SET_SIZE , lastNZPosInCG=-1 ;
+
+    for( Int subSet = (uiWidth*uiHeight-1) >> MLS_CG_SIZE; subSet >= 0; subSet-- )
+    {
+      Int  subPos     = subSet << MLS_CG_SIZE;
+      Int  firstNZPosInCG=uiCGSize , lastNZPosInCG=-1 ;
       absSum = 0 ;
-      
-      for(n = SCAN_SET_SIZE-1; n >= 0; --n )
-      {
-        if( piDstCoeff[ scan[ n + subPos ]] )
+
+      for(n = uiCGSize-1; n >= 0; --n )
+      {
+        if( piDstCoeff[ codingParameters.scan[ n + subPos ]] )
         {
           lastNZPosInCG = n;
@@ -1891,8 +2563,8 @@
         }
       }
-      
-      for(n = 0; n <SCAN_SET_SIZE; n++ )
-      {
-        if( piDstCoeff[ scan[ n + subPos ]] )
+
+      for(n = 0; n <uiCGSize; n++ )
+      {
+        if( piDstCoeff[ codingParameters.scan[ n + subPos ]] )
         {
           firstNZPosInCG = n;
@@ -1900,53 +2572,53 @@
         }
       }
-      
+
       for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
       {
-        absSum += piDstCoeff[ scan[ n + subPos ]];
-      }
-      
+        absSum += Int(piDstCoeff[ codingParameters.scan[ n + subPos ]]);
+      }
+
       if(lastNZPosInCG>=0 && lastCG==-1)
       {
-        lastCG = 1; 
-      } 
-      
+        lastCG = 1;
+      }
+
       if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
       {
-        UInt signbit = (piDstCoeff[scan[subPos+firstNZPosInCG]]>0?0:1);
+        UInt signbit = (piDstCoeff[codingParameters.scan[subPos+firstNZPosInCG]]>0?0:1);
         if( signbit!=(absSum&0x1) )  // hide but need tune
         {
-          // calculate the cost 
-          Int64 minCostInc = MAX_INT64, curCost=MAX_INT64;
-          Int minPos =-1, finalChange=0, curChange=0;
-          
-          for( n = (lastCG==1?lastNZPosInCG:SCAN_SET_SIZE-1) ; n >= 0; --n )
+          // calculate the cost
+          Int64 minCostInc = std::numeric_limits<Int64>::max(), curCost = std::numeric_limits<Int64>::max();
+          Int minPos = -1, finalChange = 0, curChange = 0;
+
+          for( n = (lastCG==1?lastNZPosInCG:uiCGSize-1) ; n >= 0; --n )
           {
-            UInt uiBlkPos   = scan[ n + subPos ];
+            UInt uiBlkPos   = codingParameters.scan[ n + subPos ];
             if(piDstCoeff[ uiBlkPos ] != 0 )
             {
-              Int64 costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos] ;
-              Int64 costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos] 
-              -   ((abs(piDstCoeff[uiBlkPos]) == 1) ? sigRateDelta[uiBlkPos] : 0);
-              
+              Int64 costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos];
+              Int64 costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos]
+                               -   ((abs(piDstCoeff[uiBlkPos]) == 1) ? sigRateDelta[uiBlkPos] : 0);
+
               if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1)
               {
-                costDown -= (4<<15) ;
+                costDown -= (4<<15);
               }
-              
+
               if(costUp<costDown)
-              {  
+              {
                 curCost = costUp;
-                curChange =  1 ;
+                curChange =  1;
               }
-              else               
+              else
               {
-                curChange = -1 ;
+                curChange = -1;
                 if(n==firstNZPosInCG && abs(piDstCoeff[uiBlkPos])==1)
                 {
-                  curCost = MAX_INT64 ;
+                  curCost = std::numeric_limits<Int64>::max();
                 }
                 else
                 {
-                  curCost = costDown ; 
+                  curCost = costDown;
                 }
               }
@@ -1954,7 +2626,7 @@
             else
             {
-              curCost = rdFactor * ( - (abs(deltaU[uiBlkPos])) ) + (1<<15) + rateIncUp[uiBlkPos] + sigRateDelta[uiBlkPos] ; 
+              curCost = rdFactor * ( - (abs(deltaU[uiBlkPos])) ) + (1<<15) + rateIncUp[uiBlkPos] + sigRateDelta[uiBlkPos] ;
               curChange = 1 ;
-              
+
               if(n<firstNZPosInCG)
               {
@@ -1962,22 +2634,22 @@
                 if(thissignbit != signbit )
                 {
-                  curCost = MAX_INT64;
+                  curCost = std::numeric_limits<Int64>::max();
                 }
               }
             }
-            
+
             if( curCost<minCostInc)
             {
-              minCostInc = curCost ;
-              finalChange = curChange ;
-              minPos = uiBlkPos ;
+              minCostInc = curCost;
+              finalChange = curChange;
+              minPos = uiBlkPos;
             }
           }
-          
-          if(piDstCoeff[minPos] == 32767 || piDstCoeff[minPos] == -32768)
+
+          if(piDstCoeff[minPos] == entropyCodingMaximum || piDstCoeff[minPos] == entropyCodingMinimum)
           {
             finalChange = -1;
           }
-          
+
           if(plSrcCoeff[minPos]>=0)
           {
@@ -1986,144 +2658,190 @@
           else
           {
-            piDstCoeff[minPos] -= finalChange ; 
-          }          
-        }
-      }
-      
+            piDstCoeff[minPos] -= finalChange ;
+          }
+        }
+      }
+
       if(lastCG==1)
       {
-        lastCG=0 ;  
-      }
-    }
-  }
-}
+        lastCG=0 ;
+      }
+    }
+  }
+}
+
 
 /** Pattern decision for context derivation process of significant_coeff_flag
  * \param sigCoeffGroupFlag pointer to prior coded significant coeff group
- * \param posXCG column of current coefficient group
- * \param posYCG row of current coefficient group
- * \param width width of the block
- * \param height height of the block
+ * \param uiCGPosX column of current coefficient group
+ * \param uiCGPosY row of current coefficient group
+ * \param widthInGroups width of the block
+ * \param heightInGroups height of the block
  * \returns pattern for current coefficient group
  */
-Int  TComTrQuant::calcPatternSigCtx( const UInt* sigCoeffGroupFlag, UInt posXCG, UInt posYCG, Int width, Int height )
-{
-  if( width == 4 && height == 4 ) return -1;
+Int  TComTrQuant::calcPatternSigCtx( const UInt* sigCoeffGroupFlag, UInt uiCGPosX, UInt uiCGPosY, UInt widthInGroups, UInt heightInGroups )
+{
+  if ((widthInGroups <= 1) && (heightInGroups <= 1))
+  {
+    return 0;
+  }
+
+  const Bool rightAvailable = uiCGPosX < (widthInGroups  - 1);
+  const Bool belowAvailable = uiCGPosY < (heightInGroups - 1);
 
   UInt sigRight = 0;
   UInt sigLower = 0;
 
-  width >>= 2;
-  height >>= 2;
-  if( posXCG < width - 1 )
-  {
-    sigRight = (sigCoeffGroupFlag[ posYCG * width + posXCG + 1 ] != 0);
-  }
-  if (posYCG < height - 1 )
-  {
-    sigLower = (sigCoeffGroupFlag[ (posYCG  + 1 ) * width + posXCG ] != 0);
-  }
-  return sigRight + (sigLower<<1);
-}
+  if (rightAvailable)
+  {
+    sigRight = ((sigCoeffGroupFlag[ (uiCGPosY * widthInGroups) + uiCGPosX + 1 ] != 0) ? 1 : 0);
+  }
+  if (belowAvailable)
+  {
+    sigLower = ((sigCoeffGroupFlag[ (uiCGPosY + 1) * widthInGroups + uiCGPosX ] != 0) ? 1 : 0);
+  }
+
+  return sigRight + (sigLower << 1);
+}
+
 
 /** Context derivation process of coeff_abs_significant_flag
  * \param patternSigCtx pattern for current coefficient group
- * \param posX column of current scan position
- * \param posY row of current scan position
- * \param log2BlockSize log2 value of block size (square block)
- * \param width width of the block
- * \param height height of the block
- * \param textureType texture type (TEXT_LUMA...)
+ * \param codingParameters coding parameters for the TU (includes the scan)
+ * \param scanPosition current position in scan order
+ * \param log2BlockWidth log2 width of the block
+ * \param log2BlockHeight log2 height of the block
+ * \param chanType channel type (CHANNEL_TYPE_LUMA/CHROMA)
  * \returns ctxInc for current scan position
  */
-Int TComTrQuant::getSigCtxInc    (
-                                   Int                             patternSigCtx,
-                                   UInt                            scanIdx,
-                                   Int                             posX,
-                                   Int                             posY,
-                                   Int                             log2BlockSize,
-                                   TextType                        textureType
-                                  )
-{
-  const Int ctxIndMap[16] =
-  {
-    0, 1, 4, 5,
-    2, 3, 4, 5,
-    6, 6, 8, 8,
-    7, 7, 8, 8
-  };
-
-  if( posX + posY == 0 )
-  {
-    return 0;
-  }
-
-  if ( log2BlockSize == 2 )
-  {
-    return ctxIndMap[ 4 * posY + posX ];
-  }
-
-  Int offset = log2BlockSize == 3 ? (scanIdx==SCAN_DIAG ? 9 : 15) : (textureType == TEXT_LUMA ? 21 : 12);
-
-  Int posXinSubset = posX-((posX>>2)<<2);
-  Int posYinSubset = posY-((posY>>2)<<2);
-  Int cnt = 0;
-  if(patternSigCtx==0)
-  {
-    cnt = posXinSubset+posYinSubset<=2 ? (posXinSubset+posYinSubset==0 ? 2 : 1) : 0;
-  }
-  else if(patternSigCtx==1)
-  {
-    cnt = posYinSubset<=1 ? (posYinSubset==0 ? 2 : 1) : 0;
-  }
-  else if(patternSigCtx==2)
-  {
-    cnt = posXinSubset<=1 ? (posXinSubset==0 ? 2 : 1) : 0;
+Int TComTrQuant::getSigCtxInc    (       Int                        patternSigCtx,
+                                   const TUEntropyCodingParameters &codingParameters,
+                                   const Int                        scanPosition,
+                                   const Int                        log2BlockWidth,
+                                   const Int                        log2BlockHeight,
+                                   const ChannelType                chanType)
+{
+  if (codingParameters.firstSignificanceMapContext == significanceMapContextSetStart[chanType][CONTEXT_TYPE_SINGLE])
+  {
+    //single context mode
+    return significanceMapContextSetStart[chanType][CONTEXT_TYPE_SINGLE];
+  }
+
+  const UInt rasterPosition = codingParameters.scan[scanPosition];
+  const UInt posY           = rasterPosition >> log2BlockWidth;
+  const UInt posX           = rasterPosition - (posY << log2BlockWidth);
+
+  if ((posX + posY) == 0)
+  {
+    return 0; //special case for the DC context variable
+  }
+
+  Int offset = MAX_INT;
+
+  if ((log2BlockWidth == 2) && (log2BlockHeight == 2)) //4x4
+  {
+    offset = ctxIndMap4x4[ (4 * posY) + posX ];
   }
   else
   {
-    cnt = 2;
-  }
-
-  return (( textureType == TEXT_LUMA && ((posX>>2) + (posY>>2)) > 0 ) ? 3 : 0) + offset + cnt;
-}
+    Int cnt = 0;
+
+    switch (patternSigCtx)
+    {
+      //------------------
+
+      case 0: //neither neighbouring group is significant
+        {
+          const Int posXinSubset     = posX & ((1 << MLS_CG_LOG2_WIDTH)  - 1);
+          const Int posYinSubset     = posY & ((1 << MLS_CG_LOG2_HEIGHT) - 1);
+          const Int posTotalInSubset = posXinSubset + posYinSubset;
+
+          //first N coefficients in scan order use 2; the next few use 1; the rest use 0.
+          const UInt context1Threshold = NEIGHBOURHOOD_00_CONTEXT_1_THRESHOLD_4x4;
+          const UInt context2Threshold = NEIGHBOURHOOD_00_CONTEXT_2_THRESHOLD_4x4;
+
+          cnt = (posTotalInSubset >= context1Threshold) ? 0 : ((posTotalInSubset >= context2Threshold) ? 1 : 2);
+        }
+        break;
+
+      //------------------
+
+      case 1: //right group is significant, below is not
+        {
+          const Int posYinSubset = posY & ((1 << MLS_CG_LOG2_HEIGHT) - 1);
+          const Int groupHeight  = 1 << MLS_CG_LOG2_HEIGHT;
+
+          cnt = (posYinSubset >= (groupHeight >> 1)) ? 0 : ((posYinSubset >= (groupHeight >> 2)) ? 1 : 2); //top quarter uses 2; second-from-top quarter uses 1; bottom half uses 0
+        }
+        break;
+
+      //------------------
+
+      case 2: //below group is significant, right is not
+        {
+          const Int posXinSubset = posX & ((1 << MLS_CG_LOG2_WIDTH)  - 1);
+          const Int groupWidth   = 1 << MLS_CG_LOG2_WIDTH;
+
+          cnt = (posXinSubset >= (groupWidth >> 1)) ? 0 : ((posXinSubset >= (groupWidth >> 2)) ? 1 : 2); //left quarter uses 2; second-from-left quarter uses 1; right half uses 0
+        }
+        break;
+
+      //------------------
+
+      case 3: //both neighbouring groups are significant
+        {
+          cnt = 2;
+        }
+        break;
+
+      //------------------
+
+      default:
+        std::cerr << "ERROR: Invalid patternSigCtx \"" << Int(patternSigCtx) << "\" in getSigCtxInc" << std::endl;
+        exit(1);
+        break;
+    }
+
+    //------------------------------------------------
+
+    const Bool notFirstGroup = ((posX >> MLS_CG_LOG2_WIDTH) + (posY >> MLS_CG_LOG2_HEIGHT)) > 0;
+
+    offset = (notFirstGroup ? notFirstGroupNeighbourhoodContextOffset[chanType] : 0) + cnt;
+  }
+
+  return codingParameters.firstSignificanceMapContext + offset;
+}
+
 
 /** Get the best level in RD sense
- * \param rd64CodedCost reference to coded cost
- * \param rd64CodedCost0 reference to cost when coefficient is 0
- * \param rd64CodedCostSig reference to cost of significant coefficient
- * \param lLevelDouble reference to unscaled quantized level
- * \param uiMaxAbsLevel scaled quantized level
- * \param ui16CtxNumSig current ctxInc for coeff_abs_significant_flag
- * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
- * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
- * \param ui16AbsGoRice current Rice parameter for coeff_abs_level_minus3
- * \param iQBits quantization step size
- * \param dTemp correction factor
- * \param bLast indicates if the coefficient is the last significant
+ *
  * \returns best quantized transform level for given scan position
+ *
  * This method calculates the best quantized transform level for a given scan position.
  */
-__inline UInt TComTrQuant::xGetCodedLevel ( Double&                         rd64CodedCost,
-                                            Double&                         rd64CodedCost0,
-                                            Double&                         rd64CodedCostSig,
-                                            Int                             lLevelDouble,
-                                            UInt                            uiMaxAbsLevel,
-                                            UShort                          ui16CtxNumSig,
-                                            UShort                          ui16CtxNumOne,
-                                            UShort                          ui16CtxNumAbs,
-                                            UShort                          ui16AbsGoRice,
-                                            UInt                            c1Idx,
-                                            UInt                            c2Idx,
-                                            Int                             iQBits,
-                                            Double                          dTemp,
-                                            Bool                            bLast        ) const
-{
-  Double dCurrCostSig   = 0; 
+__inline UInt TComTrQuant::xGetCodedLevel ( Double&          rd64CodedCost,          //< reference to coded cost
+                                            Double&          rd64CodedCost0,         //< reference to cost when coefficient is 0
+                                            Double&          rd64CodedCostSig,       //< rd64CodedCostSig reference to cost of significant coefficient
+                                            Intermediate_Int lLevelDouble,           //< reference to unscaled quantized level
+                                            UInt             uiMaxAbsLevel,          //< scaled quantized level
+                                            UShort           ui16CtxNumSig,          //< current ctxInc for coeff_abs_significant_flag
+                                            UShort           ui16CtxNumOne,          //< current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
+                                            UShort           ui16CtxNumAbs,          //< current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
+                                            UShort           ui16AbsGoRice,          //< current Rice parameter for coeff_abs_level_minus3
+                                            UInt             c1Idx,                  //< 
+                                            UInt             c2Idx,                  //< 
+                                            Int              iQBits,                 //< quantization step size
+                                            Double           errorScale,             //< 
+                                            Bool             bLast,                  //< indicates if the coefficient is the last significant
+                                            Bool             useLimitedPrefixLength, //< 
+                                            const Int        maxLog2TrDynamicRange   //< 
+                                            ) const
+{
+  Double dCurrCostSig   = 0;
   UInt   uiBestAbsLevel = 0;
-  
+
   if( !bLast && uiMaxAbsLevel < 3 )
   {
-    rd64CodedCostSig    = xGetRateSigCoef( 0, ui16CtxNumSig ); 
+    rd64CodedCostSig    = xGetRateSigCoef( 0, ui16CtxNumSig );
     rd64CodedCost       = rd64CodedCost0 + rd64CodedCostSig;
     if( uiMaxAbsLevel == 0 )
@@ -2145,6 +2863,6 @@
   for( Int uiAbsLevel  = uiMaxAbsLevel; uiAbsLevel >= uiMinAbsLevel ; uiAbsLevel-- )
   {
-    Double dErr         = Double( lLevelDouble  - ( uiAbsLevel << iQBits ) );
-    Double dCurrCost    = dErr * dErr * dTemp + xGetICost(xGetICRate( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx ));
+    Double dErr         = Double( lLevelDouble  - ( Intermediate_Int(uiAbsLevel) << iQBits ) );
+    Double dCurrCost    = dErr * dErr * errorScale + xGetICost( xGetICRate( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx, useLimitedPrefixLength, maxLog2TrDynamicRange ) );
     dCurrCost          += dCurrCostSig;
 
@@ -2165,19 +2883,25 @@
  * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
  * \param ui16AbsGoRice Rice parameter for coeff_abs_level_minus3
+ * \param c1Idx
+ * \param c2Idx
+ * \param useLimitedPrefixLength
+ * \param maxLog2TrDynamicRange
  * \returns cost of given absolute transform level
  */
-__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
-                                               UShort                          ui16CtxNumOne,
-                                               UShort                          ui16CtxNumAbs,
-                                               UShort                          ui16AbsGoRice
-                                            ,  UInt                            c1Idx,
-                                               UInt                            c2Idx
+__inline Int TComTrQuant::xGetICRate         ( const UInt    uiAbsLevel,
+                                               const UShort  ui16CtxNumOne,
+                                               const UShort  ui16CtxNumAbs,
+                                               const UShort  ui16AbsGoRice,
+                                               const UInt    c1Idx,
+                                               const UInt    c2Idx,
+                                               const Bool    useLimitedPrefixLength,
+                                               const Int     maxLog2TrDynamicRange
                                                ) const
 {
-  Int iRate = Int(xGetIEPRate());
-  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+  Int  iRate      = Int(xGetIEPRate()); // cost of sign bit
+  UInt baseLevel  = (c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
 
   if ( uiAbsLevel >= baseLevel )
-  {    
+  {
     UInt symbol     = uiAbsLevel - baseLevel;
     UInt length;
@@ -2187,4 +2911,20 @@
       iRate += (length+1+ui16AbsGoRice)<< 15;
     }
+    else if (useLimitedPrefixLength)
+    {
+      const UInt maximumPrefixLength = (32 - (COEF_REMAIN_BIN_REDUCTION + maxLog2TrDynamicRange));
+
+      UInt prefixLength = 0;
+      UInt suffix       = (symbol >> ui16AbsGoRice) - COEF_REMAIN_BIN_REDUCTION;
+
+      while ((prefixLength < maximumPrefixLength) && (suffix > ((2 << prefixLength) - 2)))
+      {
+        prefixLength++;
+      }
+
+      const UInt suffixLength = (prefixLength == maximumPrefixLength) ? (maxLog2TrDynamicRange - ui16AbsGoRice) : (prefixLength + 1/*separator*/);
+
+      iRate += (COEF_REMAIN_BIN_REDUCTION + prefixLength + suffixLength + ui16AbsGoRice) << 15;
+    }
     else
     {
@@ -2193,8 +2933,9 @@
       while (symbol >= (1<<length))
       {
-        symbol -=  (1<<(length++));    
+        symbol -=  (1<<(length++));
       }
       iRate += (COEF_REMAIN_BIN_REDUCTION+length+1-ui16AbsGoRice+length)<< 15;
     }
+
     if (c1Idx < C1FLAG_NUMBER)
     {
@@ -2207,6 +2948,5 @@
     }
   }
-  else
-  if( uiAbsLevel == 1 )
+  else if( uiAbsLevel == 1 )
   {
     iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
@@ -2221,5 +2961,6 @@
     iRate = 0;
   }
-  return iRate;
+
+  return  iRate;
 }
 
@@ -2233,4 +2974,5 @@
  * \param uiPosX X coordinate of the last significant coefficient
  * \param uiPosY Y coordinate of the last significant coefficient
+ * \param component colour component ID
  * \returns cost of last significant coefficient
  */
@@ -2239,9 +2981,12 @@
 */
 __inline Double TComTrQuant::xGetRateLast   ( const UInt                      uiPosX,
-                                              const UInt                      uiPosY ) const
+                                              const UInt                      uiPosY,
+                                              const ComponentID               component  ) const
 {
   UInt uiCtxX   = g_uiGroupIdx[uiPosX];
   UInt uiCtxY   = g_uiGroupIdx[uiPosY];
-  Double uiCost = m_pcEstBitsSbac->lastXBits[ uiCtxX ] + m_pcEstBitsSbac->lastYBits[ uiCtxY ];
+
+  Double uiCost = m_pcEstBitsSbac->lastXBits[toChannelType(component)][ uiCtxX ] + m_pcEstBitsSbac->lastYBits[toChannelType(component)][ uiCtxY ];
+
   if( uiCtxX > 3 )
   {
@@ -2255,11 +3000,4 @@
 }
 
- /** Calculates the cost for specific absolute transform level
- * \param uiAbsLevel scaled quantized level
- * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
- * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
- * \param ui16CtxBase current global offset for coeff_abs_level_greater1 and coeff_abs_level_greater2
- * \returns cost of given absolute transform level
- */
 __inline Double TComTrQuant::xGetRateSigCoef  ( UShort                          uiSignificance,
                                                 UShort                          ui16CtxNumSig ) const
@@ -2287,81 +3025,90 @@
 /** Context derivation process of coeff_abs_significant_flag
  * \param uiSigCoeffGroupFlag significance map of L1
- * \param uiBlkX column of current scan position
- * \param uiBlkY row of current scan position
- * \param uiLog2BlkSize log2 value of block size
+ * \param uiCGPosX column of current scan position
+ * \param uiCGPosY row of current scan position
+ * \param widthInGroups width of the block
+ * \param heightInGroups height of the block
  * \returns ctxInc for current scan position
  */
-UInt TComTrQuant::getSigCoeffGroupCtxInc  ( const UInt*               uiSigCoeffGroupFlag,
-                                           const UInt                      uiCGPosX,
-                                           const UInt                      uiCGPosY,
-                                           Int width, Int height)
-{
-  UInt uiRight = 0;
-  UInt uiLower = 0;
-
-  width >>= 2;
-  height >>= 2;
-  if( uiCGPosX < width - 1 )
-  {
-    uiRight = (uiSigCoeffGroupFlag[ uiCGPosY * width + uiCGPosX + 1 ] != 0);
-  }
-  if (uiCGPosY < height - 1 )
-  {
-    uiLower = (uiSigCoeffGroupFlag[ (uiCGPosY  + 1 ) * width + uiCGPosX ] != 0);
-  }
-  return (uiRight || uiLower);
-
-}
+UInt TComTrQuant::getSigCoeffGroupCtxInc  (const UInt*  uiSigCoeffGroupFlag,
+                                           const UInt   uiCGPosX,
+                                           const UInt   uiCGPosY,
+                                           const UInt   widthInGroups,
+                                           const UInt   heightInGroups)
+{
+  UInt sigRight = 0;
+  UInt sigLower = 0;
+
+  if (uiCGPosX < (widthInGroups  - 1))
+  {
+    sigRight = ((uiSigCoeffGroupFlag[ (uiCGPosY * widthInGroups) + uiCGPosX + 1 ] != 0) ? 1 : 0);
+  }
+  if (uiCGPosY < (heightInGroups - 1))
+  {
+    sigLower = ((uiSigCoeffGroupFlag[ (uiCGPosY + 1) * widthInGroups + uiCGPosX ] != 0) ? 1 : 0);
+  }
+
+  return ((sigRight + sigLower) != 0) ? 1 : 0;
+}
+
+
 /** set quantized matrix coefficient for encode
- * \param scalingList quantaized matrix address
+ * \param scalingList            quantized matrix address
+ * \param format                 chroma format
+ * \param maxLog2TrDynamicRange
+ * \param bitDepths              reference to bit depth array for all channels
  */
-Void TComTrQuant::setScalingList(TComScalingList *scalingList)
-{
-  UInt size,list;
-  UInt qp;
-
-  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
-  {
-    for(list = 0; list < g_scalingListNum[size]; list++)
-    {
-      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
+Void TComTrQuant::setScalingList(TComScalingList *scalingList, const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths)
+{
+  const Int minimumQp = 0;
+  const Int maximumQp = SCALING_LIST_REM_NUM;
+
+  for(UInt size = 0; size < SCALING_LIST_SIZE_NUM; size++)
+  {
+    for(UInt list = 0; list < SCALING_LIST_NUM; list++)
+    {
+      for(Int qp = minimumQp; qp < maximumQp; qp++)
       {
         xSetScalingListEnc(scalingList,list,size,qp);
+        xSetScalingListDec(*scalingList,list,size,qp);
+        setErrScaleCoeff(list,size,qp,maxLog2TrDynamicRange, bitDepths);
+      }
+    }
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param scalingList quantized matrix address
+ * \param format      chroma format
+ */
+Void TComTrQuant::setScalingListDec(const TComScalingList &scalingList)
+{
+  const Int minimumQp = 0;
+  const Int maximumQp = SCALING_LIST_REM_NUM;
+
+  for(UInt size = 0; size < SCALING_LIST_SIZE_NUM; size++)
+  {
+    for(UInt list = 0; list < SCALING_LIST_NUM; list++)
+    {
+      for(Int qp = minimumQp; qp < maximumQp; qp++)
+      {
         xSetScalingListDec(scalingList,list,size,qp);
-        setErrScaleCoeff(list,size,qp);
-      }
-    }
-  }
-}
-/** set quantized matrix coefficient for decode
- * \param scalingList quantaized matrix address
+      }
+    }
+  }
+}
+/** set error scale coefficients
+ * \param list                   list ID
+ * \param size                   
+ * \param qp                     quantization parameter
+ * \param maxLog2TrDynamicRange
+ * \param bitDepths              reference to bit depth array for all channels
  */
-Void TComTrQuant::setScalingListDec(TComScalingList *scalingList)
-{
-  UInt size,list;
-  UInt qp;
-
-  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
-  {
-    for(list = 0; list < g_scalingListNum[size]; list++)
-    {
-      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
-      {
-        xSetScalingListDec(scalingList,list,size,qp);
-      }
-    }
-  }
-}
-/** set error scale coefficients
- * \param list List ID
- * \param uiSize Size
- * \param uiQP Quantization parameter
- */
-Void TComTrQuant::setErrScaleCoeff(UInt list,UInt size, UInt qp)
-{
-
-  UInt uiLog2TrSize = g_aucConvertToBit[ g_scalingListSizeX[size] ] + 2;
-  Int bitDepth = (size < SCALING_LIST_32x32 && list != 0 && list != 3) ? g_bitDepthC : g_bitDepthY;
-  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - bitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+Void TComTrQuant::setErrScaleCoeff(UInt list, UInt size, Int qp, const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths)
+{
+  const UInt uiLog2TrSize = g_aucConvertToBit[ g_scalingListSizeX[size] ] + 2;
+  const ChannelType channelType = ((list == 0) || (list == MAX_NUM_COMPONENT)) ? CHANNEL_TYPE_LUMA : CHANNEL_TYPE_CHROMA;
+
+  const Int channelBitDepth    = bitDepths.recon[channelType];
+  const Int iTransformShift = getTransformShift(channelBitDepth, uiLog2TrSize, maxLog2TrDynamicRange[channelType]);  // Represents scaling through forward transform
 
   UInt i,uiMaxNumCoeff = g_scalingListSize[size];
@@ -2371,62 +3118,83 @@
   pdErrScale     = getErrScaleCoeff(list, size, qp);
 
-  Double dErrScale = (Double)(1<<SCALE_BITS);                              // Compensate for scaling of bitcount in Lagrange cost function
-  dErrScale = dErrScale*pow(2.0,-2.0*iTransformShift);                     // Compensate for scaling through forward transform
+  Double dErrScale = (Double)(1<<SCALE_BITS);                                // Compensate for scaling of bitcount in Lagrange cost function
+  dErrScale = dErrScale*pow(2.0,(-2.0*iTransformShift));                     // Compensate for scaling through forward transform
+
   for(i=0;i<uiMaxNumCoeff;i++)
   {
-    pdErrScale[i] = dErrScale / piQuantcoeff[i] / piQuantcoeff[i] / (1<<DISTORTION_PRECISION_ADJUSTMENT(2*(bitDepth-8)));
-  }
+    pdErrScale[i] =  dErrScale / piQuantcoeff[i] / piQuantcoeff[i] / (1 << DISTORTION_PRECISION_ADJUSTMENT(2 * (bitDepths.recon[channelType] - 8)));
+  }
+
+  getErrScaleCoeffNoScalingList(list, size, qp) = dErrScale / g_quantScales[qp] / g_quantScales[qp] / (1 << DISTORTION_PRECISION_ADJUSTMENT(2 * (bitDepths.recon[channelType] - 8)));
 }
 
 /** set quantized matrix coefficient for encode
+ * \param scalingList quantized matrix address
+ * \param listId List index
+ * \param sizeId size index
+ * \param qp Quantization parameter
+ * \param format chroma format
+ */
+Void TComTrQuant::xSetScalingListEnc(TComScalingList *scalingList, UInt listId, UInt sizeId, Int qp)
+{
+  UInt width  = g_scalingListSizeX[sizeId];
+  UInt height = g_scalingListSizeX[sizeId];
+  UInt ratio  = g_scalingListSizeX[sizeId]/min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]);
+  Int *quantcoeff;
+  Int *coeff  = scalingList->getScalingListAddress(sizeId,listId);
+  quantcoeff  = getQuantCoeff(listId, qp, sizeId);
+
+  Int quantScales = g_quantScales[qp];
+
+  processScalingListEnc(coeff,
+                        quantcoeff,
+                        (quantScales << LOG2_SCALING_LIST_NEUTRAL_VALUE),
+                        height, width, ratio,
+                        min(MAX_MATRIX_SIZE_NUM, (Int)g_scalingListSizeX[sizeId]),
+                        scalingList->getScalingListDC(sizeId,listId));
+}
+
+/** set quantized matrix coefficient for decode
  * \param scalingList quantaized matrix address
  * \param listId List index
  * \param sizeId size index
- * \param uiQP Quantization parameter
+ * \param qp Quantization parameter
+ * \param format chroma format
  */
-Void TComTrQuant::xSetScalingListEnc(TComScalingList *scalingList, UInt listId, UInt sizeId, UInt qp)
-{
-  UInt width = g_scalingListSizeX[sizeId];
+Void TComTrQuant::xSetScalingListDec(const TComScalingList &scalingList, UInt listId, UInt sizeId, Int qp)
+{
+  UInt width  = g_scalingListSizeX[sizeId];
   UInt height = g_scalingListSizeX[sizeId];
-  UInt ratio = g_scalingListSizeX[sizeId]/min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]);
-  Int *quantcoeff;
-  Int *coeff = scalingList->getScalingListAddress(sizeId,listId);
-  quantcoeff   = getQuantCoeff(listId, qp, sizeId);
-
-  processScalingListEnc(coeff,quantcoeff,g_quantScales[qp]<<4,height,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
-}
-/** set quantized matrix coefficient for decode
- * \param scalingList quantaized matrix address
- * \param list List index
- * \param size size index
- * \param uiQP Quantization parameter
- */
-Void TComTrQuant::xSetScalingListDec(TComScalingList *scalingList, UInt listId, UInt sizeId, UInt qp)
-{
-  UInt width = g_scalingListSizeX[sizeId];
-  UInt height = g_scalingListSizeX[sizeId];
-  UInt ratio = g_scalingListSizeX[sizeId]/min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]);
+  UInt ratio  = g_scalingListSizeX[sizeId]/min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]);
   Int *dequantcoeff;
-  Int *coeff = scalingList->getScalingListAddress(sizeId,listId);
+  const Int *coeff  = scalingList.getScalingListAddress(sizeId,listId);
 
   dequantcoeff = getDequantCoeff(listId, qp, sizeId);
-  processScalingListDec(coeff,dequantcoeff,g_invQuantScales[qp],height,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+
+  Int invQuantScale = g_invQuantScales[qp];
+
+  processScalingListDec(coeff,
+                        dequantcoeff,
+                        invQuantScale,
+                        height, width, ratio,
+                        min(MAX_MATRIX_SIZE_NUM, (Int)g_scalingListSizeX[sizeId]),
+                        scalingList.getScalingListDC(sizeId,listId));
 }
 
 /** set flat matrix value to quantized coefficient
  */
-Void TComTrQuant::setFlatScalingList()
-{
-  UInt size,list;
-  UInt qp;
-
-  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
-  {
-    for(list = 0; list <  g_scalingListNum[size]; list++)
-    {
-      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
+Void TComTrQuant::setFlatScalingList(const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths)
+{
+  const Int minimumQp = 0;
+  const Int maximumQp = SCALING_LIST_REM_NUM;
+
+  for(UInt size = 0; size < SCALING_LIST_SIZE_NUM; size++)
+  {
+    for(UInt list = 0; list < SCALING_LIST_NUM; list++)
+    {
+      for(Int qp = minimumQp; qp < maximumQp; qp++)
       {
         xsetFlatScalingList(list,size,qp);
-        setErrScaleCoeff(list,size,qp);
+        setErrScaleCoeff(list,size,qp,maxLog2TrDynamicRange, bitDepths);
       }
     }
@@ -2436,14 +3204,16 @@
 /** set flat matrix value to quantized coefficient
  * \param list List ID
- * \param uiQP Quantization parameter
- * \param uiSize Size
+ * \param size size index
+ * \param qp Quantization parameter
+ * \param format chroma format
  */
-Void TComTrQuant::xsetFlatScalingList(UInt list, UInt size, UInt qp)
+Void TComTrQuant::xsetFlatScalingList(UInt list, UInt size, Int qp)
 {
   UInt i,num = g_scalingListSize[size];
   Int *quantcoeff;
   Int *dequantcoeff;
-  Int quantScales = g_quantScales[qp];
-  Int invQuantScales = g_invQuantScales[qp]<<4;
+
+  Int quantScales    = g_quantScales   [qp];
+  Int invQuantScales = g_invQuantScales[qp] << 4;
 
   quantcoeff   = getQuantCoeff(list, qp, size);
@@ -2451,5 +3221,5 @@
 
   for(i=0;i<num;i++)
-  { 
+  {
     *quantcoeff++ = quantScales;
     *dequantcoeff++ = invQuantScales;
@@ -2469,13 +3239,12 @@
 Void TComTrQuant::processScalingListEnc( Int *coeff, Int *quantcoeff, Int quantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc)
 {
-  Int nsqth = (height < width) ? 4: 1; //height ratio for NSQT
-  Int nsqtw = (width < height) ? 4: 1; //width ratio for NSQT
   for(UInt j=0;j<height;j++)
   {
     for(UInt i=0;i<width;i++)
     {
-      quantcoeff[j*width + i] = quantScales / coeff[sizuNum * (j * nsqth / ratio) + i * nsqtw /ratio];
-    }
-  }
+      quantcoeff[j*width + i] = quantScales / coeff[sizuNum * (j / ratio) + i / ratio];
+    }
+  }
+
   if(ratio > 1)
   {
@@ -2483,4 +3252,5 @@
   }
 }
+
 /** set quantized matrix coefficient for decode
  * \param coeff quantaized matrix address
@@ -2493,5 +3263,5 @@
  * \param dc dc parameter
  */
-Void TComTrQuant::processScalingListDec( Int *coeff, Int *dequantcoeff, Int invQuantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc)
+Void TComTrQuant::processScalingListDec( const Int *coeff, Int *dequantcoeff, Int invQuantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc)
 {
   for(UInt j=0;j<height;j++)
@@ -2502,4 +3272,5 @@
     }
   }
+
   if(ratio > 1)
   {
@@ -2514,22 +3285,16 @@
   for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
   {
-    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
-    {
-      for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
-      {
-        m_quantCoef   [sizeId][listId][qp] = new Int [g_scalingListSize[sizeId]];
-        m_dequantCoef [sizeId][listId][qp] = new Int [g_scalingListSize[sizeId]];
+    for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+    {
+      for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
+      {
+        m_quantCoef   [sizeId][listId][qp] = new Int    [g_scalingListSize[sizeId]];
+        m_dequantCoef [sizeId][listId][qp] = new Int    [g_scalingListSize[sizeId]];
         m_errScale    [sizeId][listId][qp] = new Double [g_scalingListSize[sizeId]];
-      }
-    }
-  }
-  // alias list [1] as [3].
-  for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
-  {
-    m_quantCoef   [SCALING_LIST_32x32][3][qp] = m_quantCoef   [SCALING_LIST_32x32][1][qp];
-    m_dequantCoef [SCALING_LIST_32x32][3][qp] = m_dequantCoef [SCALING_LIST_32x32][1][qp];
-    m_errScale    [SCALING_LIST_32x32][3][qp] = m_errScale    [SCALING_LIST_32x32][1][qp];
-  }
-}
+      } // listID loop
+    }
+  }
+}
+
 /** destroy quantization matrix array
  */
@@ -2538,13 +3303,238 @@
   for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
   {
-    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
     {
       for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
       {
-        if(m_quantCoef   [sizeId][listId][qp]) delete [] m_quantCoef   [sizeId][listId][qp];
-        if(m_dequantCoef [sizeId][listId][qp]) delete [] m_dequantCoef [sizeId][listId][qp];
-        if(m_errScale    [sizeId][listId][qp]) delete [] m_errScale    [sizeId][listId][qp];
-      }
-    }
+        if(m_quantCoef[sizeId][listId][qp])
+        {
+          delete [] m_quantCoef[sizeId][listId][qp];
+        }
+        if(m_dequantCoef[sizeId][listId][qp])
+        {
+          delete [] m_dequantCoef[sizeId][listId][qp];
+        }
+        if(m_errScale[sizeId][listId][qp])
+        {
+          delete [] m_errScale[sizeId][listId][qp];
+        }
+      }
+    }
+  }
+}
+
+Void TComTrQuant::transformSkipQuantOneSample(TComTU &rTu, const ComponentID compID, const TCoeff resiDiff, TCoeff* pcCoeff, const UInt uiPos, const QpParam &cQP, const Bool bUseHalfRoundingPoint)
+{
+        TComDataCU    *pcCU                           = rTu.getCU();
+  const UInt           uiAbsPartIdx                   = rTu.GetAbsPartIdxTU();
+  const TComRectangle &rect                           = rTu.getRect(compID);
+  const UInt           uiWidth                        = rect.width;
+  const UInt           uiHeight                       = rect.height;
+  const Int            maxLog2TrDynamicRange          = pcCU->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(compID));
+  const Int            channelBitDepth                = pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+  const Int            iTransformShift                = getTransformShift(channelBitDepth, rTu.GetEquivalentLog2TrSize(compID), maxLog2TrDynamicRange);
+  const Int            scalingListType                = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+  const Bool           enableScalingLists             = getUseScalingList(uiWidth, uiHeight, true);
+  const Int            defaultQuantisationCoefficient = g_quantScales[cQP.rem];
+
+  assert( scalingListType < SCALING_LIST_NUM );
+  const Int *const piQuantCoeff = getQuantCoeff( scalingListType, cQP.rem, (rTu.GetEquivalentLog2TrSize(compID)-2) );
+
+
+  /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be
+  * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the
+  * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller)
+  * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result
+  */
+
+  const Int iQBits = QUANT_SHIFT + cQP.per + iTransformShift;
+  // QBits will be OK for any internal bit depth as the reduction in transform shift is balanced by an increase in Qp_per due to QpBDOffset
+
+  const Int iAdd = ( bUseHalfRoundingPoint ? 256 : (pcCU->getSlice()->getSliceType() == I_SLICE ? 171 : 85) ) << (iQBits - 9);
+
+  TCoeff transformedCoefficient;
+
+  // transform-skip
+  if (iTransformShift >= 0)
+  {
+    transformedCoefficient = resiDiff << iTransformShift;
+  }
+  else // for very high bit depths
+  {
+    const Int iTrShiftNeg  = -iTransformShift;
+    const Int offset       = 1 << (iTrShiftNeg - 1);
+    transformedCoefficient = ( resiDiff + offset ) >> iTrShiftNeg;
+  }
+
+  // quantization
+  const TCoeff iSign = (transformedCoefficient < 0 ? -1: 1);
+
+  const Int quantisationCoefficient = enableScalingLists ? piQuantCoeff[uiPos] : defaultQuantisationCoefficient;
+
+  const Int64 tmpLevel = (Int64)abs(transformedCoefficient) * quantisationCoefficient;
+
+  const TCoeff quantisedCoefficient = (TCoeff((tmpLevel + iAdd ) >> iQBits)) * iSign;
+
+  const TCoeff entropyCodingMinimum = -(1 << maxLog2TrDynamicRange);
+  const TCoeff entropyCodingMaximum =  (1 << maxLog2TrDynamicRange) - 1;
+  pcCoeff[ uiPos ] = Clip3<TCoeff>( entropyCodingMinimum, entropyCodingMaximum, quantisedCoefficient );
+}
+
+
+Void TComTrQuant::invTrSkipDeQuantOneSample( TComTU &rTu, ComponentID compID, TCoeff inSample, Pel &reconSample, const QpParam &cQP, UInt uiPos )
+{
+        TComDataCU    *pcCU               = rTu.getCU();
+  const UInt           uiAbsPartIdx       = rTu.GetAbsPartIdxTU();
+  const TComRectangle &rect               = rTu.getRect(compID);
+  const UInt           uiWidth            = rect.width;
+  const UInt           uiHeight           = rect.height;
+  const Int            QP_per             = cQP.per;
+  const Int            QP_rem             = cQP.rem;
+  const Int            maxLog2TrDynamicRange = pcCU->getSlice()->getSPS()->getMaxLog2TrDynamicRange(toChannelType(compID));
+#if O0043_BEST_EFFORT_DECODING
+  const Int            channelBitDepth    = pcCU->getSlice()->getSPS()->getStreamBitDepth(toChannelType(compID));
+#else
+  const Int            channelBitDepth    = pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+#endif
+  const Int            iTransformShift    = getTransformShift(channelBitDepth, rTu.GetEquivalentLog2TrSize(compID), maxLog2TrDynamicRange);
+  const Int            scalingListType    = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+  const Bool           enableScalingLists = getUseScalingList(uiWidth, uiHeight, true);
+  const UInt           uiLog2TrSize       = rTu.GetEquivalentLog2TrSize(compID);
+
+  assert( scalingListType < SCALING_LIST_NUM );
+
+  const Int rightShift = (IQUANT_SHIFT - (iTransformShift + QP_per)) + (enableScalingLists ? LOG2_SCALING_LIST_NEUTRAL_VALUE : 0);
+
+  const TCoeff transformMinimum = -(1 << maxLog2TrDynamicRange);
+  const TCoeff transformMaximum =  (1 << maxLog2TrDynamicRange) - 1;
+
+  // Dequantisation
+
+  TCoeff dequantisedSample;
+
+  if(enableScalingLists)
+  {
+    const UInt             dequantCoefBits     = 1 + IQUANT_SHIFT + SCALING_LIST_BITS;
+    const UInt             targetInputBitDepth = std::min<UInt>((maxLog2TrDynamicRange + 1), (((sizeof(Intermediate_Int) * 8) + rightShift) - dequantCoefBits));
+
+    const Intermediate_Int inputMinimum        = -(1 << (targetInputBitDepth - 1));
+    const Intermediate_Int inputMaximum        =  (1 << (targetInputBitDepth - 1)) - 1;
+
+    Int *piDequantCoef = getDequantCoeff(scalingListType,QP_rem,uiLog2TrSize-2);
+
+    if(rightShift > 0)
+    {
+      const Intermediate_Int iAdd      = 1 << (rightShift - 1);
+      const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, inSample));
+      const Intermediate_Int iCoeffQ   = ((Intermediate_Int(clipQCoef) * piDequantCoef[uiPos]) + iAdd ) >> rightShift;
+
+      dequantisedSample = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+    }
+    else
+    {
+      const Int              leftShift = -rightShift;
+      const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, inSample));
+      const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * piDequantCoef[uiPos]) << leftShift;
+
+      dequantisedSample = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+    }
+  }
+  else
+  {
+    const Int scale     =  g_invQuantScales[QP_rem];
+    const Int scaleBits =     (IQUANT_SHIFT + 1)   ;
+
+    const UInt             targetInputBitDepth = std::min<UInt>((maxLog2TrDynamicRange + 1), (((sizeof(Intermediate_Int) * 8) + rightShift) - scaleBits));
+    const Intermediate_Int inputMinimum        = -(1 << (targetInputBitDepth - 1));
+    const Intermediate_Int inputMaximum        =  (1 << (targetInputBitDepth - 1)) - 1;
+
+    if (rightShift > 0)
+    {
+      const Intermediate_Int iAdd      = 1 << (rightShift - 1);
+      const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, inSample));
+      const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * scale + iAdd) >> rightShift;
+
+      dequantisedSample = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+    }
+    else
+    {
+      const Int              leftShift = -rightShift;
+      const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, inSample));
+      const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * scale) << leftShift;
+
+      dequantisedSample = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+    }
+  }
+
+  // Inverse transform-skip
+
+  if (iTransformShift >= 0)
+  {
+    const TCoeff offset = iTransformShift==0 ? 0 : (1 << (iTransformShift - 1));
+    reconSample =  Pel(( dequantisedSample + offset ) >> iTransformShift);
+  }
+  else //for very high bit depths
+  {
+    const Int iTrShiftNeg = -iTransformShift;
+    reconSample = Pel(dequantisedSample << iTrShiftNeg);
+  }
+}
+
+
+Void TComTrQuant::crossComponentPrediction(       TComTU      & rTu,
+                                            const ComponentID   compID,
+                                            const Pel         * piResiL,
+                                            const Pel         * piResiC,
+                                                  Pel         * piResiT,
+                                            const Int           width,
+                                            const Int           height,
+                                            const Int           strideL,
+                                            const Int           strideC,
+                                            const Int           strideT,
+                                            const Bool          reverse )
+{
+  const Pel *pResiL = piResiL;
+  const Pel *pResiC = piResiC;
+        Pel *pResiT = piResiT;
+
+  TComDataCU *pCU = rTu.getCU();
+  const Int alpha = pCU->getCrossComponentPredictionAlpha( rTu.GetAbsPartIdxTU( compID ), compID );
+  const Int diffBitDepth = pCU->getSlice()->getSPS()->getDifferentialLumaChromaBitDepth();
+
+  for( Int y = 0; y < height; y++ )
+  {
+    if (reverse)
+    {
+      // A constraint is to be added to the HEVC Standard to limit the size of pResiL and pResiC at this point.
+      // The likely form of the constraint is to either restrict the values to CoeffMin to CoeffMax,
+      // or to be representable in a bitDepthY+4 or bitDepthC+4 signed integer.
+      //  The result of the constraint is that for 8/10/12bit profiles, the input values
+      //  can be represented within a 16-bit Pel-type.
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+      for( Int x = 0; x < width; x++ )
+      {
+        pResiT[x] = pResiC[x] + (( alpha * rightShift( pResiL[x], diffBitDepth) ) >> 3);
+      }
+#else
+      const Int minPel=std::numeric_limits<Pel>::min();
+      const Int maxPel=std::numeric_limits<Pel>::max();
+      for( Int x = 0; x < width; x++ )
+      {
+        pResiT[x] = Clip3<Int>(minPel, maxPel, pResiC[x] + (( alpha * rightShift<Int>(Int(pResiL[x]), diffBitDepth) ) >> 3));
+      }
+#endif
+    }
+    else
+    {
+      // Forward does not need clipping. Pel type should always be big enough.
+      for( Int x = 0; x < width; x++ )
+      {
+        pResiT[x] = pResiC[x] - (( alpha * rightShift<Int>(Int(pResiL[x]), diffBitDepth) ) >> 3);
+      }
+    }
+
+    pResiL += strideL;
+    pResiC += strideC;
+    pResiT += strideT;
   }
 }
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTrQuant.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComTrQuant.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -42,4 +42,5 @@
 #include "TComYuv.h"
 #include "TComDataCU.h"
+#include "TComChromaFormat.h"
 #include "ContextTables.h"
 
@@ -59,13 +60,15 @@
 typedef struct
 {
-  Int significantCoeffGroupBits[NUM_SIG_CG_FLAG_CTX][2];
-  Int significantBits[NUM_SIG_FLAG_CTX][2];
-  Int lastXBits[32];
-  Int lastYBits[32];
-  Int m_greaterOneBits[NUM_ONE_FLAG_CTX][2];
-  Int m_levelAbsBits[NUM_ABS_FLAG_CTX][2];
-
-  Int blockCbpBits[3*NUM_QT_CBF_CTX][2];
-  Int blockRootCbpBits[4][2];
+  Int significantCoeffGroupBits[NUM_SIG_CG_FLAG_CTX][2 /*Flag = [0|1]*/];
+  Int significantBits[NUM_SIG_FLAG_CTX][2 /*Flag = [0|1]*/];
+  Int lastXBits[MAX_NUM_CHANNEL_TYPE][LAST_SIGNIFICANT_GROUPS];
+  Int lastYBits[MAX_NUM_CHANNEL_TYPE][LAST_SIGNIFICANT_GROUPS];
+  Int m_greaterOneBits[NUM_ONE_FLAG_CTX][2 /*Flag = [0|1]*/];
+  Int m_levelAbsBits[NUM_ABS_FLAG_CTX][2 /*Flag = [0|1]*/];
+
+  Int blockCbpBits[NUM_QT_CBF_CTX_SETS * NUM_QT_CBF_CTX_PER_SET][2 /*Flag = [0|1]*/];
+  Int blockRootCbpBits[4][2 /*Flag = [0|1]*/];
+
+  Int golombRiceAdaptationStatistics[RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS];
 } estBitsSbacStruct;
 
@@ -74,40 +77,21 @@
 // ====================================================================================================================
 
-/// QP class
-class QpParam
+/// QP struct
+struct QpParam
 {
-public:
-  QpParam();
-  
-  Int m_iQP;
-  Int m_iPer;
-  Int m_iRem;
-  
-public:
-  Int m_iBits;
-    
-  Void setQpParam( Int qpScaled )
-  {
-    m_iQP   = qpScaled;
-    m_iPer  = qpScaled / 6;
-    m_iRem  = qpScaled % 6;
-    m_iBits = QP_BITS + m_iPer;
-  }
-  
-  Void clear()
-  {
-    m_iQP   = 0;
-    m_iPer  = 0;
-    m_iRem  = 0;
-    m_iBits = 0;
-  }
-  
-  
-  Int per()   const { return m_iPer; }
-  Int rem()   const { return m_iRem; }
-  Int bits()  const { return m_iBits; }
-  
-  Int qp() {return m_iQP;}
-}; // END CLASS DEFINITION QpParam
+  Int Qp;
+  Int per;
+  Int rem;
+
+  QpParam(const Int           qpy,
+          const ChannelType   chType,
+          const Int           qpBdOffset,
+          const Int           chromaQPOffset,
+          const ChromaFormat  chFmt );
+
+  QpParam(const TComDataCU   &cu, const ComponentID compID);
+
+}; // END STRUCT DEFINITION QpParam
+
 
 /// transform and quantization class
@@ -117,95 +101,115 @@
   TComTrQuant();
   ~TComTrQuant();
-  
+
   // initialize class
-  Void init                 ( UInt uiMaxTrSize, Bool useRDOQ = false,  
-    Bool useRDOQTS = false,
-    Bool bEnc = false, Bool useTransformSkipFast = false
-#if ADAPTIVE_QP_SELECTION
-    , Bool bUseAdaptQpSelect = false
-#endif 
-    );
-  
+  Void init                 ( UInt  uiMaxTrSize,
+                              Bool useRDOQ                = false,
+                              Bool useRDOQTS              = false,
+#if T0196_SELECTIVE_RDOQ
+                              Bool useSelectiveRDOQ       = false,
+#endif
+                              Bool bEnc                   = false,
+                              Bool useTransformSkipFast   = false
+#if ADAPTIVE_QP_SELECTION
+                            , Bool bUseAdaptQpSelect      = false
+#endif
+                              );
+
   // transform & inverse transform functions
-  Void transformNxN( TComDataCU* pcCU, 
-                     Pel*        pcResidual, 
-                     UInt        uiStride, 
-                     TCoeff*     rpcCoeff, 
-#if ADAPTIVE_QP_SELECTION
-                     Int*&       rpcArlCoeff, 
-#endif
-                     UInt        uiWidth, 
-                     UInt        uiHeight, 
-                     UInt&       uiAbsSum, 
-                     TextType    eTType, 
-                     UInt        uiAbsPartIdx,
-                     Bool        useTransformSkip = false );
-
-  Void invtransformNxN( Bool transQuantBypass, TextType eText, UInt uiMode,Pel* rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight,  Int scalingListType, Bool useTransformSkip = false );
-  Void invRecurTransformNxN ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eTxt, Pel* rpcResidual, UInt uiAddr,   UInt uiStride, UInt uiWidth, UInt uiHeight,
-                             UInt uiMaxTrMode,  UInt uiTrMode, TCoeff* rpcCoeff );
-  
+  Void transformNxN(       TComTU         & rTu,
+                     const ComponentID      compID,
+                           Pel           *  pcResidual,
+                     const UInt             uiStride,
+                           TCoeff        *  rpcCoeff,
+#if ADAPTIVE_QP_SELECTION
+                           TCoeff        * rpcArlCoeff,
+#endif
+                           TCoeff         & uiAbsSum,
+                     const QpParam        & cQP
+                    );
+
+
+  Void invTransformNxN(      TComTU       & rTu,
+                       const ComponentID    compID,
+                             Pel         *pcResidual,
+                       const UInt           uiStride,
+                             TCoeff      *  pcCoeff,
+                       const QpParam      & cQP
+                             DEBUG_STRING_FN_DECLAREP(psDebug));
+
+  Void invRecurTransformNxN ( const ComponentID compID, TComYuv *pResidual, TComTU &rTu );
+
+  Void rdpcmNxN   ( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride, const QpParam& cQP, TCoeff* pcCoeff, TCoeff &uiAbsSum, RDPCMMode& rdpcmMode );
+  Void invRdpcmNxN( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride );
+
+  Void applyForwardRDPCM( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride, const QpParam& cQP, TCoeff* pcCoeff, TCoeff &uiAbsSum, const RDPCMMode mode );
+
   // Misc functions
-  Void setQPforQuant( Int qpy, TextType eTxtType, Int qpBdOffset, Int chromaQPOffset);
-
-#if RDOQ_CHROMA_LAMBDA 
-  Void setLambdas ( const Double lambdas[3] ) { for (Int component = 0; component < 3; component++) m_lambdas[component] = lambdas[component]; }
-  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_lambdas[0] : ((eTType == TEXT_CHROMA_U) ? m_lambdas[1] : m_lambdas[2]); }
+
+#if RDOQ_CHROMA_LAMBDA
+  Void setLambdas(const Double lambdas[MAX_NUM_COMPONENT]) { for (UInt component = 0; component < MAX_NUM_COMPONENT; component++) m_lambdas[component] = lambdas[component]; }
+  Void selectLambda(const ComponentID compIdx) { m_dLambda = m_lambdas[compIdx]; }
 #else
   Void setLambda(Double dLambda) { m_dLambda = dLambda;}
 #endif
   Void setRDOQOffset( UInt uiRDOQOffset ) { m_uiRDOQOffset = uiRDOQOffset; }
-  
+
   estBitsSbacStruct* m_pcEstBitsSbac;
-  
-  static Int      calcPatternSigCtx( const UInt* sigCoeffGroupFlag, UInt posXCG, UInt posYCG, Int width, Int height );
-
-  static Int      getSigCtxInc     (
-                                     Int                             patternSigCtx,
-                                     UInt                            scanIdx,
-                                     Int                             posX,
-                                     Int                             posY,
-                                     Int                             log2BlkSize,
-                                     TextType                        textureType
+
+  static Int      calcPatternSigCtx( const UInt* sigCoeffGroupFlag, UInt uiCGPosX, UInt uiCGPosY, UInt widthInGroups, UInt heightInGroups );
+
+  static Int      getSigCtxInc     ( Int                              patternSigCtx,
+                                     const TUEntropyCodingParameters &codingParameters,
+                                     const Int                        scanPosition,
+                                     const Int                        log2BlockWidth,
+                                     const Int                        log2BlockHeight,
+                                     const ChannelType                chanType
                                     );
-  static UInt getSigCoeffGroupCtxInc  ( const UInt*                   uiSigCoeffGroupFlag,
-                                       const UInt                       uiCGPosX,
-                                       const UInt                       uiCGPosY,
-                                       Int width, Int height);
+
+  static UInt getSigCoeffGroupCtxInc  (const UInt*  uiSigCoeffGroupFlag,
+                                       const UInt   uiCGPosX,
+                                       const UInt   uiCGPosY,
+                                       const UInt   widthInGroups,
+                                       const UInt   heightInGroups);
+
   Void initScalingList                      ();
   Void destroyScalingList                   ();
-  Void setErrScaleCoeff    ( UInt list, UInt size, UInt qp);
-  Double* getErrScaleCoeff ( UInt list, UInt size, UInt qp) {return m_errScale[size][list][qp];};    //!< get Error Scale Coefficent
-  Int* getQuantCoeff       ( UInt list, UInt qp, UInt size) {return m_quantCoef[size][list][qp];};   //!< get Quant Coefficent
-  Int* getDequantCoeff     ( UInt list, UInt qp, UInt size) {return m_dequantCoef[size][list][qp];}; //!< get DeQuant Coefficent
+  Void setErrScaleCoeff    ( UInt list, UInt size, Int qp, const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths );
+  Double* getErrScaleCoeff              ( UInt list, UInt size, Int qp ) { return m_errScale             [size][list][qp]; };  //!< get Error Scale Coefficent
+  Double& getErrScaleCoeffNoScalingList ( UInt list, UInt size, Int qp ) { return m_errScaleNoScalingList[size][list][qp]; };  //!< get Error Scale Coefficent
+  Int* getQuantCoeff                    ( UInt list, Int qp, UInt size ) { return m_quantCoef            [size][list][qp]; };  //!< get Quant Coefficent
+  Int* getDequantCoeff                  ( UInt list, Int qp, UInt size ) { return m_dequantCoef          [size][list][qp]; };  //!< get DeQuant Coefficent
   Void setUseScalingList   ( Bool bUseScalingList){ m_scalingListEnabledFlag = bUseScalingList; };
-  Bool getUseScalingList   (){ return m_scalingListEnabledFlag; };
-  Void setFlatScalingList  ();
-  Void xsetFlatScalingList ( UInt list, UInt size, UInt qp);
-  Void xSetScalingListEnc  ( TComScalingList *scalingList, UInt list, UInt size, UInt qp);
-  Void xSetScalingListDec  ( TComScalingList *scalingList, UInt list, UInt size, UInt qp);
-  Void setScalingList      ( TComScalingList *scalingList);
-  Void setScalingListDec   ( TComScalingList *scalingList);
+  Bool getUseScalingList   (const UInt width, const UInt height, const Bool isTransformSkip){ return m_scalingListEnabledFlag && (!isTransformSkip || ((width == 4) && (height == 4))); };
+  Void setFlatScalingList  (const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths);
+  Void xsetFlatScalingList ( UInt list, UInt size, Int qp);
+  Void xSetScalingListEnc  ( TComScalingList *scalingList, UInt list, UInt size, Int qp);
+  Void xSetScalingListDec  ( const TComScalingList &scalingList, UInt list, UInt size, Int qp);
+  Void setScalingList      ( TComScalingList *scalingList, const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths);
+  Void setScalingListDec   ( const TComScalingList &scalingList);
   Void processScalingListEnc( Int *coeff, Int *quantcoeff, Int quantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc);
-  Void processScalingListDec( Int *coeff, Int *dequantcoeff, Int invQuantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc);
+  Void processScalingListDec( const Int *coeff, Int *dequantcoeff, Int invQuantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc);
 #if ADAPTIVE_QP_SELECTION
   Void    initSliceQpDelta() ;
   Void    storeSliceQpNext(TComSlice* pcSlice);
   Void    clearSliceARLCnt();
-  Int     getQpDelta(Int qp) { return m_qpDelta[qp]; } 
-  Int*    getSliceNSamples(){ return m_sliceNsamples ;} 
+  Int     getQpDelta(Int qp) { return m_qpDelta[qp]; }
+  Int*    getSliceNSamples(){ return m_sliceNsamples ;}
   Double* getSliceSumC()    { return m_sliceSumC; }
 #endif
+  Void transformSkipQuantOneSample(TComTU &rTu, const ComponentID compID, const TCoeff resiDiff, TCoeff* pcCoeff, const UInt uiPos, const QpParam &cQP, const Bool bUseHalfRoundingPoint);
+  Void invTrSkipDeQuantOneSample(TComTU &rTu, ComponentID compID, TCoeff pcCoeff, Pel &reconSample, const QpParam &cQP, UInt uiPos );
+
 protected:
 #if ADAPTIVE_QP_SELECTION
-  Int     m_qpDelta[MAX_QP+1]; 
-  Int     m_sliceNsamples[LEVEL_RANGE+1];  
-  Double  m_sliceSumC[LEVEL_RANGE+1] ;  
-#endif
-  Int*    m_plTempCoeff;
-  
-  QpParam  m_cQP;
+  Int     m_qpDelta[MAX_QP+1];
+  Int     m_sliceNsamples[LEVEL_RANGE+1];
+  Double  m_sliceSumC[LEVEL_RANGE+1] ;
+#endif
+  TCoeff* m_plTempCoeff;
+
+//  QpParam  m_cQP; - removed - placed on the stack.
 #if RDOQ_CHROMA_LAMBDA
-  Double   m_lambdas[3];
+  Double   m_lambdas[MAX_NUM_COMPONENT];
 #endif
   Double   m_dLambda;
@@ -215,86 +219,120 @@
   Bool     m_useRDOQ;
   Bool     m_useRDOQTS;
+#if T0196_SELECTIVE_RDOQ
+  Bool     m_useSelectiveRDOQ;
+#endif
 #if ADAPTIVE_QP_SELECTION
   Bool     m_bUseAdaptQpSelect;
 #endif
   Bool     m_useTransformSkipFast;
+
   Bool     m_scalingListEnabledFlag;
-  Int      *m_quantCoef      [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of quantization matrix coefficient 4x4
-  Int      *m_dequantCoef    [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of dequantization matrix coefficient 4x4
-  Double   *m_errScale       [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of quantization matrix coefficient 4x4
+
+  Int      *m_quantCoef            [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of quantization matrix coefficient 4x4
+  Int      *m_dequantCoef          [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of dequantization matrix coefficient 4x4
+  Double   *m_errScale             [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of quantization matrix coefficient 4x4
+  Double    m_errScaleNoScalingList[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of quantization matrix coefficient 4x4
+
 private:
   // forward Transform
-  Void xT   (Int bitDepth, UInt uiMode,Pel* pResidual, UInt uiStride, Int* plCoeff, Int iWidth, Int iHeight );
-  
+  Void xT   ( const Int channelBitDepth, Bool useDST, Pel* piBlkResi, UInt uiStride, TCoeff* psCoeff, Int iWidth, Int iHeight, const Int maxLog2TrDynamicRange );
+
   // skipping Transform
-  Void xTransformSkip (Int bitDepth, Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int width, Int height );
-
-  Void signBitHidingHDQ( TCoeff* pQCoef, TCoeff* pCoef, UInt const *scan, Int* deltaU, Int width, Int height );
+  Void xTransformSkip ( Pel* piBlkResi, UInt uiStride, TCoeff* psCoeff, TComTU &rTu, const ComponentID component );
+
+  Void signBitHidingHDQ( TCoeff* pQCoef, TCoeff* pCoef, TCoeff* deltaU, const TUEntropyCodingParameters &codingParameters, const Int maxLog2TrDynamicRange );
 
   // quantization
-  Void xQuant( TComDataCU* pcCU, 
-               Int*        pSrc, 
-               TCoeff*     pDes, 
-#if ADAPTIVE_QP_SELECTION
-               Int*&       pArlDes,
-#endif
-               Int         iWidth, 
-               Int         iHeight, 
-               UInt&       uiAcSum, 
-               TextType    eTType, 
-               UInt        uiAbsPartIdx );
+  Void xQuant(       TComTU       &rTu,
+                     TCoeff      * pSrc,
+                     TCoeff      * pDes,
+#if ADAPTIVE_QP_SELECTION
+                     TCoeff      *pArlDes,
+#endif
+                     TCoeff       &uiAbsSum,
+               const ComponentID   compID,
+               const QpParam      &cQP );
+
+#if T0196_SELECTIVE_RDOQ
+  Bool xNeedRDOQ(    TComTU       &rTu,
+                     TCoeff      * pSrc,
+               const ComponentID   compID,
+               const QpParam      &cQP );
+#endif
 
   // RDOQ functions
-  
-  Void           xRateDistOptQuant ( TComDataCU*                     pcCU,
-                                     Int*                            plSrcCoeff,
-                                     TCoeff*                         piDstCoeff,
-#if ADAPTIVE_QP_SELECTION
-                                     Int*&                           piArlDstCoeff,
-#endif
-                                     UInt                            uiWidth,
-                                     UInt                            uiHeight,
-                                     UInt&                           uiAbsSum,
-                                     TextType                        eTType,
-                                     UInt                            uiAbsPartIdx );
-__inline UInt              xGetCodedLevel  ( Double&                         rd64CodedCost,
-                                             Double&                         rd64CodedCost0,
-                                             Double&                         rd64CodedCostSig,
-                                             Int                             lLevelDouble,
-                                             UInt                            uiMaxAbsLevel,
-                                             UShort                          ui16CtxNumSig,
-                                             UShort                          ui16CtxNumOne,
-                                             UShort                          ui16CtxNumAbs,
-                                             UShort                          ui16AbsGoRice,
-                                             UInt                            c1Idx,  
-                                             UInt                            c2Idx,  
-                                             Int                             iQBits,
-                                             Double                          dTemp,
-                                             Bool                            bLast        ) const;
-__inline Int xGetICRate  ( UInt                            uiAbsLevel,
-                           UShort                          ui16CtxNumOne,
-                           UShort                          ui16CtxNumAbs,
-                           UShort                          ui16AbsGoRice
-                         , UInt                            c1Idx,
-                           UInt                            c2Idx
-                         ) const;
-  __inline Double xGetRateLast     ( const UInt                      uiPosX,
-                                     const UInt                      uiPosY ) const;
-  __inline Double xGetRateSigCoeffGroup (  UShort                    uiSignificanceCoeffGroup,
-                                     UShort                          ui16CtxNumSig ) const;
-  __inline Double xGetRateSigCoef (  UShort                          uiSignificance,
-                                     UShort                          ui16CtxNumSig ) const;
-  __inline Double xGetICost        ( Double                          dRate         ) const; 
-  __inline Double xGetIEPRate      (                                               ) const;
-  
-  
+
+  Void           xRateDistOptQuant (       TComTU       &rTu,
+                                           TCoeff      * plSrcCoeff,
+                                           TCoeff      * piDstCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                           TCoeff      *piArlDstCoeff,
+#endif
+                                           TCoeff       &uiAbsSum,
+                                     const ComponentID   compID,
+                                     const QpParam      &cQP );
+
+__inline UInt              xGetCodedLevel  ( Double&          rd64CodedCost,
+                                             Double&          rd64CodedCost0,
+                                             Double&          rd64CodedCostSig,
+                                             Intermediate_Int lLevelDouble,
+                                             UInt             uiMaxAbsLevel,
+                                             UShort           ui16CtxNumSig,
+                                             UShort           ui16CtxNumOne,
+                                             UShort           ui16CtxNumAbs,
+                                             UShort           ui16AbsGoRice,
+                                             UInt             c1Idx,
+                                             UInt             c2Idx,
+                                             Int              iQBits,
+                                             Double           errorScale,
+                                             Bool             bLast,
+                                             Bool             useLimitedPrefixLength,
+                                             const Int        maxLog2TrDynamicRange
+                                             ) const;
+
+
+  __inline Int xGetICRate  ( const UInt   uiAbsLevel,
+                             const UShort ui16CtxNumOne,
+                             const UShort ui16CtxNumAbs,
+                             const UShort ui16AbsGoRice,
+                             const UInt   c1Idx,
+                             const UInt   c2Idx,
+                             const Bool   useLimitedPrefixLength,
+                             const Int maxLog2TrDynamicRange
+                           ) const;
+
+  __inline Double xGetRateLast         ( const UInt uiPosX, const UInt uiPosY, const ComponentID component ) const;
+  __inline Double xGetRateSigCoeffGroup( UShort uiSignificanceCoeffGroup, UShort ui16CtxNumSig             ) const;
+  __inline Double xGetRateSigCoef      ( UShort uiSignificance,           UShort ui16CtxNumSig             ) const;
+  __inline Double xGetICost            ( Double dRate                                                      ) const;
+  __inline Double xGetIEPRate          (                                                                   ) const;
+
+
   // dequantization
-  Void xDeQuant(Int bitDepth, const TCoeff* pSrc, Int* pDes, Int iWidth, Int iHeight, Int scalingListType );
-  
+  Void xDeQuant(       TComTU       &rTu,
+                 const TCoeff      * pSrc,
+                       TCoeff      * pDes,
+                 const ComponentID   compID,
+                 const QpParam      &cQP );
+
   // inverse transform
-  Void xIT    (Int bitDepth, UInt uiMode, Int* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight );
-  
+  Void xIT    ( const Int channelBitDepth, Bool useDST, TCoeff* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight, const Int maxLog2TrDynamicRange );
+
   // inverse skipping transform
-  Void xITransformSkip (Int bitDepth, Int* plCoef, Pel* pResidual, UInt uiStride, Int width, Int height );
+  Void xITransformSkip ( TCoeff* plCoef, Pel* pResidual, UInt uiStride, TComTU &rTu, const ComponentID component );
+
+public:
+  static Void crossComponentPrediction(      TComTU      &rTu,
+                                       const ComponentID  compID,
+                                       const Pel         *piResiL,
+                                       const Pel         *piResiC,
+                                             Pel         *piResiT,
+                                       const Int          width,
+                                       const Int          height,
+                                       const Int          strideL,
+                                       const Int          strideC,
+                                       const Int          strideT,
+                                       const Bool         reverse);
+
 };// END CLASS DEFINITION TComTrQuant
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,24 +37,20 @@
 
 // Include files
-#include "TComSlice.h"
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComPic.h"
+#include "TComInterpolationFilter.h"
 #include "TComWeightPrediction.h"
-#include "TComInterpolationFilter.h"
-
-static inline Pel weightBidirY( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset)
-{
-  return ClipY( ( (w0*(P0 + IF_INTERNAL_OFFS) + w1*(P1 + IF_INTERNAL_OFFS) + round + (offset << (shift-1))) >> shift ) );
-}
-static inline Pel weightBidirC( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset)
-{
-  return ClipC( ( (w0*(P0 + IF_INTERNAL_OFFS) + w1*(P1 + IF_INTERNAL_OFFS) + round + (offset << (shift-1))) >> shift ) );
-}
-
-static inline Pel weightUnidirY( Int w0, Pel P0, Int round, Int shift, Int offset)
-{
-  return ClipY( ( (w0*(P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset );
-}
-static inline Pel weightUnidirC( Int w0, Pel P0, Int round, Int shift, Int offset)
-{
-  return ClipC( ( (w0*(P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset );
+
+
+static inline Pel weightBidir( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset, Int clipBD)
+{
+  return ClipBD( ( (w0*(P0 + IF_INTERNAL_OFFS) + w1*(P1 + IF_INTERNAL_OFFS) + round + (offset << (shift-1))) >> shift ), clipBD );
+}
+
+
+static inline Pel weightUnidir( Int w0, Pel P0, Int round, Int shift, Int offset, Int clipBD)
+{
+  return ClipBD( ( (w0*(P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset, clipBD );
 }
 
@@ -62,221 +58,145 @@
 // Class definition
 // ====================================================================================================================
+
 TComWeightPrediction::TComWeightPrediction()
 {
 }
 
-/** weighted averaging for bi-pred
- * \param TComYuv* pcYuvSrc0
- * \param TComYuv* pcYuvSrc1
- * \param iPartUnitIdx
- * \param iWidth
- * \param iHeight
- * \param wpScalingParam *wp0
- * \param wpScalingParam *wp1
- * \param TComYuv* rpcYuvDst
- * \returns Void
- */
-Void TComWeightPrediction::addWeightBi( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, wpScalingParam *wp1, TComYuv* rpcYuvDst, Bool bRound )
-{
-  Int x, y;
-
-  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
-  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
-  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
-  
-  Pel* pSrcY1  = pcYuvSrc1->getLumaAddr( iPartUnitIdx );
-  Pel* pSrcU1  = pcYuvSrc1->getCbAddr  ( iPartUnitIdx );
-  Pel* pSrcV1  = pcYuvSrc1->getCrAddr  ( iPartUnitIdx );
-  
-  Pel* pDstY   = rpcYuvDst->getLumaAddr( iPartUnitIdx );
-  Pel* pDstU   = rpcYuvDst->getCbAddr  ( iPartUnitIdx );
-  Pel* pDstV   = rpcYuvDst->getCrAddr  ( iPartUnitIdx );
-  
-  // Luma : --------------------------------------------
-  Int w0      = wp0[0].w;
-  Int offset  = wp0[0].offset;
-  Int shiftNum = IF_INTERNAL_PREC - g_bitDepthY;
-  Int shift   = wp0[0].shift + shiftNum;
-  Int round   = shift?(1<<(shift-1)) * bRound:0;
-  Int w1      = wp1[0].w;
-
-  UInt  iSrc0Stride = pcYuvSrc0->getStride();
-  UInt  iSrc1Stride = pcYuvSrc1->getStride();
-  UInt  iDstStride  = rpcYuvDst->getStride();
-  for ( y = iHeight-1; y >= 0; y-- )
-  {
-    for ( x = iWidth-1; x >= 0; )
-    {
-      // note: luma min width is 4
-      pDstY[x] = weightBidirY(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
-      pDstY[x] = weightBidirY(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
-      pDstY[x] = weightBidirY(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
-      pDstY[x] = weightBidirY(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
-    }
-    pSrcY0 += iSrc0Stride;
-    pSrcY1 += iSrc1Stride;
-    pDstY  += iDstStride;
-  }
-
-  
-  // Chroma U : --------------------------------------------
-  w0      = wp0[1].w;
-  offset  = wp0[1].offset;
-  shiftNum = IF_INTERNAL_PREC - g_bitDepthC;
-  shift   = wp0[1].shift + shiftNum;
-  round   = shift?(1<<(shift-1)):0;
-  w1      = wp1[1].w;
-
-  iSrc0Stride = pcYuvSrc0->getCStride();
-  iSrc1Stride = pcYuvSrc1->getCStride();
-  iDstStride  = rpcYuvDst->getCStride();
-  
-  iWidth  >>=1;
-  iHeight >>=1;
-  
-  for ( y = iHeight-1; y >= 0; y-- )
-  {
-    for ( x = iWidth-1; x >= 0; )
-    {
-      // note: chroma min width is 2
-      pDstU[x] = weightBidirC(w0,pSrcU0[x], w1,pSrcU1[x], round, shift, offset); x--;
-      pDstU[x] = weightBidirC(w0,pSrcU0[x], w1,pSrcU1[x], round, shift, offset); x--;
-    }
-    pSrcU0 += iSrc0Stride;
-    pSrcU1 += iSrc1Stride;
-    pDstU  += iDstStride;
-  }
-
-  // Chroma V : --------------------------------------------
-  w0      = wp0[2].w;
-  offset  = wp0[2].offset;
-  shift   = wp0[2].shift + shiftNum;
-  round   = shift?(1<<(shift-1)):0;
-  w1      = wp1[2].w;
-
-  for ( y = iHeight-1; y >= 0; y-- )
-  {
-    for ( x = iWidth-1; x >= 0; )
-    {
-      // note: chroma min width is 2
-      pDstV[x] = weightBidirC(w0,pSrcV0[x], w1,pSrcV1[x], round, shift, offset); x--;
-      pDstV[x] = weightBidirC(w0,pSrcV0[x], w1,pSrcV1[x], round, shift, offset); x--;
-    }
-    pSrcV0 += iSrc0Stride;
-    pSrcV1 += iSrc1Stride;
-    pDstV  += iDstStride;
-  }
-}
-
-/** weighted averaging for uni-pred
- * \param TComYuv* pcYuvSrc0
- * \param iPartUnitIdx
- * \param iWidth
- * \param iHeight
- * \param wpScalingParam *wp0
- * \param TComYuv* rpcYuvDst
- * \returns Void
- */
-Void TComWeightPrediction::addWeightUni( TComYuv* pcYuvSrc0, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, TComYuv* rpcYuvDst )
-{
-  Int x, y;
-  
-  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
-  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
-  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
-  
-  Pel* pDstY   = rpcYuvDst->getLumaAddr( iPartUnitIdx );
-  Pel* pDstU   = rpcYuvDst->getCbAddr  ( iPartUnitIdx );
-  Pel* pDstV   = rpcYuvDst->getCrAddr  ( iPartUnitIdx );
-  
-  // Luma : --------------------------------------------
-  Int w0      = wp0[0].w;
-  Int offset  = wp0[0].offset;
-  Int shiftNum = IF_INTERNAL_PREC - g_bitDepthY;
-  Int shift   = wp0[0].shift + shiftNum;
-  Int round   = shift?(1<<(shift-1)):0;
-  UInt  iSrc0Stride = pcYuvSrc0->getStride();
-  UInt  iDstStride  = rpcYuvDst->getStride();
-  
-  for ( y = iHeight-1; y >= 0; y-- )
-  {
-    for ( x = iWidth-1; x >= 0; )
-    {
-      // note: luma min width is 4
-      pDstY[x] = weightUnidirY(w0,pSrcY0[x], round, shift, offset); x--;
-      pDstY[x] = weightUnidirY(w0,pSrcY0[x], round, shift, offset); x--;
-      pDstY[x] = weightUnidirY(w0,pSrcY0[x], round, shift, offset); x--;
-      pDstY[x] = weightUnidirY(w0,pSrcY0[x], round, shift, offset); x--;
-    }
-    pSrcY0 += iSrc0Stride;
-    pDstY  += iDstStride;
-  }
-  
-  // Chroma U : --------------------------------------------
-  w0      = wp0[1].w;
-  offset  = wp0[1].offset;
-  shiftNum = IF_INTERNAL_PREC - g_bitDepthC;
-  shift   = wp0[1].shift + shiftNum;
-  round   = shift?(1<<(shift-1)):0;
-
-  iSrc0Stride = pcYuvSrc0->getCStride();
-  iDstStride  = rpcYuvDst->getCStride();
-  
-  iWidth  >>=1;
-  iHeight >>=1;
-  
-  for ( y = iHeight-1; y >= 0; y-- )
-  {
-    for ( x = iWidth-1; x >= 0; )
-    {
-      // note: chroma min width is 2
-      pDstU[x] = weightUnidirC(w0,pSrcU0[x], round, shift, offset); x--;
-      pDstU[x] = weightUnidirC(w0,pSrcU0[x], round, shift, offset); x--;
-    }
-    pSrcU0 += iSrc0Stride;
-    pDstU  += iDstStride;
-  }
-
-  // Chroma V : --------------------------------------------
-  w0      = wp0[2].w;
-  offset  = wp0[2].offset;
-  shift   = wp0[2].shift + shiftNum;
-  round   = shift?(1<<(shift-1)):0;
-
-  for ( y = iHeight-1; y >= 0; y-- )
-  {
-    for ( x = iWidth-1; x >= 0; )
-    {
-      // note: chroma min width is 2
-      pDstV[x] = weightUnidirC(w0,pSrcV0[x], round, shift, offset); x--;
-      pDstV[x] = weightUnidirC(w0,pSrcV0[x], round, shift, offset); x--;
-    }
-    pSrcV0 += iSrc0Stride;
-    pDstV  += iDstStride;
-  }
-}
+
+//! weighted averaging for bi-pred
+Void TComWeightPrediction::addWeightBi( const TComYuv              *pcYuvSrc0,
+                                        const TComYuv              *pcYuvSrc1,
+                                        const BitDepths            &bitDepths,
+                                        const UInt                  iPartUnitIdx,
+                                        const UInt                  uiWidth,
+                                        const UInt                  uiHeight,
+                                        const WPScalingParam *const wp0,
+                                        const WPScalingParam *const wp1,
+                                              TComYuv        *const rpcYuvDst,
+                                        const Bool                  bRoundLuma)
+{
+
+  const Bool enableRounding[MAX_NUM_COMPONENT]={ bRoundLuma, true, true };
+
+  const UInt numValidComponent = pcYuvSrc0->getNumberValidComponents();
+
+  for(Int componentIndex=0; componentIndex<numValidComponent; componentIndex++)
+  {
+    const ComponentID compID=ComponentID(componentIndex);
+
+    const Pel* pSrc0       = pcYuvSrc0->getAddr( compID,  iPartUnitIdx );
+    const Pel* pSrc1       = pcYuvSrc1->getAddr( compID,  iPartUnitIdx );
+          Pel* pDst        = rpcYuvDst->getAddr( compID,  iPartUnitIdx );
+
+    // Luma : --------------------------------------------
+    const Int  w0          = wp0[compID].w;
+    const Int  offset      = wp0[compID].offset;
+    const Int  clipBD      = bitDepths.recon[toChannelType(compID)];
+    const Int  shiftNum    = std::max<Int>(2, (IF_INTERNAL_PREC - clipBD));
+    const Int  shift       = wp0[compID].shift + shiftNum;
+    const Int  round       = (enableRounding[compID] && (shift > 0)) ? (1<<(shift-1)) : 0;
+    const Int  w1          = wp1[compID].w;
+    const UInt csx         = pcYuvSrc0->getComponentScaleX(compID);
+    const UInt csy         = pcYuvSrc0->getComponentScaleY(compID);
+    const Int  iHeight     = uiHeight>>csy;
+    const Int  iWidth      = uiWidth>>csx;
+
+    const UInt iSrc0Stride = pcYuvSrc0->getStride(compID);
+    const UInt iSrc1Stride = pcYuvSrc1->getStride(compID);
+    const UInt iDstStride  = rpcYuvDst->getStride(compID);
+
+    for ( Int y = iHeight-1; y >= 0; y-- )
+    {
+      // do it in batches of 4 (partial unroll)
+      Int x = iWidth-1;
+      for ( ; x >= 3; )
+      {
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD); x--;
+      }
+      for( ; x >= 0; x-- )
+      {
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD);
+      }
+
+      pSrc0 += iSrc0Stride;
+      pSrc1 += iSrc1Stride;
+      pDst  += iDstStride;
+    } // y loop
+  } // compID loop
+}
+
+
+//! weighted averaging for uni-pred
+Void TComWeightPrediction::addWeightUni( const TComYuv        *const pcYuvSrc0,
+                                         const BitDepths            &bitDepths,
+                                         const UInt                  iPartUnitIdx,
+                                         const UInt                  uiWidth,
+                                         const UInt                  uiHeight,
+                                         const WPScalingParam *const wp0,
+                                               TComYuv        *const pcYuvDst )
+{
+  const UInt numValidComponent = pcYuvSrc0->getNumberValidComponents();
+
+  for(Int componentIndex=0; componentIndex<numValidComponent; componentIndex++)
+  {
+    const ComponentID compID=ComponentID(componentIndex);
+
+    const Pel* pSrc0       = pcYuvSrc0->getAddr( compID,  iPartUnitIdx );
+          Pel* pDst        = pcYuvDst->getAddr( compID,  iPartUnitIdx );
+
+    // Luma : --------------------------------------------
+    const Int  w0          = wp0[compID].w;
+    const Int  offset      = wp0[compID].offset;
+    const Int  clipBD      = bitDepths.recon[toChannelType(compID)];
+    const Int  shiftNum    = std::max<Int>(2, (IF_INTERNAL_PREC - clipBD));
+    const Int  shift       = wp0[compID].shift + shiftNum;
+    const Int  round       = (shift > 0) ? (1<<(shift-1)) : 0;
+    const UInt iSrc0Stride = pcYuvSrc0->getStride(compID);
+    const UInt iDstStride  = pcYuvDst->getStride(compID);
+    const UInt csx         = pcYuvSrc0->getComponentScaleX(compID);
+    const UInt csy         = pcYuvSrc0->getComponentScaleY(compID);
+    const Int  iHeight     = uiHeight>>csy;
+    const Int  iWidth      = uiWidth>>csx;
+
+    for (Int y = iHeight-1; y >= 0; y-- )
+    {
+      Int x = iWidth-1;
+      for ( ; x >= 3; )
+      {
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD); x--;
+      }
+      for( ; x >= 0; x--)
+      {
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD);
+      }
+      pSrc0 += iSrc0Stride;
+      pDst  += iDstStride;
+    }
+  }
+}
+
 
 //=======================================================
 //  getWpScaling()
 //=======================================================
-/** derivation of wp tables
- * \param TComDataCU* pcCU
- * \param iRefIdx0
- * \param iRefIdx1
- * \param wpScalingParam *&wp0
- * \param wpScalingParam *&wp1
- * \param ibdi
- * \returns Void
- */
-Void TComWeightPrediction::getWpScaling( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1, wpScalingParam *&wp0, wpScalingParam *&wp1)
+//! derivation of wp tables
+Void TComWeightPrediction::getWpScaling(       TComDataCU *const pcCU,
+                                         const Int               iRefIdx0,
+                                         const Int               iRefIdx1,
+                                               WPScalingParam  *&wp0,
+                                               WPScalingParam  *&wp1)
 {
   assert(iRefIdx0 >= 0 || iRefIdx1 >= 0);
-  
-  TComSlice*      pcSlice       = pcCU->getSlice();
-  TComPPS*        pps           = pcCU->getSlice()->getPPS();
-  Bool            wpBiPred = pps->getWPBiPred();
-  wpScalingParam* pwp;
-  Bool            bBiDir        = (iRefIdx0>=0 && iRefIdx1>=0);
-  Bool            bUniDir       = !bBiDir;
+
+        TComSlice *const pcSlice  = pcCU->getSlice();
+  const Bool             wpBiPred = pcCU->getSlice()->getPPS()->getWPBiPred();
+  const Bool             bBiDir   = (iRefIdx0>=0 && iRefIdx1>=0);
+  const Bool             bUniDir  = !bBiDir;
 
   if ( bUniDir || wpBiPred )
@@ -305,13 +225,18 @@
   }
 
+  const UInt numValidComponent                    = pcCU->getPic()->getNumberValidComponents();
+  const Bool bUseHighPrecisionPredictionWeighting = pcSlice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
+
   if ( bBiDir )
   { // Bi-Dir case
-    for ( Int yuv=0 ; yuv<3 ; yuv++ )
-    {
-      Int bitDepth = yuv ? g_bitDepthC : g_bitDepthY;
+    for ( Int yuv=0 ; yuv<numValidComponent ; yuv++ )
+    {
+      const Int bitDepth            = pcSlice->getSPS()->getBitDepth(toChannelType(ComponentID(yuv)));
+      const Int offsetScalingFactor = bUseHighPrecisionPredictionWeighting ? 1 : (1 << (bitDepth-8));
+
       wp0[yuv].w      = wp0[yuv].iWeight;
-      wp0[yuv].o      = wp0[yuv].iOffset * (1 << (bitDepth-8));
       wp1[yuv].w      = wp1[yuv].iWeight;
-      wp1[yuv].o      = wp1[yuv].iOffset * (1 << (bitDepth-8));
+      wp0[yuv].o      = wp0[yuv].iOffset * offsetScalingFactor;
+      wp1[yuv].o      = wp1[yuv].iOffset * offsetScalingFactor;
       wp0[yuv].offset = wp0[yuv].o + wp1[yuv].o;
       wp0[yuv].shift  = wp0[yuv].uiLog2WeightDenom + 1;
@@ -324,10 +249,13 @@
   else
   {  // Unidir
-    pwp = (iRefIdx0>=0) ? wp0 : wp1 ;
-    for ( Int yuv=0 ; yuv<3 ; yuv++ )
-    {
-      Int bitDepth = yuv ? g_bitDepthC : g_bitDepthY;
+    WPScalingParam *const pwp = (iRefIdx0>=0) ? wp0 : wp1 ;
+
+    for ( Int yuv=0 ; yuv<numValidComponent ; yuv++ )
+    {
+      const Int bitDepth            = pcSlice->getSPS()->getBitDepth(toChannelType(ComponentID(yuv)));
+      const Int offsetScalingFactor = bUseHighPrecisionPredictionWeighting ? 1 : (1 << (bitDepth-8));
+
       pwp[yuv].w      = pwp[yuv].iWeight;
-      pwp[yuv].offset = pwp[yuv].iOffset * (1 << (bitDepth-8));
+      pwp[yuv].offset = pwp[yuv].iOffset * offsetScalingFactor;
       pwp[yuv].shift  = pwp[yuv].uiLog2WeightDenom;
       pwp[yuv].round  = (pwp[yuv].uiLog2WeightDenom>=1) ? (1 << (pwp[yuv].uiLog2WeightDenom-1)) : (0);
@@ -336,21 +264,20 @@
 }
 
-/** weighted prediction for bi-pred
- * \param TComDataCU* pcCU
- * \param TComYuv* pcYuvSrc0
- * \param TComYuv* pcYuvSrc1
- * \param iRefIdx0
- * \param iRefIdx1
- * \param uiPartIdx
- * \param iWidth
- * \param iHeight
- * \param TComYuv* rpcYuvDst
- * \returns Void
- */
-Void TComWeightPrediction::xWeightedPredictionBi( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* rpcYuvDst )
-{
-  wpScalingParam  *pwp0, *pwp1;
-  TComPPS         *pps = pcCU->getSlice()->getPPS();
-  assert( pps->getWPBiPred());
+
+//! weighted prediction for bi-pred
+Void TComWeightPrediction::xWeightedPredictionBi(       TComDataCU *const pcCU,
+                                                  const TComYuv    *const pcYuvSrc0,
+                                                  const TComYuv    *const pcYuvSrc1,
+                                                  const Int               iRefIdx0,
+                                                  const Int               iRefIdx1,
+                                                  const UInt              uiPartIdx,
+                                                  const Int               iWidth,
+                                                  const Int               iHeight,
+                                                        TComYuv          *rpcYuvDst )
+{
+  WPScalingParam  *pwp0;
+  WPScalingParam  *pwp1;
+
+  assert(pcCU->getSlice()->getPPS()->getWPBiPred());
 
   getWpScaling(pcCU, iRefIdx0, iRefIdx1, pwp0, pwp1);
@@ -358,13 +285,13 @@
   if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
   {
-    addWeightBi(pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight, pwp0, pwp1, rpcYuvDst );
+    addWeightBi(pcYuvSrc0, pcYuvSrc1, pcCU->getSlice()->getSPS()->getBitDepths(), uiPartIdx, iWidth, iHeight, pwp0, pwp1, rpcYuvDst );
   }
   else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
   {
-    addWeightUni( pcYuvSrc0, uiPartIdx, iWidth, iHeight, pwp0, rpcYuvDst );
+    addWeightUni( pcYuvSrc0, pcCU->getSlice()->getSPS()->getBitDepths(), uiPartIdx, iWidth, iHeight, pwp0, rpcYuvDst );
   }
   else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
   {
-    addWeightUni( pcYuvSrc1, uiPartIdx, iWidth, iHeight, pwp1, rpcYuvDst );
+    addWeightUni( pcYuvSrc1, pcCU->getSlice()->getSPS()->getBitDepths(), uiPartIdx, iWidth, iHeight, pwp1, rpcYuvDst );
   }
   else
@@ -374,19 +301,18 @@
 }
 
-/** weighted prediction for uni-pred
- * \param TComDataCU* pcCU
- * \param TComYuv* pcYuvSrc
- * \param uiPartAddr
- * \param iWidth
- * \param iHeight
- * \param eRefPicList
- * \param TComYuv*& rpcYuvPred
- * \param iPartIdx
- * \param iRefIdx
- * \returns Void
- */
-Void TComWeightPrediction::xWeightedPredictionUni( TComDataCU* pcCU, TComYuv* pcYuvSrc, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iRefIdx)
-{ 
-  wpScalingParam  *pwp, *pwpTmp;
+
+//! weighted prediction for uni-pred
+Void TComWeightPrediction::xWeightedPredictionUni(       TComDataCU *const pcCU,
+                                                   const TComYuv    *const pcYuvSrc,
+                                                   const UInt              uiPartAddr,
+                                                   const Int               iWidth,
+                                                   const Int               iHeight,
+                                                   const RefPicList        eRefPicList,
+                                                         TComYuv          *pcYuvPred,
+                                                   const Int               iRefIdx_input)
+{
+  WPScalingParam  *pwp, *pwpTmp;
+
+  Int iRefIdx=iRefIdx_input;
   if ( iRefIdx < 0 )
   {
@@ -403,6 +329,4 @@
     getWpScaling(pcCU, -1, iRefIdx, pwpTmp, pwp);
   }
-  addWeightUni( pcYuvSrc, uiPartAddr, iWidth, iHeight, pwp, rpcYuvPred );
-}
-
-
+  addWeightUni( pcYuvSrc, pcCU->getSlice()->getSPS()->getBitDepths(), uiPartAddr, iWidth, iHeight, pwp, pcYuvPred );
+}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,11 +39,10 @@
 #define __TCOMWEIGHTPREDICTION__
 
+#include "CommonDef.h"
 
-// Include files
-#include "TComPic.h"
-#include "TComMotionInfo.h"
-#include "TComPattern.h"
-#include "TComTrQuant.h"
-#include "TComInterpolationFilter.h"
+// forward declarations
+class  TComDataCU;
+class  TComYuv;
+struct WPScalingParam;
 
 // ====================================================================================================================
@@ -56,12 +55,48 @@
   TComWeightPrediction();
 
-  Void  getWpScaling( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1, wpScalingParam *&wp0 , wpScalingParam *&wp1);
+  Void  getWpScaling(                 TComDataCU     *const pcCU,
+                                const Int                   iRefIdx0,
+                                const Int                   iRefIdx1,
+                                      WPScalingParam      *&wp0,
+                                      WPScalingParam      *&wp1);
 
-  Void  addWeightBi( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, wpScalingParam *wp1, TComYuv* rpcYuvDst, Bool bRound=true );
-  Void  addWeightUni( TComYuv* pcYuvSrc0, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, TComYuv* rpcYuvDst );
+  Void addWeightBi(             const TComYuv              *pcYuvSrc0,
+                                const TComYuv              *pcYuvSrc1,
+                                const BitDepths            &bitDepths,
+                                const UInt                  iPartUnitIdx,
+                                const UInt                  uiWidth,
+                                const UInt                  uiHeight,
+                                const WPScalingParam *const wp0,
+                                const WPScalingParam *const wp1,
+                                      TComYuv        *const rpcYuvDst,
+                                const Bool                  bRoundLuma=true );
 
-  Void  xWeightedPredictionUni( TComDataCU* pcCU, TComYuv* pcYuvSrc, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iRefIdx=-1 );
-  Void  xWeightedPredictionBi( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* rpcYuvDst );
+  Void  addWeightUni(           const TComYuv        *const pcYuvSrc0,
+                                const BitDepths            &bitDepths,
+                                const UInt                  iPartUnitIdx,
+                                const UInt                  uiWidth,
+                                const UInt                  uiHeight,
+                                const WPScalingParam *const wp0,
+                                      TComYuv        *const rpcYuvDst );
+
+  Void  xWeightedPredictionUni(       TComDataCU     *const pcCU,
+                                const TComYuv        *const pcYuvSrc,
+                                const UInt                  uiPartAddr,
+                                const Int                   iWidth,
+                                const Int                   iHeight,
+                                const RefPicList            eRefPicList,
+                                      TComYuv              *pcYuvPred,
+                                const Int                   iRefIdx=-1 );
+
+  Void  xWeightedPredictionBi(        TComDataCU     *const pcCU,
+                                const TComYuv        *const pcYuvSrc0,
+                                const TComYuv        *const pcYuvSrc1,
+                                const Int                   iRefIdx0,
+                                const Int                   iRefIdx1,
+                                const UInt                  uiPartIdx,
+                                const Int                   iWidth,
+                                const Int                   iHeight,
+                                      TComYuv              *pcYuvDst );
 };
 
-#endif 
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComYuv.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComYuv.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -51,7 +51,8 @@
 TComYuv::TComYuv()
 {
-  m_apiBufY = NULL;
-  m_apiBufU = NULL;
-  m_apiBufV = NULL;
+  for(Int comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    m_apiBuf[comp] = NULL;
+  }
 }
 
@@ -60,16 +61,16 @@
 }
 
-Void TComYuv::create( UInt iWidth, UInt iHeight )
-{
-  // memory allocation
-  m_apiBufY  = (Pel*)xMalloc( Pel, iWidth*iHeight    );
-  m_apiBufU  = (Pel*)xMalloc( Pel, iWidth*iHeight >> 2 );
-  m_apiBufV  = (Pel*)xMalloc( Pel, iWidth*iHeight >> 2 );
-  
+Void TComYuv::create( UInt iWidth, UInt iHeight, ChromaFormat chromaFormatIDC )
+{
   // set width and height
   m_iWidth   = iWidth;
   m_iHeight  = iHeight;
-  m_iCWidth  = iWidth  >> 1;
-  m_iCHeight = iHeight >> 1;
+  m_chromaFormatIDC = chromaFormatIDC;
+
+  for(Int comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    // memory allocation
+    m_apiBuf[comp]  = (Pel*)xMalloc( Pel, getWidth(ComponentID(comp))*getHeight(ComponentID(comp)) );
+  }
 }
 
@@ -77,35 +78,48 @@
 {
   // memory free
-  xFree( m_apiBufY ); m_apiBufY = NULL;
-  xFree( m_apiBufU ); m_apiBufU = NULL;
-  xFree( m_apiBufV ); m_apiBufV = NULL;
+  for(Int comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    if (m_apiBuf[comp]!=NULL)
+    {
+      xFree( m_apiBuf[comp] );
+      m_apiBuf[comp] = NULL;
+    }
+  }
 }
 
 Void TComYuv::clear()
 {
-  ::memset( m_apiBufY, 0, ( m_iWidth  * m_iHeight  )*sizeof(Pel) );
-  ::memset( m_apiBufU, 0, ( m_iCWidth * m_iCHeight )*sizeof(Pel) );
-  ::memset( m_apiBufV, 0, ( m_iCWidth * m_iCHeight )*sizeof(Pel) );
-}
-
-Void TComYuv::copyToPicYuv   ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
-{
-  copyToPicLuma  ( pcPicYuvDst, iCuAddr, uiAbsZorderIdx, uiPartDepth, uiPartIdx );
-  copyToPicChroma( pcPicYuvDst, iCuAddr, uiAbsZorderIdx, uiPartDepth, uiPartIdx );
-}
-
-Void TComYuv::copyToPicLuma  ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
-{
-  Int  y, iWidth, iHeight;
-  iWidth  = m_iWidth >>uiPartDepth;
-  iHeight = m_iHeight>>uiPartDepth;
-  
-  Pel* pSrc     = getLumaAddr(uiPartIdx, iWidth);
-  Pel* pDst     = pcPicYuvDst->getLumaAddr ( iCuAddr, uiAbsZorderIdx );
-  
-  UInt  iSrcStride  = getStride();
-  UInt  iDstStride  = pcPicYuvDst->getStride();
-  
-  for ( y = iHeight; y != 0; y-- )
+  for(Int comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    if (m_apiBuf[comp]!=NULL)
+    {
+      ::memset( m_apiBuf[comp], 0, ( getWidth(ComponentID(comp)) * getHeight(ComponentID(comp))  )*sizeof(Pel) );
+    }
+  }
+}
+
+
+
+
+Void TComYuv::copyToPicYuv   ( TComPicYuv* pcPicYuvDst, const UInt ctuRsAddr, const UInt uiAbsZorderIdx, const UInt uiPartDepth, const UInt uiPartIdx ) const
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    copyToPicComponent  ( ComponentID(comp), pcPicYuvDst, ctuRsAddr, uiAbsZorderIdx, uiPartDepth, uiPartIdx );
+  }
+}
+
+Void TComYuv::copyToPicComponent  ( const ComponentID compID, TComPicYuv* pcPicYuvDst, const UInt ctuRsAddr, const UInt uiAbsZorderIdx, const UInt uiPartDepth, const UInt uiPartIdx ) const
+{
+  const Int iWidth  = getWidth(compID) >>uiPartDepth;
+  const Int iHeight = getHeight(compID)>>uiPartDepth;
+
+  const Pel* pSrc     = getAddr(compID, uiPartIdx, iWidth);
+        Pel* pDst     = pcPicYuvDst->getAddr ( compID, ctuRsAddr, uiAbsZorderIdx );
+
+  const UInt  iSrcStride  = getStride(compID);
+  const UInt  iDstStride  = pcPicYuvDst->getStride(compID);
+
+  for ( Int y = iHeight; y != 0; y-- )
   {
     ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
@@ -125,46 +139,28 @@
 }
 
-Void TComYuv::copyToPicChroma( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
-{
-  Int  y, iWidth, iHeight;
-  iWidth  = m_iCWidth >>uiPartDepth;
-  iHeight = m_iCHeight>>uiPartDepth;
-  
-  Pel* pSrcU      = getCbAddr(uiPartIdx, iWidth);
-  Pel* pSrcV      = getCrAddr(uiPartIdx, iWidth);
-  Pel* pDstU      = pcPicYuvDst->getCbAddr( iCuAddr, uiAbsZorderIdx );
-  Pel* pDstV      = pcPicYuvDst->getCrAddr( iCuAddr, uiAbsZorderIdx );
-  
-  UInt  iSrcStride = getCStride();
-  UInt  iDstStride = pcPicYuvDst->getCStride();
-  for ( y = iHeight; y != 0; y-- )
-  {
-    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(iWidth) );
-    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(iWidth) );
-    pSrcU += iSrcStride;
-    pSrcV += iSrcStride;
-    pDstU += iDstStride;
-    pDstV += iDstStride;
-  }
-}
-
-Void TComYuv::copyFromPicYuv   ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
-{
-  copyFromPicLuma  ( pcPicYuvSrc, iCuAddr, uiAbsZorderIdx );
-  copyFromPicChroma( pcPicYuvSrc, iCuAddr, uiAbsZorderIdx );
-}
-
-Void TComYuv::copyFromPicLuma  ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
-{
-  Int  y;
-  
-  Pel* pDst     = m_apiBufY;
-  Pel* pSrc     = pcPicYuvSrc->getLumaAddr ( iCuAddr, uiAbsZorderIdx );
-  
-  UInt  iDstStride  = getStride();
-  UInt  iSrcStride  = pcPicYuvSrc->getStride();
-  for ( y = m_iHeight; y != 0; y-- )
-  {
-    ::memcpy( pDst, pSrc, sizeof(Pel)*m_iWidth);
+
+
+
+Void TComYuv::copyFromPicYuv   ( const TComPicYuv* pcPicYuvSrc, const UInt ctuRsAddr, const UInt uiAbsZorderIdx )
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    copyFromPicComponent  ( ComponentID(comp), pcPicYuvSrc, ctuRsAddr, uiAbsZorderIdx );
+  }
+}
+
+Void TComYuv::copyFromPicComponent  ( const ComponentID compID, const TComPicYuv* pcPicYuvSrc, const UInt ctuRsAddr, const UInt uiAbsZorderIdx )
+{
+        Pel* pDst     = getAddr(compID);
+  const Pel* pSrc     = pcPicYuvSrc->getAddr ( compID, ctuRsAddr, uiAbsZorderIdx );
+
+  const UInt iDstStride  = getStride(compID);
+  const UInt iSrcStride  = pcPicYuvSrc->getStride(compID);
+  const Int  iWidth=getWidth(compID);
+  const Int  iHeight=getHeight(compID);
+
+  for (Int y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
     pDst += iDstStride;
     pSrc += iSrcStride;
@@ -172,44 +168,28 @@
 }
 
-Void TComYuv::copyFromPicChroma( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
-{
-  Int  y;
-  
-  Pel* pDstU      = m_apiBufU;
-  Pel* pDstV      = m_apiBufV;
-  Pel* pSrcU      = pcPicYuvSrc->getCbAddr( iCuAddr, uiAbsZorderIdx );
-  Pel* pSrcV      = pcPicYuvSrc->getCrAddr( iCuAddr, uiAbsZorderIdx );
-  
-  UInt  iDstStride = getCStride();
-  UInt  iSrcStride = pcPicYuvSrc->getCStride();
-  for ( y = m_iCHeight; y != 0; y-- )
-  {
-    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(m_iCWidth) );
-    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(m_iCWidth) );
-    pSrcU += iSrcStride;
-    pSrcV += iSrcStride;
-    pDstU += iDstStride;
-    pDstV += iDstStride;
-  }
-}
-
-Void TComYuv::copyToPartYuv( TComYuv* pcYuvDst, UInt uiDstPartIdx )
-{
-  copyToPartLuma  ( pcYuvDst, uiDstPartIdx );
-  copyToPartChroma( pcYuvDst, uiDstPartIdx );
-}
-
-Void TComYuv::copyToPartLuma( TComYuv* pcYuvDst, UInt uiDstPartIdx )
-{
-  Int  y;
-  
-  Pel* pSrc     = m_apiBufY;
-  Pel* pDst     = pcYuvDst->getLumaAddr( uiDstPartIdx );
-  
-  UInt  iSrcStride  = getStride();
-  UInt  iDstStride  = pcYuvDst->getStride();
-  for ( y = m_iHeight; y != 0; y-- )
-  {
-    ::memcpy( pDst, pSrc, sizeof(Pel)*m_iWidth);
+
+
+
+Void TComYuv::copyToPartYuv( TComYuv* pcYuvDst, const UInt uiDstPartIdx ) const
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    copyToPartComponent  ( ComponentID(comp), pcYuvDst, uiDstPartIdx );
+  }
+}
+
+Void TComYuv::copyToPartComponent( const ComponentID compID, TComYuv* pcYuvDst, const UInt uiDstPartIdx ) const
+{
+  const Pel* pSrc     = getAddr(compID);
+        Pel* pDst     = pcYuvDst->getAddr( compID, uiDstPartIdx );
+
+  const UInt iSrcStride  = getStride(compID);
+  const UInt iDstStride  = pcYuvDst->getStride(compID);
+  const Int  iWidth=getWidth(compID);
+  const Int  iHeight=getHeight(compID);
+
+  for (Int y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
     pDst += iDstStride;
     pSrc += iSrcStride;
@@ -217,46 +197,27 @@
 }
 
-Void TComYuv::copyToPartChroma( TComYuv* pcYuvDst, UInt uiDstPartIdx )
-{
-  Int  y;
-  
-  Pel* pSrcU      = m_apiBufU;
-  Pel* pSrcV      = m_apiBufV;
-  Pel* pDstU      = pcYuvDst->getCbAddr( uiDstPartIdx );
-  Pel* pDstV      = pcYuvDst->getCrAddr( uiDstPartIdx );
-  
-  UInt  iSrcStride = getCStride();
-  UInt  iDstStride = pcYuvDst->getCStride();
-  for ( y = m_iCHeight; y != 0; y-- )
-  {
-    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(m_iCWidth) );
-    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(m_iCWidth) );
-    pSrcU += iSrcStride;
-    pSrcV += iSrcStride;
-    pDstU += iDstStride;
-    pDstV += iDstStride;
-  }
-}
-
-Void TComYuv::copyPartToYuv( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
-{
-  copyPartToLuma  ( pcYuvDst, uiSrcPartIdx );
-  copyPartToChroma( pcYuvDst, uiSrcPartIdx );
-}
-
-Void TComYuv::copyPartToLuma( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
-{
-  Int  y;
-  
-  Pel* pSrc     = getLumaAddr(uiSrcPartIdx);
-  Pel* pDst     = pcYuvDst->getLumaAddr( 0 );
-  
-  UInt  iSrcStride  = getStride();
-  UInt  iDstStride  = pcYuvDst->getStride();
-  
-  UInt uiHeight = pcYuvDst->getHeight();
-  UInt uiWidth = pcYuvDst->getWidth();
-  
-  for ( y = uiHeight; y != 0; y-- )
+
+
+
+Void TComYuv::copyPartToYuv( TComYuv* pcYuvDst, const UInt uiSrcPartIdx ) const
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    copyPartToComponent  ( ComponentID(comp), pcYuvDst, uiSrcPartIdx );
+  }
+}
+
+Void TComYuv::copyPartToComponent( const ComponentID compID, TComYuv* pcYuvDst, const UInt uiSrcPartIdx ) const
+{
+  const Pel* pSrc     = getAddr(compID, uiSrcPartIdx);
+        Pel* pDst     = pcYuvDst->getAddr(compID, 0 );
+
+  const UInt  iSrcStride  = getStride(compID);
+  const UInt  iDstStride  = pcYuvDst->getStride(compID);
+
+  const UInt uiHeight = pcYuvDst->getHeight(compID);
+  const UInt uiWidth = pcYuvDst->getWidth(compID);
+
+  for ( UInt y = uiHeight; y != 0; y-- )
   {
     ::memcpy( pDst, pSrc, sizeof(Pel)*uiWidth);
@@ -266,52 +227,31 @@
 }
 
-Void TComYuv::copyPartToChroma( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
-{
-  Int  y;
-  
-  Pel* pSrcU      = getCbAddr( uiSrcPartIdx );
-  Pel* pSrcV      = getCrAddr( uiSrcPartIdx );
-  Pel* pDstU      = pcYuvDst->getCbAddr( 0 );
-  Pel* pDstV      = pcYuvDst->getCrAddr( 0 );
-  
-  UInt  iSrcStride = getCStride();
-  UInt  iDstStride = pcYuvDst->getCStride();
-  
-  UInt uiCHeight = pcYuvDst->getCHeight();
-  UInt uiCWidth = pcYuvDst->getCWidth();
-  
-  for ( y = uiCHeight; y != 0; y-- )
-  {
-    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(uiCWidth) );
-    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(uiCWidth) );
-    pSrcU += iSrcStride;
-    pSrcV += iSrcStride;
-    pDstU += iDstStride;
-    pDstV += iDstStride;
-  }
-}
-
-Void TComYuv::copyPartToPartYuv   ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
-{
-  copyPartToPartLuma   (pcYuvDst, uiPartIdx, iWidth, iHeight );
-  copyPartToPartChroma (pcYuvDst, uiPartIdx, iWidth>>1, iHeight>>1 );
-}
-
-Void TComYuv::copyPartToPartLuma  ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
-{
-  Pel* pSrc =           getLumaAddr(uiPartIdx);
-  Pel* pDst = pcYuvDst->getLumaAddr(uiPartIdx);
+
+
+
+Void TComYuv::copyPartToPartYuv   ( TComYuv* pcYuvDst, const UInt uiPartIdx, const UInt iWidth, const UInt iHeight ) const
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    copyPartToPartComponent   (ComponentID(comp), pcYuvDst, uiPartIdx, iWidth>>getComponentScaleX(ComponentID(comp)), iHeight>>getComponentScaleY(ComponentID(comp)) );
+  }
+}
+
+Void TComYuv::copyPartToPartComponent  ( const ComponentID compID, TComYuv* pcYuvDst, const UInt uiPartIdx, const UInt iWidthComponent, const UInt iHeightComponent ) const
+{
+  const Pel* pSrc =           getAddr(compID, uiPartIdx);
+        Pel* pDst = pcYuvDst->getAddr(compID, uiPartIdx);
   if( pSrc == pDst )
   {
     //th not a good idea
-    //th best would be to fix the caller 
+    //th best would be to fix the caller
     return ;
   }
-  
-  UInt  iSrcStride = getStride();
-  UInt  iDstStride = pcYuvDst->getStride();
-  for ( UInt y = iHeight; y != 0; y-- )
-  {
-    ::memcpy( pDst, pSrc, iWidth * sizeof(Pel) );
+
+  const UInt  iSrcStride = getStride(compID);
+  const UInt  iDstStride = pcYuvDst->getStride(compID);
+  for ( UInt y = iHeightComponent; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, iWidthComponent * sizeof(Pel) );
     pSrc += iSrcStride;
     pDst += iDstStride;
@@ -319,116 +259,261 @@
 }
 
-Void TComYuv::copyPartToPartChroma( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
-{
-  Pel*  pSrcU =           getCbAddr(uiPartIdx);
-  Pel*  pSrcV =           getCrAddr(uiPartIdx);
-  Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
-  Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
-  
-  if( pSrcU == pDstU && pSrcV == pDstV)
+
+
+
+Void TComYuv::copyPartToPartComponentMxN  ( const ComponentID compID, TComYuv* pcYuvDst, const TComRectangle &rect) const
+{
+  const Pel* pSrc =           getAddrPix( compID, rect.x0, rect.y0 );
+        Pel* pDst = pcYuvDst->getAddrPix( compID, rect.x0, rect.y0 );
+  if( pSrc == pDst )
   {
     //th not a good idea
-    //th best would be to fix the caller 
+    //th best would be to fix the caller
     return ;
   }
-  
-  UInt   iSrcStride = getCStride();
-  UInt   iDstStride = pcYuvDst->getCStride();
-  for ( UInt y = iHeight; y != 0; y-- )
-  {
-    ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
-    ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
-    pSrcU += iSrcStride;
-    pSrcV += iSrcStride;
-    pDstU += iDstStride;
-    pDstV += iDstStride;
-  }
-}
-
-Void TComYuv::copyPartToPartChroma( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight, UInt chromaId)
-{
-  if(chromaId == 0)
-  {
-    Pel*  pSrcU =           getCbAddr(uiPartIdx);
-    Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
-    if( pSrcU == pDstU)
-    {
-      return ;
-    }
-    UInt   iSrcStride = getCStride();
-    UInt   iDstStride = pcYuvDst->getCStride();
-    for ( UInt y = iHeight; y != 0; y-- )
-    {
-      ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
-      pSrcU += iSrcStride;
-      pDstU += iDstStride;
-    }
-  }
-  else if (chromaId == 1)
-  {
-    Pel*  pSrcV =           getCrAddr(uiPartIdx);
-    Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
-    if( pSrcV == pDstV)
-    {
-      return;
-    }
-    UInt   iSrcStride = getCStride();
-    UInt   iDstStride = pcYuvDst->getCStride();
-    for ( UInt y = iHeight; y != 0; y-- )
-    { 
-      ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
-      pSrcV += iSrcStride;
-      pDstV += iDstStride;
-    }
-  }
-  else
-  {
-    Pel*  pSrcU =           getCbAddr(uiPartIdx);
-    Pel*  pSrcV =           getCrAddr(uiPartIdx);
-    Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
-    Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
-    
-    if( pSrcU == pDstU && pSrcV == pDstV)
-    {
-      //th not a good idea
-      //th best would be to fix the caller 
-      return ;
-    }
-    UInt   iSrcStride = getCStride();
-    UInt   iDstStride = pcYuvDst->getCStride();
-    for ( UInt y = iHeight; y != 0; y-- )
-    {
-      ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
-      ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
-      pSrcU += iSrcStride;
-      pSrcV += iSrcStride;
-      pDstU += iDstStride;
-      pDstV += iDstStride;
-    }
-  }
-}
-
-Void TComYuv::addClip( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
-{
-  addClipLuma   ( pcYuvSrc0, pcYuvSrc1, uiTrUnitIdx, uiPartSize     );
-  addClipChroma ( pcYuvSrc0, pcYuvSrc1, uiTrUnitIdx, uiPartSize>>1  );
-}
-
-Void TComYuv::addClipLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+
+  const UInt  iSrcStride = getStride(compID);
+  const UInt  iDstStride = pcYuvDst->getStride(compID);
+  const UInt uiHeightComponent=rect.height;
+  const UInt uiWidthComponent=rect.width;
+  for ( UInt y = uiHeightComponent; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, uiWidthComponent * sizeof( Pel ) );
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+}
+
+
+
+
+Void TComYuv::addClip( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt uiTrUnitIdx, const UInt uiPartSize, const BitDepths &clipBitDepths )
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    const ComponentID compID=ComponentID(comp);
+    const Int uiPartWidth =uiPartSize>>getComponentScaleX(compID);
+    const Int uiPartHeight=uiPartSize>>getComponentScaleY(compID);
+
+    const Pel* pSrc0 = pcYuvSrc0->getAddr(compID, uiTrUnitIdx, uiPartWidth );
+    const Pel* pSrc1 = pcYuvSrc1->getAddr(compID, uiTrUnitIdx, uiPartWidth );
+          Pel* pDst  = getAddr(compID, uiTrUnitIdx, uiPartWidth );
+
+    const UInt iSrc0Stride = pcYuvSrc0->getStride(compID);
+    const UInt iSrc1Stride = pcYuvSrc1->getStride(compID);
+    const UInt iDstStride  = getStride(compID);
+    const Int clipbd = clipBitDepths.recon[toChannelType(compID)];
+#if O0043_BEST_EFFORT_DECODING
+    const Int bitDepthDelta = clipBitDepths.stream[toChannelType(compID)] - clipbd;
+#endif
+
+    for ( Int y = uiPartHeight-1; y >= 0; y-- )
+    {
+      for ( Int x = uiPartWidth-1; x >= 0; x-- )
+      {
+#if O0043_BEST_EFFORT_DECODING
+        pDst[x] = Pel(ClipBD<Int>( Int(pSrc0[x]) + rightShiftEvenRounding<Pel>(pSrc1[x], bitDepthDelta), clipbd));
+#else
+        pDst[x] = Pel(ClipBD<Int>( Int(pSrc0[x]) + Int(pSrc1[x]), clipbd));
+#endif
+      }
+      pSrc0 += iSrc0Stride;
+      pSrc1 += iSrc1Stride;
+      pDst  += iDstStride;
+    }
+  }
+}
+
+
+
+
+Void TComYuv::subtract( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt uiTrUnitIdx, const UInt uiPartSize )
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    const ComponentID compID=ComponentID(comp);
+    const Int uiPartWidth =uiPartSize>>getComponentScaleX(compID);
+    const Int uiPartHeight=uiPartSize>>getComponentScaleY(compID);
+
+    const Pel* pSrc0 = pcYuvSrc0->getAddr( compID, uiTrUnitIdx, uiPartWidth );
+    const Pel* pSrc1 = pcYuvSrc1->getAddr( compID, uiTrUnitIdx, uiPartWidth );
+          Pel* pDst  = getAddr( compID, uiTrUnitIdx, uiPartWidth );
+
+    const Int  iSrc0Stride = pcYuvSrc0->getStride(compID);
+    const Int  iSrc1Stride = pcYuvSrc1->getStride(compID);
+    const Int  iDstStride  = getStride(compID);
+
+    for (Int y = uiPartHeight-1; y >= 0; y-- )
+    {
+      for (Int x = uiPartWidth-1; x >= 0; x-- )
+      {
+        pDst[x] = pSrc0[x] - pSrc1[x];
+      }
+      pSrc0 += iSrc0Stride;
+      pSrc1 += iSrc1Stride;
+      pDst  += iDstStride;
+    }
+  }
+}
+
+
+
+
+Void TComYuv::addAvg( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt iPartUnitIdx, const UInt uiWidth, const UInt uiHeight, const BitDepths &clipBitDepths )
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    const ComponentID compID=ComponentID(comp);
+    const Pel* pSrc0  = pcYuvSrc0->getAddr( compID, iPartUnitIdx );
+    const Pel* pSrc1  = pcYuvSrc1->getAddr( compID, iPartUnitIdx );
+    Pel* pDst   = getAddr( compID, iPartUnitIdx );
+
+    const UInt  iSrc0Stride = pcYuvSrc0->getStride(compID);
+    const UInt  iSrc1Stride = pcYuvSrc1->getStride(compID);
+    const UInt  iDstStride  = getStride(compID);
+    const Int   clipbd      = clipBitDepths.recon[toChannelType(compID)];
+    const Int   shiftNum    = std::max<Int>(2, (IF_INTERNAL_PREC - clipbd)) + 1;
+    const Int   offset      = ( 1 << ( shiftNum - 1 ) ) + 2 * IF_INTERNAL_OFFS;
+
+    const Int   iWidth      = uiWidth  >> getComponentScaleX(compID);
+    const Int   iHeight     = uiHeight >> getComponentScaleY(compID);
+
+    if (iWidth&1)
+    {
+      assert(0);
+      exit(-1);
+    }
+    else if (iWidth&2)
+    {
+      for ( Int y = 0; y < iHeight; y++ )
+      {
+        for (Int x=0 ; x < iWidth; x+=2 )
+        {
+          pDst[ x + 0 ] = ClipBD( rightShift(( pSrc0[ x + 0 ] + pSrc1[ x + 0 ] + offset ), shiftNum), clipbd );
+          pDst[ x + 1 ] = ClipBD( rightShift(( pSrc0[ x + 1 ] + pSrc1[ x + 1 ] + offset ), shiftNum), clipbd );
+        }
+        pSrc0 += iSrc0Stride;
+        pSrc1 += iSrc1Stride;
+        pDst  += iDstStride;
+      }
+    }
+    else
+    {
+      for ( Int y = 0; y < iHeight; y++ )
+      {
+        for (Int x=0 ; x < iWidth; x+=4 )
+        {
+          pDst[ x + 0 ] = ClipBD( rightShift(( pSrc0[ x + 0 ] + pSrc1[ x + 0 ] + offset ), shiftNum), clipbd );
+          pDst[ x + 1 ] = ClipBD( rightShift(( pSrc0[ x + 1 ] + pSrc1[ x + 1 ] + offset ), shiftNum), clipbd );
+          pDst[ x + 2 ] = ClipBD( rightShift(( pSrc0[ x + 2 ] + pSrc1[ x + 2 ] + offset ), shiftNum), clipbd );
+          pDst[ x + 3 ] = ClipBD( rightShift(( pSrc0[ x + 3 ] + pSrc1[ x + 3 ] + offset ), shiftNum), clipbd );
+        }
+        pSrc0 += iSrc0Stride;
+        pSrc1 += iSrc1Stride;
+        pDst  += iDstStride;
+      }
+    }
+  }
+}
+
+Void TComYuv::removeHighFreq( const TComYuv* pcYuvSrc,
+                              const UInt uiPartIdx,
+                              const UInt uiWidth,
+                              const UInt uiHeight,
+                              const Int bitDepths[MAX_NUM_CHANNEL_TYPE],
+                              const Bool bClipToBitDepths
+                              )
+{
+  for(Int comp=0; comp<getNumberValidComponents(); comp++)
+  {
+    const ComponentID compID=ComponentID(comp);
+    const Pel* pSrc  = pcYuvSrc->getAddr(compID, uiPartIdx);
+    Pel* pDst  = getAddr(compID, uiPartIdx);
+
+    const Int iSrcStride = pcYuvSrc->getStride(compID);
+    const Int iDstStride = getStride(compID);
+    const Int iWidth  = uiWidth >>getComponentScaleX(compID);
+    const Int iHeight = uiHeight>>getComponentScaleY(compID);
+    if (bClipToBitDepths)
+    {
+      const Int clipBd=bitDepths[toChannelType(compID)];
+      for ( Int y = iHeight-1; y >= 0; y-- )
+      {
+        for ( Int x = iWidth-1; x >= 0; x-- )
+        {
+          pDst[x ] = ClipBD((2 * pDst[x]) - pSrc[x], clipBd);
+        }
+        pSrc += iSrcStride;
+        pDst += iDstStride;
+      }
+    }
+    else
+    {
+      for ( Int y = iHeight-1; y >= 0; y-- )
+      {
+        for ( Int x = iWidth-1; x >= 0; x-- )
+        {
+          pDst[x ] = (2 * pDst[x]) - pSrc[x];
+        }
+        pSrc += iSrcStride;
+        pDst += iDstStride;
+      }
+    }
+  }
+}
+
+#if NH_3D_VSO
+Void TComYuv::addClipPartLuma( Int bitDepth, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
 {
   Int x, y;
-  
-  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pDst  = getLumaAddr( uiTrUnitIdx, uiPartSize );
-  
+
+  Pel* pSrc0 = pcYuvSrc0->getAddr( COMPONENT_Y, uiTrUnitIdx);
+  Pel* pSrc1 = pcYuvSrc1->getAddr( COMPONENT_Y, uiTrUnitIdx);
+  Pel* pDst  =            getAddr( COMPONENT_Y, uiTrUnitIdx);
+
+  UInt iSrc0Stride = pcYuvSrc0->getStride( COMPONENT_Y );
+  UInt iSrc1Stride = pcYuvSrc1->getStride( COMPONENT_Y );
+  UInt iDstStride  =            getStride( COMPONENT_Y );
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDst[x] = ClipBD( pSrc0[x] + pSrc1[x], bitDepth );      
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+#if H_3D_ARP
+Void TComYuv::addARP( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
+{
+  addARPLuma   ( pcYuvSrc0, pcYuvSrc1, uiAbsPartIdx, uiWidth   , uiHeight    , bClip );
+  addARPChroma ( pcYuvSrc0, pcYuvSrc1, uiAbsPartIdx, uiWidth>>1, uiHeight>>1 , bClip );
+}
+
+Void TComYuv::addARPLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
+{
+  Int x, y;
+
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiAbsPartIdx );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiAbsPartIdx );
+  Pel* pDst  = getLumaAddr( uiAbsPartIdx );
+
   UInt iSrc0Stride = pcYuvSrc0->getStride();
   UInt iSrc1Stride = pcYuvSrc1->getStride();
   UInt iDstStride  = getStride();
-  for ( y = uiPartSize-1; y >= 0; y-- )
-  {
-    for ( x = uiPartSize-1; x >= 0; x-- )
-    {
-      pDst[x] = ClipY( pSrc0[x] + pSrc1[x] );
+  Int iIFshift = IF_INTERNAL_PREC - g_bitDepthY;
+  Int iOffSet  = ( 1 << ( iIFshift - 1 ) ) + IF_INTERNAL_OFFS;
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidth-1; x >= 0; x-- )
+    {
+      pDst[x] = pSrc0[x] + pSrc1[x];
+      if( bClip )
+      {
+        pDst[x] = ClipY( ( pDst[x] + iOffSet ) >> iIFshift );
+      }
     }
     pSrc0 += iSrc0Stride;
@@ -438,26 +523,35 @@
 }
 
-Void TComYuv::addClipChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+Void TComYuv::addARPChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
 {
   Int x, y;
-  
-  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pDstU = getCbAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pDstV = getCrAddr( uiTrUnitIdx, uiPartSize );
-  
+
+  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiAbsPartIdx );
+  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiAbsPartIdx );
+  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiAbsPartIdx );
+  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiAbsPartIdx );
+  Pel* pDstU = getCbAddr( uiAbsPartIdx );
+  Pel* pDstV = getCrAddr( uiAbsPartIdx );
+
   UInt  iSrc0Stride = pcYuvSrc0->getCStride();
   UInt  iSrc1Stride = pcYuvSrc1->getCStride();
   UInt  iDstStride  = getCStride();
-  for ( y = uiPartSize-1; y >= 0; y-- )
-  {
-    for ( x = uiPartSize-1; x >= 0; x-- )
-    {
-      pDstU[x] = ClipC( pSrcU0[x] + pSrcU1[x] );
-      pDstV[x] = ClipC( pSrcV0[x] + pSrcV1[x] );
-    }
-    
+
+  Int iIFshift = IF_INTERNAL_PREC - g_bitDepthC;
+  Int iOffSet  = ( 1 << ( iIFshift - 1 ) ) + IF_INTERNAL_OFFS;
+
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidth-1; x >= 0; x-- )
+    {
+      pDstU[x] = pSrcU0[x] + pSrcU1[x];
+      pDstV[x] = pSrcV0[x] + pSrcV1[x];
+      if( bClip )
+      {
+        pDstU[x] = ClipC( ( pDstU[x] + iOffSet ) >> iIFshift );
+        pDstV[x] = ClipC( ( pDstV[x] + iOffSet ) >> iIFshift );
+      }
+    }
+
     pSrcU0 += iSrc0Stride;
     pSrcU1 += iSrc1Stride;
@@ -469,24 +563,26 @@
 }
 
-Void TComYuv::subtract( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
-{
-  subtractLuma  ( pcYuvSrc0, pcYuvSrc1,  uiTrUnitIdx, uiPartSize    );
-  subtractChroma( pcYuvSrc0, pcYuvSrc1,  uiTrUnitIdx, uiPartSize>>1 );
-}
-
-Void TComYuv::subtractLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+Void TComYuv::subtractARP( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
+{
+  subtractARPLuma  ( pcYuvSrc0, pcYuvSrc1,  uiAbsPartIdx, uiWidth    , uiHeight    );
+
+  if (uiWidth > 8)
+    subtractARPChroma( pcYuvSrc0, pcYuvSrc1,  uiAbsPartIdx, uiWidth>>1 , uiHeight>>1 );
+}
+
+Void TComYuv::subtractARPLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
 {
   Int x, y;
-  
-  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pDst  = getLumaAddr( uiTrUnitIdx, uiPartSize );
-  
+
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiAbsPartIdx );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiAbsPartIdx );
+  Pel* pDst  = getLumaAddr( uiAbsPartIdx );
+
   Int  iSrc0Stride = pcYuvSrc0->getStride();
   Int  iSrc1Stride = pcYuvSrc1->getStride();
   Int  iDstStride  = getStride();
-  for ( y = uiPartSize-1; y >= 0; y-- )
-  {
-    for ( x = uiPartSize-1; x >= 0; x-- )
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidth-1; x >= 0; x-- )
     {
       pDst[x] = pSrc0[x] - pSrc1[x];
@@ -498,21 +594,21 @@
 }
 
-Void TComYuv::subtractChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+Void TComYuv::subtractARPChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
 {
   Int x, y;
-  
-  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pDstU  = getCbAddr( uiTrUnitIdx, uiPartSize );
-  Pel* pDstV  = getCrAddr( uiTrUnitIdx, uiPartSize );
-  
+
+  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiAbsPartIdx );
+  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiAbsPartIdx );
+  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiAbsPartIdx );
+  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiAbsPartIdx );
+  Pel* pDstU  = getCbAddr( uiAbsPartIdx );
+  Pel* pDstV  = getCrAddr( uiAbsPartIdx );
+
   Int  iSrc0Stride = pcYuvSrc0->getCStride();
   Int  iSrc1Stride = pcYuvSrc1->getCStride();
   Int  iDstStride  = getCStride();
-  for ( y = uiPartSize-1; y >= 0; y-- )
-  {
-    for ( x = uiPartSize-1; x >= 0; x-- )
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidth-1; x >= 0; x-- )
     {
       pDstU[x] = pSrcU0[x] - pSrcU1[x];
@@ -528,284 +624,4 @@
 }
 
-Void TComYuv::addAvg( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight )
-{
-  Int x, y;
-  
-  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
-  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
-  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
-  
-  Pel* pSrcY1  = pcYuvSrc1->getLumaAddr( iPartUnitIdx );
-  Pel* pSrcU1  = pcYuvSrc1->getCbAddr  ( iPartUnitIdx );
-  Pel* pSrcV1  = pcYuvSrc1->getCrAddr  ( iPartUnitIdx );
-  
-  Pel* pDstY   = getLumaAddr( iPartUnitIdx );
-  Pel* pDstU   = getCbAddr  ( iPartUnitIdx );
-  Pel* pDstV   = getCrAddr  ( iPartUnitIdx );
-  
-  UInt  iSrc0Stride = pcYuvSrc0->getStride();
-  UInt  iSrc1Stride = pcYuvSrc1->getStride();
-  UInt  iDstStride  = getStride();
-  Int shiftNum = IF_INTERNAL_PREC + 1 - g_bitDepthY;
-  Int offset = ( 1 << ( shiftNum - 1 ) ) + 2 * IF_INTERNAL_OFFS;
-  
-  for ( y = 0; y < iHeight; y++ )
-  {
-    for ( x = 0; x < iWidth; x += 4 )
-    {
-      pDstY[ x + 0 ] = ClipY( ( pSrcY0[ x + 0 ] + pSrcY1[ x + 0 ] + offset ) >> shiftNum );
-      pDstY[ x + 1 ] = ClipY( ( pSrcY0[ x + 1 ] + pSrcY1[ x + 1 ] + offset ) >> shiftNum );
-      pDstY[ x + 2 ] = ClipY( ( pSrcY0[ x + 2 ] + pSrcY1[ x + 2 ] + offset ) >> shiftNum );
-      pDstY[ x + 3 ] = ClipY( ( pSrcY0[ x + 3 ] + pSrcY1[ x + 3 ] + offset ) >> shiftNum );
-    }
-    pSrcY0 += iSrc0Stride;
-    pSrcY1 += iSrc1Stride;
-    pDstY  += iDstStride;
-  }
-  
-  shiftNum = IF_INTERNAL_PREC + 1 - g_bitDepthC;
-  offset = ( 1 << ( shiftNum - 1 ) ) + 2 * IF_INTERNAL_OFFS;
-
-  iSrc0Stride = pcYuvSrc0->getCStride();
-  iSrc1Stride = pcYuvSrc1->getCStride();
-  iDstStride  = getCStride();
-  
-  iWidth  >>=1;
-  iHeight >>=1;
-  
-  for ( y = iHeight-1; y >= 0; y-- )
-  {
-    for ( x = iWidth-1; x >= 0; )
-    {
-      // note: chroma min width is 2
-      pDstU[x] = ClipC((pSrcU0[x] + pSrcU1[x] + offset) >> shiftNum);
-      pDstV[x] = ClipC((pSrcV0[x] + pSrcV1[x] + offset) >> shiftNum); x--;
-      pDstU[x] = ClipC((pSrcU0[x] + pSrcU1[x] + offset) >> shiftNum);
-      pDstV[x] = ClipC((pSrcV0[x] + pSrcV1[x] + offset) >> shiftNum); x--;
-    }
-    
-    pSrcU0 += iSrc0Stride;
-    pSrcU1 += iSrc1Stride;
-    pSrcV0 += iSrc0Stride;
-    pSrcV1 += iSrc1Stride;
-    pDstU  += iDstStride;
-    pDstV  += iDstStride;
-  }
-}
-
-Void TComYuv::removeHighFreq( TComYuv* pcYuvSrc, UInt uiPartIdx, UInt uiWidht, UInt uiHeight )
-{
-  Int x, y;
-  
-  Pel* pSrc  = pcYuvSrc->getLumaAddr(uiPartIdx);
-  Pel* pSrcU = pcYuvSrc->getCbAddr(uiPartIdx);
-  Pel* pSrcV = pcYuvSrc->getCrAddr(uiPartIdx);
-  
-  Pel* pDst  = getLumaAddr(uiPartIdx);
-  Pel* pDstU = getCbAddr(uiPartIdx);
-  Pel* pDstV = getCrAddr(uiPartIdx);
-  
-  Int  iSrcStride = pcYuvSrc->getStride();
-  Int  iDstStride = getStride();
-  
-  for ( y = uiHeight-1; y >= 0; y-- )
-  {
-    for ( x = uiWidht-1; x >= 0; x-- )
-    {
-#if DISABLING_CLIP_FOR_BIPREDME
-      pDst[x ] = 2 * pDst[x] - pSrc[x];
-#else
-      pDst[x ] = ClipY(2 * pDst[x] - pSrc[x]);
-#endif
-    }
-    pSrc += iSrcStride;
-    pDst += iDstStride;
-  }
-  
-  iSrcStride = pcYuvSrc->getCStride();
-  iDstStride = getCStride();
-  
-  uiHeight >>= 1;
-  uiWidht  >>= 1;
-  
-  for ( y = uiHeight-1; y >= 0; y-- )
-  {
-    for ( x = uiWidht-1; x >= 0; x-- )
-    {
-#if DISABLING_CLIP_FOR_BIPREDME
-      pDstU[x ] = 2 * pDstU[x] - pSrcU[x];
-      pDstV[x ] = 2 * pDstV[x] - pSrcV[x];
-#else
-      pDstU[x ] = ClipC(2 * pDstU[x] - pSrcU[x]);
-      pDstV[x ] = ClipC(2 * pDstV[x] - pSrcV[x]);
-#endif
-    }
-    pSrcU += iSrcStride;
-    pSrcV += iSrcStride;
-    pDstU += iDstStride;
-    pDstV += iDstStride;
-  }
-}
-#if H_3D
-Void TComYuv::addClipPartLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
-{
-  Int x, y;
-
-  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx);
-  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx);
-  Pel* pDst  = getLumaAddr( uiTrUnitIdx);
-
-  UInt iSrc0Stride = pcYuvSrc0->getStride();
-  UInt iSrc1Stride = pcYuvSrc1->getStride();
-  UInt iDstStride  = getStride();
-  for ( y = uiPartSize-1; y >= 0; y-- )
-  {
-    for ( x = uiPartSize-1; x >= 0; x-- )
-    {
-      pDst[x] = ClipY( pSrc0[x] + pSrc1[x] );      
-    }
-    pSrc0 += iSrc0Stride;
-    pSrc1 += iSrc1Stride;
-    pDst  += iDstStride;
-  }
-}
-
-#if H_3D_ARP
-Void TComYuv::addARP( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
-{
-  addARPLuma   ( pcYuvSrc0, pcYuvSrc1, uiAbsPartIdx, uiWidth   , uiHeight    , bClip );
-  addARPChroma ( pcYuvSrc0, pcYuvSrc1, uiAbsPartIdx, uiWidth>>1, uiHeight>>1 , bClip );
-}
-
-Void TComYuv::addARPLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
-{
-  Int x, y;
-
-  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiAbsPartIdx );
-  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiAbsPartIdx );
-  Pel* pDst  = getLumaAddr( uiAbsPartIdx );
-
-  UInt iSrc0Stride = pcYuvSrc0->getStride();
-  UInt iSrc1Stride = pcYuvSrc1->getStride();
-  UInt iDstStride  = getStride();
-  Int iIFshift = IF_INTERNAL_PREC - g_bitDepthY;
-  Int iOffSet  = ( 1 << ( iIFshift - 1 ) ) + IF_INTERNAL_OFFS;
-  for ( y = uiHeight-1; y >= 0; y-- )
-  {
-    for ( x = uiWidth-1; x >= 0; x-- )
-    {
-      pDst[x] = pSrc0[x] + pSrc1[x];
-      if( bClip )
-      {
-        pDst[x] = ClipY( ( pDst[x] + iOffSet ) >> iIFshift );
-      }
-    }
-    pSrc0 += iSrc0Stride;
-    pSrc1 += iSrc1Stride;
-    pDst  += iDstStride;
-  }
-}
-
-Void TComYuv::addARPChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
-{
-  Int x, y;
-
-  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiAbsPartIdx );
-  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiAbsPartIdx );
-  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiAbsPartIdx );
-  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiAbsPartIdx );
-  Pel* pDstU = getCbAddr( uiAbsPartIdx );
-  Pel* pDstV = getCrAddr( uiAbsPartIdx );
-
-  UInt  iSrc0Stride = pcYuvSrc0->getCStride();
-  UInt  iSrc1Stride = pcYuvSrc1->getCStride();
-  UInt  iDstStride  = getCStride();
-
-  Int iIFshift = IF_INTERNAL_PREC - g_bitDepthC;
-  Int iOffSet  = ( 1 << ( iIFshift - 1 ) ) + IF_INTERNAL_OFFS;
-
-  for ( y = uiHeight-1; y >= 0; y-- )
-  {
-    for ( x = uiWidth-1; x >= 0; x-- )
-    {
-      pDstU[x] = pSrcU0[x] + pSrcU1[x];
-      pDstV[x] = pSrcV0[x] + pSrcV1[x];
-      if( bClip )
-      {
-        pDstU[x] = ClipC( ( pDstU[x] + iOffSet ) >> iIFshift );
-        pDstV[x] = ClipC( ( pDstV[x] + iOffSet ) >> iIFshift );
-      }
-    }
-
-    pSrcU0 += iSrc0Stride;
-    pSrcU1 += iSrc1Stride;
-    pSrcV0 += iSrc0Stride;
-    pSrcV1 += iSrc1Stride;
-    pDstU  += iDstStride;
-    pDstV  += iDstStride;
-  }
-}
-
-Void TComYuv::subtractARP( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
-{
-  subtractARPLuma  ( pcYuvSrc0, pcYuvSrc1,  uiAbsPartIdx, uiWidth    , uiHeight    );
-
-  if (uiWidth > 8)
-    subtractARPChroma( pcYuvSrc0, pcYuvSrc1,  uiAbsPartIdx, uiWidth>>1 , uiHeight>>1 );
-}
-
-Void TComYuv::subtractARPLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
-{
-  Int x, y;
-
-  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiAbsPartIdx );
-  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiAbsPartIdx );
-  Pel* pDst  = getLumaAddr( uiAbsPartIdx );
-
-  Int  iSrc0Stride = pcYuvSrc0->getStride();
-  Int  iSrc1Stride = pcYuvSrc1->getStride();
-  Int  iDstStride  = getStride();
-  for ( y = uiHeight-1; y >= 0; y-- )
-  {
-    for ( x = uiWidth-1; x >= 0; x-- )
-    {
-      pDst[x] = pSrc0[x] - pSrc1[x];
-    }
-    pSrc0 += iSrc0Stride;
-    pSrc1 += iSrc1Stride;
-    pDst  += iDstStride;
-  }
-}
-
-Void TComYuv::subtractARPChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
-{
-  Int x, y;
-
-  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiAbsPartIdx );
-  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiAbsPartIdx );
-  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiAbsPartIdx );
-  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiAbsPartIdx );
-  Pel* pDstU  = getCbAddr( uiAbsPartIdx );
-  Pel* pDstV  = getCrAddr( uiAbsPartIdx );
-
-  Int  iSrc0Stride = pcYuvSrc0->getCStride();
-  Int  iSrc1Stride = pcYuvSrc1->getCStride();
-  Int  iDstStride  = getCStride();
-  for ( y = uiHeight-1; y >= 0; y-- )
-  {
-    for ( x = uiWidth-1; x >= 0; x-- )
-    {
-      pDstU[x] = pSrcU0[x] - pSrcU1[x];
-      pDstV[x] = pSrcV0[x] - pSrcV1[x];
-    }
-    pSrcU0 += iSrc0Stride;
-    pSrcU1 += iSrc1Stride;
-    pSrcV0 += iSrc0Stride;
-    pSrcV1 += iSrc1Stride;
-    pDstU  += iDstStride;
-    pDstV  += iDstStride;
-  }
-}
-
 Void TComYuv::multiplyARP( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW )
 {
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComYuv.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TComYuv.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -40,7 +40,7 @@
 #ifndef __TCOMYUV__
 #define __TCOMYUV__
-#include <assert.h>
 #include "CommonDef.h"
 #include "TComPicYuv.h"
+#include "TComRectangle.h"
 
 //! \ingroup TLibCommon
@@ -55,144 +55,167 @@
 {
 private:
-  
+
   // ------------------------------------------------------------------------------------------------------------------
   //  YUV buffer
   // ------------------------------------------------------------------------------------------------------------------
-  
-  Pel*    m_apiBufY;
-  Pel*    m_apiBufU;
-  Pel*    m_apiBufV;
-  
+
+  Pel*    m_apiBuf[MAX_NUM_COMPONENT];
+
   // ------------------------------------------------------------------------------------------------------------------
   //  Parameter for general YUV buffer usage
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   UInt     m_iWidth;
   UInt     m_iHeight;
-  UInt     m_iCWidth;
-  UInt     m_iCHeight;
-  
-  static Int getAddrOffset( UInt uiPartUnitIdx, UInt width )
-  {
-    Int blkX = g_auiRasterToPelX[ g_auiZscanToRaster[ uiPartUnitIdx ] ];
-    Int blkY = g_auiRasterToPelY[ g_auiZscanToRaster[ uiPartUnitIdx ] ];
-    
-    return blkX + blkY * width;
-  }
-
-  static Int getAddrOffset( UInt iTransUnitIdx, UInt iBlkSize, UInt width )
-  {
-    Int blkX = ( iTransUnitIdx * iBlkSize ) &  ( width - 1 );
-    Int blkY = ( iTransUnitIdx * iBlkSize ) &~ ( width - 1 );
-    
-    return blkX + blkY * iBlkSize;
-  }
-  
+  ChromaFormat m_chromaFormatIDC; ////< Chroma Format
+
+  // dims 16x16
+  // blkSize=4x4
+
+  // these functions assume a square CU, of size width*width, split into square TUs each of size blkSize*blkSize.
+  // iTransUnitIdx is the raster-scanned index of the sub-block (TU) in question.
+  // eg for a 16x16 CU, with 4x4 TUs:
+  //  0  1  2  3
+  //  4  5  6  7
+  //  8  9 10 11
+  // 12 13 14 15
+
+  // So, for iTransUnitIdx=14, 14*4 & 15 =8=X offset.
+  //                           14*4 / 16 =3=Y block offset
+  //                                      3*4*16 = Y offset within buffer
+
+
 public:
-  
-  TComYuv();
-  virtual ~TComYuv();
-  
+
+               TComYuv                    ();
+  virtual     ~TComYuv                    ();
+
   // ------------------------------------------------------------------------------------------------------------------
   //  Memory management
   // ------------------------------------------------------------------------------------------------------------------
-  
-  Void    create            ( UInt iWidth, UInt iHeight );  ///< Create  YUV buffer
-  Void    destroy           ();                             ///< Destroy YUV buffer
-  Void    clear             ();                             ///< clear   YUV buffer
-  
+
+  Void         create                     ( const UInt iWidth, const UInt iHeight, const ChromaFormat chromaFormatIDC );  ///< Create  YUV buffer
+  Void         destroy                    ();                             ///< Destroy YUV buffer
+  Void         clear                      ();                             ///< clear   YUV buffer
+
   // ------------------------------------------------------------------------------------------------------------------
   //  Copy, load, store YUV buffer
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   //  Copy YUV buffer to picture buffer
-  Void    copyToPicYuv         ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
-  Void    copyToPicLuma        ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
-  Void    copyToPicChroma      ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
-  
+  Void         copyToPicYuv               ( TComPicYuv* pcPicYuvDst, const UInt ctuRsAddr, const UInt uiAbsZorderIdx, const UInt uiPartDepth = 0, const UInt uiPartIdx = 0 ) const ;
+  Void         copyToPicComponent         ( const ComponentID id, TComPicYuv* pcPicYuvDst, const UInt iCtuRsAddr, const UInt uiAbsZorderIdx, const UInt uiPartDepth = 0, const UInt uiPartIdx = 0 ) const ;
+
   //  Copy YUV buffer from picture buffer
-  Void    copyFromPicYuv       ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
-  Void    copyFromPicLuma      ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
-  Void    copyFromPicChroma    ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
-  
+  Void         copyFromPicYuv             ( const TComPicYuv* pcPicYuvSrc, const  UInt ctuRsAddr, const UInt uiAbsZorderIdx );
+  Void         copyFromPicComponent       ( const ComponentID id, const TComPicYuv* pcPicYuvSrc, const UInt iCtuRsAddr, const UInt uiAbsZorderIdx );
+
   //  Copy Small YUV buffer to the part of other Big YUV buffer
-  Void    copyToPartYuv         ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
-  Void    copyToPartLuma        ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
-  Void    copyToPartChroma      ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
-  
+  Void         copyToPartYuv              ( TComYuv*    pcYuvDst,    const UInt uiDstPartIdx ) const ;
+  Void         copyToPartComponent        ( const ComponentID id, TComYuv*    pcYuvDst,    const UInt uiDstPartIdx ) const ;
+
   //  Copy the part of Big YUV buffer to other Small YUV buffer
-  Void    copyPartToYuv         ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
-  Void    copyPartToLuma        ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
-  Void    copyPartToChroma      ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
-  
+  Void         copyPartToYuv              ( TComYuv*    pcYuvDst,   const UInt uiSrcPartIdx ) const;
+  Void         copyPartToComponent        ( const ComponentID id, TComYuv*    pcYuvDst,    const UInt uiSrcPartIdx ) const;
+
   //  Copy YUV partition buffer to other YUV partition buffer
-  Void    copyPartToPartYuv     ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
-  Void    copyPartToPartLuma    ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
-  Void    copyPartToPartChroma  ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
-  
-  Void    copyPartToPartChroma  ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight, UInt chromaId);
+  Void         copyPartToPartYuv          ( TComYuv*    pcYuvDst, const UInt uiPartIdx, const UInt uiWidth, const UInt uiHeight ) const;
+  Void         copyPartToPartComponent    ( const ComponentID id, TComYuv*    pcYuvDst, const UInt uiPartIdx, const UInt uiWidthComponent, const UInt uiHeightComponent ) const;
+
+ // Copy YUV partition buffer to other YUV partition buffer for non-square blocks
+  Void         copyPartToPartComponentMxN ( const ComponentID id, TComYuv*    pcYuvDst, const TComRectangle &rect ) const;
 
   // ------------------------------------------------------------------------------------------------------------------
   //  Algebraic operation for YUV buffer
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   //  Clip(pcYuvSrc0 + pcYuvSrc1) -> m_apiBuf
-  Void    addClip           ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
-  Void    addClipLuma       ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
-  Void    addClipChroma     ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
-  
+  Void         addClip                    ( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt uiTrUnitIdx, const UInt uiPartSize, const BitDepths &clipBitDepths );
+
   //  pcYuvSrc0 - pcYuvSrc1 -> m_apiBuf
-  Void    subtract          ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
-  Void    subtractLuma      ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
-  Void    subtractChroma    ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
-  
+  Void         subtract                   ( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt uiTrUnitIdx, const UInt uiPartSize );
+
   //  (pcYuvSrc0 + pcYuvSrc1)/2 for YUV partition
-  Void    addAvg            ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight );
-
-  //   Remove High frequency
-  Void    removeHighFreq    ( TComYuv* pcYuvSrc, UInt uiPartIdx, UInt uiWidht, UInt uiHeight );
-  
+  Void         addAvg                     ( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt iPartUnitIdx, const UInt iWidth, const UInt iHeight, const BitDepths &clipBitDepths );
+
+  Void         removeHighFreq             ( const TComYuv* pcYuvSrc, const UInt uiPartIdx, const UInt uiWidth, const UInt uiHeight
+                                          , const Int bitDepths[MAX_NUM_CHANNEL_TYPE], const Bool bClipToBitDepths
+                                          );
+
   // ------------------------------------------------------------------------------------------------------------------
   //  Access function for YUV buffer
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   //  Access starting position of YUV buffer
-  Pel*    getLumaAddr ()    { return m_apiBufY; }
-  Pel*    getCbAddr   ()    { return m_apiBufU; }
-  Pel*    getCrAddr   ()    { return m_apiBufV; }
-  
+  Pel*         getAddr                    (const ComponentID id)                    { return m_apiBuf[id]; }
+  const Pel*   getAddr                    (const ComponentID id) const              { return m_apiBuf[id]; }
+
   //  Access starting position of YUV partition unit buffer
-  Pel* getLumaAddr( UInt iPartUnitIdx ) { return m_apiBufY +   getAddrOffset( iPartUnitIdx, m_iWidth  )       ; }
-  Pel* getCbAddr  ( UInt iPartUnitIdx ) { return m_apiBufU + ( getAddrOffset( iPartUnitIdx, m_iCWidth ) >> 1 ); }
-  Pel* getCrAddr  ( UInt iPartUnitIdx ) { return m_apiBufV + ( getAddrOffset( iPartUnitIdx, m_iCWidth ) >> 1 ); }
-  
+  Pel*         getAddr                    (const ComponentID id, const UInt uiPartUnitIdx)
+                                              {
+                                                  Int blkX = g_auiRasterToPelX[ g_auiZscanToRaster[ uiPartUnitIdx ] ] >> getComponentScaleX(id);
+                                                  Int blkY = g_auiRasterToPelY[ g_auiZscanToRaster[ uiPartUnitIdx ] ] >> getComponentScaleY(id);
+                                                  assert((blkX<getWidth(id) && blkY<getHeight(id)));
+                                                  return m_apiBuf[id] + blkX + blkY * getStride(id);
+                                              }
+  const Pel*   getAddr                    (const ComponentID id, const UInt uiPartUnitIdx) const
+                                              {
+                                                  Int blkX = g_auiRasterToPelX[ g_auiZscanToRaster[ uiPartUnitIdx ] ] >> getComponentScaleX(id);
+                                                  Int blkY = g_auiRasterToPelY[ g_auiZscanToRaster[ uiPartUnitIdx ] ] >> getComponentScaleY(id);
+                                                  assert((blkX<getWidth(id) && blkY<getHeight(id)));
+                                                  return m_apiBuf[id] + blkX + blkY * getStride(id);
+                                              }
+
   //  Access starting position of YUV transform unit buffer
-  Pel* getLumaAddr( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufY + getAddrOffset( iTransUnitIdx, iBlkSize, m_iWidth  ); }
-  Pel* getCbAddr  ( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufU + getAddrOffset( iTransUnitIdx, iBlkSize, m_iCWidth ); }
-  Pel* getCrAddr  ( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufV + getAddrOffset( iTransUnitIdx, iBlkSize, m_iCWidth ); }
+  Pel*         getAddr                    (const ComponentID id, const UInt iTransUnitIdx, const UInt iBlkSizeForComponent)
+                                              {
+                                                UInt width=getWidth(id);
+                                                Int blkX = ( iTransUnitIdx * iBlkSizeForComponent ) &  ( width - 1 );
+                                                Int blkY = ( iTransUnitIdx * iBlkSizeForComponent ) &~ ( width - 1 );
+                                                if (m_chromaFormatIDC==CHROMA_422 && id!=COMPONENT_Y)
+                                                {
+                                                  blkY<<=1;
+                                                }
+                                                return m_apiBuf[id] + blkX + blkY * iBlkSizeForComponent;
+                                              }
+
+  const Pel*   getAddr                    (const ComponentID id, const UInt iTransUnitIdx, const UInt iBlkSizeForComponent) const
+                                              {
+                                                UInt width=getWidth(id);
+                                                Int blkX = ( iTransUnitIdx * iBlkSizeForComponent ) &  ( width - 1 );
+                                                Int blkY = ( iTransUnitIdx * iBlkSizeForComponent ) &~ ( width - 1 );
+                                                if (m_chromaFormatIDC==CHROMA_422 && id!=COMPONENT_Y)
+                                                {
+                                                  blkY<<=1;
+                                                }
+                                                return m_apiBuf[id] + blkX + blkY * iBlkSizeForComponent;
+                                              }
+
+  // Access starting position of YUV transform unit buffer by pix offset for square & non-square blocks
+  Pel*         getAddrPix                 (const ComponentID id, const UInt iPixX, const UInt iPixY )       { return m_apiBuf[id] + iPixY * getStride(id) + iPixX; }
+  const Pel*   getAddrPix                 (const ComponentID id, const UInt iPixX, const UInt iPixY ) const { return m_apiBuf[id] + iPixY * getStride(id) + iPixX; }
 
   //  Get stride value of YUV buffer
-  UInt    getStride   ()    { return  m_iWidth;   }
-  UInt    getCStride  ()    { return  m_iCWidth;  }
-  UInt    getHeight   ()    { return  m_iHeight;  }
-  
-  UInt    getWidth    ()    { return  m_iWidth;   }
-  UInt    getCHeight  ()    { return  m_iCHeight; }
-  UInt    getCWidth   ()    { return  m_iCWidth;  }  
-#if H_3D
-  Void addClipPartLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
-
+  UInt         getStride                  (const ComponentID id) const { return m_iWidth >> getComponentScaleX(id);   }
+  UInt         getHeight                  (const ComponentID id) const { return m_iHeight >> getComponentScaleY(id);  }
+  UInt         getWidth                   (const ComponentID id) const { return m_iWidth >> getComponentScaleX(id);   }
+  ChromaFormat getChromaFormat            ()                     const { return m_chromaFormatIDC; }
+  UInt         getNumberValidComponents   ()                     const { return ::getNumberValidComponents(m_chromaFormatIDC); }
+  UInt         getComponentScaleX         (const ComponentID id) const { return ::getComponentScaleX(id, m_chromaFormatIDC); }
+  UInt         getComponentScaleY         (const ComponentID id) const { return ::getComponentScaleY(id, m_chromaFormatIDC); }
+#if NH_3D
+  Void         addClipPartLuma( Int bitDepth, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
 #if H_3D_ARP
-  Void    addARP           ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
-  Void    addARPLuma       ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
-  Void    addARPChroma     ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
-  Void    subtractARP      ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
-  Void    subtractARPLuma  ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
-  Void    subtractARPChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
-  Void    multiplyARP      ( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
-  Void    multiplyARPLuma  ( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
-  Void    multiplyARPChroma( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
-private:
-  Void    xxMultiplyLine( Pel * pSrcDst , UInt uiWidth , UChar dW );
+  Void         addARP                     ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
+  Void         addARPLuma                 ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
+  Void         addARPChroma               ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
+  Void         subtractARP                ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
+  Void         subtractARPLuma            ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
+  Void         subtractARPChroma          ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
+  Void         multiplyARP                ( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
+  Void         multiplyARPLuma            ( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
+  Void         multiplyARPChroma          ( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
+private:                                  
+  Void         xxMultiplyLine             ( Pel * pSrcDst , UInt uiWidth , UChar dW );
 #endif
 #endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TypeDef.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibCommon/TypeDef.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -31,12 +31,13 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
-
 /** \file     TypeDef.h
     \brief    Define basic types, new types and enumerations
 */
-
-#ifndef _TYPEDEF__
-#define _TYPEDEF__
-
+#ifndef __TYPEDEF__
+#define __TYPEDEF__
+#ifndef __COMMONDEF__
+#error Include CommonDef.h not TypeDef.h
+#endif
+#include <vector>
 //! \ingroup TLibCommon
 //! \{
@@ -44,32 +45,28 @@
 ///////////////////////////////// EXTENSION SELECTION ///////////////////////////////////  
 /////////////////////////////////////////////////////////////////////////////////////////
-
 /* HEVC_EXT might be defined by compiler/makefile options.
-   
    Linux makefiles support the following settings:   
    make             -> HEVC_EXT not defined    
-   make HEVC_EXT=0  -> H_MV=0 H_3D=0   --> plain HM
-   make HEVC_EXT=1  -> H_MV=1 H_3D=0   --> MV only 
-   make HEVC_EXT=2  -> H_MV=1 H_3D=1   --> full 3D 
+   make HEVC_EXT=0  -> NH_MV=0 H_3D=0   --> plain HM
+   make HEVC_EXT=1  -> NH_MV=1 H_3D=0   --> MV only 
+   make HEVC_EXT=2  -> NH_MV=1 H_3D=1   --> full 3D 
 */
-
 #ifndef HEVC_EXT
-#define HEVC_EXT                    2
-#endif
-
+#define HEVC_EXT                    1
+#endif
 #if ( HEVC_EXT < 0 )||( HEVC_EXT > 2 )
 #error HEVC_EXT must be in the range of 0 to 2, inclusive. 
 #endif
-
-#define H_MV          ( HEVC_EXT != 0)
-#define H_3D          ( HEVC_EXT == 2)
-
+#define NH_MV          ( HEVC_EXT != 0)
+#define NH_3D          ( HEVC_EXT == 2)
 
 /////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////   MAJOR DEFINES   ///////////////////////////////////  
 /////////////////////////////////////////////////////////////////////////////////////////
+#if NH_MV
+#define H_MV_ENC_DEC_TRAC                 1  //< CU/PU level tracking
 
-#if H_MV
-#define H_MV_ENC_DEC_TRAC                 1  //< CU/PU level tracking
+#if NH_3D
+#define NH_3D_VSO                         1
 #endif
 
@@ -78,5 +75,4 @@
                                               // HHI_QTLPC_RAU_OFF_C0160 JCT3V-C0160 change 2: quadtree limitation and predictive coding switched off in random access units 
                                               // MTK_TEX_DEP_PAR_G0055 Texture-partition-dependent depth partition. JCT3V-G0055
-
 #define H_3D_VSO                          1   // VSO, View synthesis optimization, includes: 
                                               // HHI_VSO
@@ -101,5 +97,4 @@
                                               // MTK_TEXTURE_MRGCAND_BUGFIX_E0182  Bug fix for TEXTURE MERGING CANDIDATE     , JCT3V-E0182
                                               // LGE_SIMP_DISP_AVAIL_J0041    // Use 2 status for disparity availability - DISP_AVAILABLE and DISP_NONE
-
 #define H_3D_ARP                          1   // Advanced residual prediction (ARP), JCT3V-D0177
                                               // QC_MTK_INTERVIEW_ARP_F0123_F0108 JCT3V-F0123; JCT3V-F0108
@@ -114,5 +109,4 @@
                                               // SEC_ARP_VIEW_REF_CHECK_J0037    Signaling iv_res_pred_weight_idx when the current slice has both view and temporal reference picture(s), JCT3V-J0037 item1
                                               // SEC_ARP_REM_ENC_RESTRICT_K0035    Removal of encoder restriction of ARP, JCT3V-K0035
-
 #define H_3D_IC                           1   // Illumination Compensation, JCT3V-B0045, JCT3V-C0046, JCT3V-D0060
                                               // Unifying rounding offset, for IC part, JCT3V-D0135
@@ -128,5 +122,4 @@
                                               // SEC_IC_NEIGHBOR_CLIP_I0080    // Clipping of neighboring sample position, JCT3V-I0080
                                               // LGE_CHROMA_IC_J0050_J0034
-
 #if H_3D_NBDV
 #define H_3D_NBDV_REF                     1   // Depth oriented neighboring block disparity derivation
@@ -138,5 +131,4 @@
                                               // SEC_VER_DONBDV_H0103          Vertical DV Restriction for DoNBDV
 #endif
-
 #define H_3D_VSP                          1   // View synthesis prediction
                                               // MERL_C0152: Basic VSP
@@ -157,7 +149,4 @@
                                               // MTK_MRG_LIST_SIZE_CLEANUP_J0059   1   // Include VSP for deriving merge candidate list size, JCT3V-J0059
                                               // SEC_A1_BASED_VSP_J0039            1   // Removal of redundant VSP in Merge list
-
-
-
 #define H_3D_IV_MERGE                     1   // Inter-view motion merge candidate
                                               // HHI_INTER_VIEW_MOTION_PRED 
@@ -183,11 +172,7 @@
                                               // SEC_SIMP_SHIFTED_DV_I0086     Simplification of Shifted DV candidate, JCT3V-I0086
                                               // SEC_SHIFTED_IVMC_POS_K0036    Position Derivation for Shifted-IVMC, JCT3V-K0036
-
-
 #define H_3D_TMVP                         1   // QC_TMVP_C0047 
                                               // Sony_M23639
                                               // H_3D_TMVP_SCALING_FIX_K0053       1   // QC/CY for K0053
-
-
 #define H_3D_DIM                          1   // DIM, Depth intra modes, includes:
                                               // HHI_DMM_WEDGE_INTRA
@@ -238,10 +223,7 @@
                                               // SHARP_DLT_SIMP_J0029 DLT(DepthValue2Idx[]) table derivation cleanup
                                               // SHARP_DMM_CLEAN_K0042             1   // Generate DMM pattern with rotation 
-
-
 #define H_3D_INTER_SDC                    1   // INTER SDC, Inter simplified depth coding
                                               // LGE_INTER_SDC_E0156 Enable inter SDC for depth coding
                                               // SEC_INTER_SDC_G0101 Improved inter SDC with multiple DC candidates
-
 #define H_3D_SPIVMP                       1   // H_3D_SPIVMP JCT3V-F0110: Sub-PU level inter-view motion prediction
                                               // SEC_SPIVMP_MCP_SIZE_G0077, Apply SPIVMP only to 2Nx2N partition, JCT3V-G0077
@@ -249,5 +231,4 @@
                                               // Simplification on Sub-PU level temporal interview motion prediction
                                               // MPI_SUBPU_DEFAULT_MV_H0077_H0099_H0111_H0133
-
 #define H_3D_DBBP                         1   // DBBP: Depth-based Block Partitioning and Merging
                                               // MTK_DBBP_AMP_REM_H0072   
@@ -263,18 +244,12 @@
                                               // RWTH_DBBP_NO_SATD_K0028
                                               // HS_DBBP_CLEAN_K0048
-
 #define H_3D_DDD                          1   // Disparity derived depth coding
                                               // LGE_DDD_REMOVAL_J0042_J0030 DDD removal
-
 #define H_3D_DIS                          1   // Depth intra skip 
                                               // SEC_DEPTH_INTRA_SKIP_MODE_K0033  Depth intra skip mode
-
 #define H_3D_FCO                          0   // Flexible coding order for 3D
-
 #define H_3D_FAST_INTRA_SDC               1   // I0123
-
 // OTHERS
                                               // MTK_SONY_PROGRESSIVE_MV_COMPRESSION_E0170 // Progressive MV Compression, JCT3V-E0170
-
 #define H_3D_FAST_TEXTURE_ENCODING        1   // Fast merge mode decision and early CU determination for texture component of dependent view, JCT3V-E0173
                                               // MTK_FAST_TEXTURE_ENCODING_E0173
@@ -283,5 +258,4 @@
                                               // SCU_HS_FAST_DEPTH_INTRA_E0238_HHIFIX
 #endif
-
 //HLS
                                              // HHI_DEPENDENCY_SIGNALLING_I1_J0107
@@ -292,5 +266,4 @@
                                              // HHI_CAM_PARA_K0052       
                                              // H_3D_DIRECT_DEP_TYPE     
-
 // Rate Control
 #define KWU_FIX_URQ                       1
@@ -298,17 +271,13 @@
 #define KWU_RC_MADPRED_E0227              0  ///< JCT3V-E0227, inter-view MAD prediction
 #endif // H_3D
-
 /////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////   DERIVED DEFINES ///////////////////////////////////  
 /////////////////////////////////////////////////////////////////////////////////////////
-
-#if H_3D
-#define H_3D_DISABLE_CHROMA                    1 
+#if NH_3D
 #define H_3D_OUTPUT_ACTIVE_TOOLS               0
 #define H_3D_REN_MAX_DEV_OUT                   0
 #endif
-
 ///// ***** VIEW SYNTHESIS OPTIMIZAION *********
-#if H_3D_VSO                                  
+#if NH_3D_VSO                                  
 #define H_3D_VSO_DIST_INT                 1   // Allow negative synthesized view distortion change
 #define H_3D_VSO_COLOR_PLANES             1   // Compute VSO distortion on color planes 
@@ -317,5 +286,4 @@
 #define H_3D_VSO_SYNTH_DIST_OUT           0   // Output of synthesized view distortion instead of depth distortion in encoder output
 #endif
-
 ////   ****** NEIGHBOURING BLOCK-BASED DISPARITY VECTOR  *********
 #if H_3D_NBDV
@@ -324,10 +292,8 @@
 #define IDV_CANDS                         2
 #endif
-
 ///// ***** ADVANCED INTERVIEW RESIDUAL PREDICTION *********
 #if H_3D_ARP
 #define H_3D_ARP_WFNR                     3
 #endif
-
 ///// ***** DEPTH INTRA MODES *********
 #if H_3D_DIM
@@ -336,10 +302,11 @@
 #define H_3D_DIM_SDC                      1   // Simplified Depth Coding method
 #define H_3D_DIM_DLT                      1   // Depth Lookup Table
-
 #define H_3D_DIM_ENC                      1   // Depth Intra encoder optimizations, includes:
                                               // HHI_DEPTH_INTRA_SEARCH_RAU_C0160
                                               // LG_ZEROINTRADEPTHRESI_A0087
-
-#endif
+#endif
+/////////////////////////////////////////////////////////////////////////////////////
+/// GT: Move values which are not flags to CommonDef.h and convert to static int !!
+///////////////////////////////////////////////////////////////////////////////////
 ///// ***** VIEW SYNTHESIS PREDICTION *********
 #if H_3D_VSP
@@ -351,6 +318,4 @@
 #endif
 #endif
-
-
 ///// ***** ILLUMATION COMPENSATION *********
 #if H_3D_IC
@@ -360,6 +325,4 @@
 #define IC_LOW_LATENCY_ENCODING_THRESHOLD 0.1 // Threshold for low-latency IC encoding in JCT3V-H0086
 #endif
-
-
 ///// ***** DEPTH BASED BLOCK PARTITIONING *********
 #if H_3D_DBBP
@@ -367,6 +330,4 @@
 #define DBBP_PACK_MODE               SIZE_2NxN
 #endif
-
-
 ///// ***** FCO *********
 #if H_3D_FCO
@@ -375,24 +336,17 @@
 #define H_3D_FCO_VSP_DONBDV_E0163               0   // Adaptive depth reference for flexible coding order
 #endif
-
 #if H_3D
 #define PPS_FIX_DEPTH                           1
 #endif
-
-
 /////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////   MV_HEVC HLS  //////////////////////////////
 /////////////////////////////////////////////////////////////////////////////////
 // TBD: Check if integration is necessary. 
-
-
 #define H_MV_HLS_PTL_LIMITS                  0
 #define H_MV_HLS7_GEN                        0  // General changes (not tested)
-
 // POC
 // #define H_MV_HLS_7_POC_P0041_3            0 // (POC/P0041/POC reset) #3 It was remarked that we should require each non-IRAP picture that has discardable_flag equal to 1 to have NUT value indicating that it is a sub-layer non-reference picture. This was agreed. Decision: Adopt (with constraint for discardable_flag as described above) 
 // #define H_MV_HLS_7_POC_P0041_FIXES        0 // (POC/P0041/Fixes) For each non-IRAP picture that has discardable_flag equal to 1 to have NUT value indicating that it is a sub-layer non-reference picture. 
 // #define H_MV_HLS_7_POC_P0056_4            0 // (POC/P0056/layer tree poc) #4 Proposal 1: If the POC reset approach is adopted as the basis for multi-layer POC derivation, it is proposed to derive the POC anchor picture from the previous TID0 picture (that is not a RASL picture, a RADL picture or a sub-layer non-reference picture and not with discardable_flag equal to 1) of  the current layer or any of its reference layer. This is asserted to improve loss resilience and reduce bit rate overhead. Decision: Adopt Proposal 1 (with the suggested modifications Ewith text provided as P0297).
-
 // SEI related
 //#define H_MV_HLS_8_SEI_NODOC_53  0 // #53 (SEI    /NODOC/Added Multiview view position SEI message) Plain copy from AVC.
@@ -409,5 +363,4 @@
 //#define H_MV_HLS_7_SEI_P0133_28  0 // (SEI/P0133/Recovery point SEI) #28 Decision: Adopt change to recover point semantics only (-v3)
 //#define H_MV_HLS_7_SEI_P0123_25  0 // (SEI/P0123/Alpha channel info) #25 Add alpha channel information SEI message Decision: Adopt. Constrain the bit depth indicated to be equal to the coded bit depth of the aux picture. 
-
 // DPB
 //#define H_MV_HLS_8_HRD_Q0102_09  0 // #9  (HRD    /Q0102/NoOutputOfPriorPicsFlag) It was suggested that also the separate_colour_plane_flag should affect inference of NoOutputOfPriorPicsFlag. Decision (Ed.): Agreed (affects RExt text).
@@ -415,193 +368,110 @@
 //#define H_MV_HLS_8_HRD_Q0154_10  0 // #10 (HRD    /Q0154/DPB Flushing and parameters) On picture flushing and DPB parameters Decision: Adopted (some details to be discussed further in BoG).
 //#define H_MV_HLS_7_OTHER_P0187_1 0 // (OTHER/P0187/NoOutputOfPriorPicsFlag) #1 Inference of NoOutputOfPriorPicsFlag and proposes to take into account colour format and bit depth for the inference in addition to spatial resolution 
-
 // OTHERS
 //#define H_MV_HLS_8_HSB_Q0041_03  0 // #3  (HS     /Q0041/hybrid scalability) The proposed text was endorsed, with non-editorial open issues considered as follows ?// #define H_MV_HLS_7_OTHER_P0187_1          0 // (OTHER/P0187/NoOutputOfPriorPicsFlag) #1 Inference of NoOutputOfPriorPicsFlag and proposes to take into account colour format and bit depth for the inference in addition to spatial resolution 
 //#define H_MV_HLS_8_MIS_Q0078_24  0 // #24 (MISC   /Q0078/scan and pic type) , Items 3 b,c and 4, clarifying which pictures in an output layer sets are applied the values of general_progressive_source_flag, general_interlaced_source_flag, general_non_packed_constraint_flag and general_frame_only_constraint_flag.
 //#define H_MV_HLS_7_HRD_P0138_6   0 //     (HRD/P0138/HRD parameters for bitstreams excluding) #6 Decision: Adopt (as revised in updated contribution, with the specification of a flag in the BP SEI (HRD/P0192/sub-DPB) #12 Establish sub-DPBs based on the representation format indicated at the VPS level. It was suggested that the expressed shared capacity limit would need to be less than or equal to the sum of the individual capacity limits. Decision: Adopt as modified. Further study is encouraged on profile/level constraint selections. 
-
 /////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////   HM RELATED DEFINES ////////////////////////////////
 /////////////////////////////////////////////////////////////////////////////////////////
-#define HARMONIZE_GOP_FIRST_FIELD_COUPLE  1
-#define FIX_FIELD_DEPTH                 1
-#if H_MV
-#define EFFICIENT_FIELD_IRAP            0
-#else
-#define EFFICIENT_FIELD_IRAP            1
-#endif
-#define ALLOW_RECOVERY_POINT_AS_RAP     1
-#define BUGFIX_INTRAPERIOD              1
-#define SAO_ENCODE_ALLOW_USE_PREDEBLOCK 1
-
-#define SAO_SGN_FUNC 1
-
-#define TILE_SIZE_CHECK 1
-
-#define FIX1172 1 ///< fix ticket #1172
-
-#define SETTING_PIC_OUTPUT_MARK     1
-#define SETTING_NO_OUT_PIC_PRIOR    1
-#define FIX_EMPTY_PAYLOAD_NAL       1
-#define FIX_WRITING_OUTPUT          1
-#define FIX_OUTPUT_EOS              1
-
-#define FIX_POC_CRA_NORASL_OUTPUT   1
-
-#define MAX_NUM_PICS_IN_SOP           1024
-
-#define MAX_NESTING_NUM_OPS         1024
-#define MAX_NESTING_NUM_LAYER       64
-
-#if H_MV
-#define MAX_VPS_NUM_HRD_PARAMETERS                1024
-#else
-#define MAX_VPS_NUM_HRD_PARAMETERS                1
-#endif
-#if H_MV
-#define MAX_NUM_SUB_LAYERS                        7
-#define MAX_NUM_SIGNALLED_PARTITIONING_SCHEMES    16
-#endif
-#define MAX_VPS_OP_SETS_PLUS1                     1024
-#if H_MV
-#define MAX_VPS_NUM_ADD_LAYER_SETS                1024
-#define MAX_VPS_NUH_LAYER_ID_PLUS1  63
-#define MAX_NUM_SCALABILITY_TYPES   16
-#define ENC_CFG_CONSOUT_SPACE       29           
-#else
-#define MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1  1
-#endif
-
-
-#define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
-#if H_MV
-#define MAX_NUM_LAYER_IDS               63
-#define MAX_NUM_LAYERS                  63
-#define MAX_VPS_PROFILE_TIER_LEVEL      64
-#define MAX_VPS_ADD_OUTPUT_LAYER_SETS   1024
-#define MAX_VPS_OUTPUTLAYER_SETS        ( MAX_VPS_ADD_OUTPUT_LAYER_SETS + MAX_VPS_OP_SETS_PLUS1 + MAX_VPS_OP_SETS_PLUS1 )
-#define  MAX_NUM_VIDEO_SIGNAL_INFO      16
-#define MAX_NUM_SCALED_REF_LAYERS       MAX_NUM_LAYERS-1
-#else
-#define MAX_NUM_LAYER_IDS                64
-#endif
-
-#define COEF_REMAIN_BIN_REDUCTION        3 ///< indicates the level at which the VLC 
-                                           ///< transitions from Golomb-Rice to TU+EG(k)
-
-#define CU_DQP_TU_CMAX 5                   ///< max number bins for truncated unary
-#define CU_DQP_EG_k 0                      ///< expgolomb order
-
-#define SBH_THRESHOLD                    4  ///< I0156: value of the fixed SBH controlling threshold
-  
-#define SEQUENCE_LEVEL_LOSSLESS           0  ///< H0530: used only for sequence or frame-level lossless coding
-
-#define DISABLING_CLIP_FOR_BIPREDME         1  ///< Ticket #175
-  
-#define C1FLAG_NUMBER               8 // maximum number of largerThan1 flag coded in one chunk :  16 in HM5
-#define C2FLAG_NUMBER               1 // maximum number of largerThan2 flag coded in one chunk:  16 in HM5 
-#define SAO_ENCODING_CHOICE              1  ///< I0184: picture early termination
-#if SAO_ENCODING_CHOICE
-#define SAO_ENCODING_RATE                0.75
-#define SAO_ENCODING_CHOICE_CHROMA       1 ///< J0044: picture early termination Luma and Chroma are handled separately
-#if SAO_ENCODING_CHOICE_CHROMA
-#define SAO_ENCODING_RATE_CHROMA         0.5
-#endif
-#endif
-
-#define MAX_NUM_VPS                16
-#define MAX_NUM_SPS                16
-#define MAX_NUM_PPS                64
-
-#define RDOQ_CHROMA_LAMBDA          1   ///< F386: weighting of chroma for RDOQ
-
-#define MIN_SCAN_POS_CROSS          4
-
-#define FAST_BIT_EST                1   ///< G763: Table-based bit estimation for CABAC
-
-#define MLS_GRP_NUM                         64     ///< G644 : Max number of coefficient groups, max(16, 64)
-#define MLS_CG_SIZE                         4      ///< G644 : Coefficient group size of 4x4
-
-#define ADAPTIVE_QP_SELECTION               1      ///< G382: Adaptive reconstruction levels, non-normative part for adaptive QP selection
-#if ADAPTIVE_QP_SELECTION
-#define ARL_C_PRECISION                     7      ///< G382: 7-bit arithmetic precision
-#define LEVEL_RANGE                         30     ///< G382: max coefficient level in statistics collection
-#endif
-
-#define HHI_RQT_INTRA_SPEEDUP             1           ///< tests one best mode with full rqt
-#define HHI_RQT_INTRA_SPEEDUP_MOD         0           ///< tests two best modes with full rqt
-
+#endif
+// ====================================================================================================================
+// Debugging
+// ====================================================================================================================
+#define DEBUG_STRING                                      0 ///< When enabled, prints out final decision debug info at encoder and decoder
+#define DEBUG_ENCODER_SEARCH_BINS                         0 ///< When enabled, prints out each bin as it is coded during encoder search
+#define DEBUG_CABAC_BINS                                  0 ///< When enabled, prints out each bin as it is coded during final encode and decode
+#define DEBUG_INTRA_SEARCH_COSTS                          0 ///< When enabled, prints out the cost for each mode during encoder search
+#define DEBUG_TRANSFORM_AND_QUANTISE                      0 ///< When enabled, prints out each TU as it passes through the transform-quantise-dequantise-inverseTransform process
+#define ENVIRONMENT_VARIABLE_DEBUG_AND_TEST               0 ///< When enabled, allows control of debug modifications via environment variables
+#define PRINT_MACRO_VALUES                                1 ///< When enabled, the encoder prints out a list of the non-environment-variable controlled macros and their values on startup
+// TODO: rename this macro to DECODER_DEBUG_BIT_STATISTICS (may currently cause merge issues with other branches)
+// This can be enabled by the makefile
+#ifndef RExt__DECODER_DEBUG_BIT_STATISTICS
+#define RExt__DECODER_DEBUG_BIT_STATISTICS                0 ///< 0 (default) = decoder reports as normal, 1 = decoder produces bit usage statistics (will impact decoder run time by up to ~10%)
+#endif
+// This can be enabled by the makefile
+#if !NH_MV
+#ifndef ENC_DEC_TRACE
+#define ENC_DEC_TRACE                                     0
+#endif
+#endif
+#define DEC_NUH_TRACE                                     0 ///< When trace enabled, enable tracing of NAL unit headers at the decoder (currently not possible at the encoder)
+#define PRINT_RPS_INFO                                    0 ///< Enable/disable the printing of bits used to send the RPS.
+// ====================================================================================================================
+// Tool Switches - transitory (these macros are likely to be removed in future revisions)
+// ====================================================================================================================
+#define DECODER_CHECK_SUBSTREAM_AND_SLICE_TRAILING_BYTES  1 ///< TODO: integrate this macro into a broader conformance checking system.
+#define T0196_SELECTIVE_RDOQ                              1 ///< selective RDOQ
+// ====================================================================================================================
+// Tool Switches
+// ====================================================================================================================
+#define ADAPTIVE_QP_SELECTION                             1 ///< G382: Adaptive reconstruction levels, non-normative part for adaptive QP selection
+#define AMP_ENC_SPEEDUP                                   1 ///< encoder only speed-up by AMP mode skipping
+#if AMP_ENC_SPEEDUP
+#define AMP_MRG                                           1 ///< encoder only force merge for AMP partition (no motion search for AMP)
+#endif
+#define FAST_BIT_EST                                      1   ///< G763: Table-based bit estimation for CABAC
+#define HHI_RQT_INTRA_SPEEDUP                             1           ///< tests one best mode with full rqt
+#define HHI_RQT_INTRA_SPEEDUP_MOD                         0           ///< tests two best modes with full rqt
 #if HHI_RQT_INTRA_SPEEDUP_MOD && !HHI_RQT_INTRA_SPEEDUP
 #error
 #endif
-
-#define VERBOSE_RATE 0 ///< Print additional rate information in encoder
-
-#define AMVP_DECIMATION_FACTOR            4
-
-#define SCAN_SET_SIZE                     16
-#define LOG2_SCAN_SET_SIZE                4
-
-#define FAST_UDI_MAX_RDMODE_NUM               35          ///< maximum number of RD comparison in fast-UDI estimation loop 
-
-#define ZERO_MVD_EST                          0           ///< Zero Mvd Estimation in normal mode
-
-#define NUM_INTRA_MODE 36
-#if !REMOVE_LM_CHROMA
-#define LM_CHROMA_IDX  35
-#endif
-
-#define WRITE_BACK                      1           ///< Enable/disable the encoder to replace the deltaPOC and Used by current from the config file with the values derived by the refIdc parameter.
-#define AUTO_INTER_RPS                  1           ///< Enable/disable the automatic generation of refIdc from the deltaPOC and Used by current from the config file.
-#define PRINT_RPS_INFO                  0           ///< Enable/disable the printing of bits used to send the RPS.
-                                                    // using one nearest frame as reference frame, and the other frames are high quality (POC%4==0) frames (1+X)
-                                                    // this should be done with encoder only decision
-                                                    // but because of the absence of reference frame management, the related code was hard coded currently
-
-#define RVM_VCEGAM10_M 4
-
-#define PLANAR_IDX             0
-#define VER_IDX                26                    // index for intra VERTICAL   mode
-#define HOR_IDX                10                    // index for intra HORIZONTAL mode
-#define DC_IDX                 1                     // index for intra DC mode
-#define NUM_CHROMA_MODE        5                     // total number of chroma modes
-#define DM_CHROMA_IDX          36                    // chroma mode index for derived from luma intra mode
-
-
-#define FAST_UDI_USE_MPM 1
-
-#define RDO_WITHOUT_DQP_BITS              0           ///< Disable counting dQP bits in RDO-based mode decision
-
-#define FULL_NBIT 0 ///< When enabled, compute costs using full sample bitdepth.  When disabled, compute costs as if it is 8-bit source video.
+#define MATRIX_MULT                                       0 ///< Brute force matrix multiplication instead of partial butterfly
+#define O0043_BEST_EFFORT_DECODING                        0 ///< 0 (default) = disable code related to best effort decoding, 1 = enable code relating to best effort decoding [ decode-side only ].
+#define RDOQ_CHROMA_LAMBDA                                1 ///< F386: weighting of chroma for RDOQ
+// This can be enabled by the makefile
+#ifndef RExt__HIGH_BIT_DEPTH_SUPPORT
+#define RExt__HIGH_BIT_DEPTH_SUPPORT                                           0 ///< 0 (default) use data type definitions for 8-10 bit video, 1 = use larger data types to allow for up to 16-bit video (originally developed as part of N0188)
+#endif
+// ====================================================================================================================
+// Derived macros
+// ====================================================================================================================
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+#define FULL_NBIT                                                              1 ///< When enabled, use distortion measure derived from all bits of source data, otherwise discard (bitDepth - 8) least-significant bits of distortion
+#define RExt__HIGH_PRECISION_FORWARD_TRANSFORM                                 1 ///< 0 use original 6-bit transform matrices for both forward and inverse transform, 1 (default) = use original matrices for inverse transform and high precision matrices for forward transform
+#else
+#define FULL_NBIT                                                              0 ///< When enabled, use distortion measure derived from all bits of source data, otherwise discard (bitDepth - 8) least-significant bits of distortion
+#define RExt__HIGH_PRECISION_FORWARD_TRANSFORM                                 0 ///< 0 (default) use original 6-bit transform matrices for both forward and inverse transform, 1 = use original matrices for inverse transform and high precision matrices for forward transform
+#endif
 #if FULL_NBIT
-# define DISTORTION_PRECISION_ADJUSTMENT(x) 0
+# define DISTORTION_PRECISION_ADJUSTMENT(x)  0
 #else
 # define DISTORTION_PRECISION_ADJUSTMENT(x) (x)
 #endif
-
-#define LOG2_MAX_NUM_COLUMNS_MINUS1        7
-#define LOG2_MAX_NUM_ROWS_MINUS1           7
-#define LOG2_MAX_COLUMN_WIDTH              13
-#define LOG2_MAX_ROW_HEIGHT                13
-
-#define MATRIX_MULT                             0   // Brute force matrix multiplication instead of partial butterfly
-
-#define REG_DCT 65535
-
-#define AMP_SAD                               1           ///< dedicated SAD functions for AMP
-#define AMP_ENC_SPEEDUP                       1           ///< encoder only speed-up by AMP mode skipping
-#if AMP_ENC_SPEEDUP
-#define AMP_MRG                               1           ///< encoder only force merge for AMP partition (no motion search for AMP)
-#endif
-
-#define CABAC_INIT_PRESENT_FLAG     1
-
+#if DEBUG_STRING
+  #define DEBUG_STRING_PASS_INTO(name) , name
+  #define DEBUG_STRING_PASS_INTO_OPTIONAL(name, exp) , (exp==0)?0:name
+  #define DEBUG_STRING_FN_DECLARE(name) , std::string &name
+  #define DEBUG_STRING_FN_DECLAREP(name) , std::string *name
+  #define DEBUG_STRING_NEW(name) std::string name;
+  #define DEBUG_STRING_OUTPUT(os, name) os << name;
+  #define DEBUG_STRING_APPEND(str1, str2) str1+=str2;
+  #define DEBUG_STRING_SWAP(str1, str2) str1.swap(str2);
+  #define DEBUG_STRING_CHANNEL_CONDITION(compID) (true)
+  #include <sstream>
+  #include <iomanip>
+#else
+  #define DEBUG_STRING_PASS_INTO(name)
+  #define DEBUG_STRING_PASS_INTO_OPTIONAL(name, exp)
+  #define DEBUG_STRING_FN_DECLARE(name)
+  #define DEBUG_STRING_FN_DECLAREP(name)
+  #define DEBUG_STRING_NEW(name)
+  #define DEBUG_STRING_OUTPUT(os, name)
+  #define DEBUG_STRING_APPEND(str1, str2)
+  #define DEBUG_STRING_SWAP(srt1, str2)
+  #define DEBUG_STRING_CHANNEL_CONDITION(compID)
+#endif
+// ====================================================================================================================
+// Error checks
+// ====================================================================================================================
+#if ((RExt__HIGH_PRECISION_FORWARD_TRANSFORM != 0) && (RExt__HIGH_BIT_DEPTH_SUPPORT == 0))
+#error ERROR: cannot enable RExt__HIGH_PRECISION_FORWARD_TRANSFORM without RExt__HIGH_BIT_DEPTH_SUPPORT
+#endif
 // ====================================================================================================================
 // Basic type redefinition
 // ====================================================================================================================
-
 typedef       void                Void;
 typedef       bool                Bool;
-
 #ifdef __arm__
 typedef       signed char         Char;
@@ -616,12 +486,9 @@
 typedef       double              Double;
 typedef       float               Float;
-
 // ====================================================================================================================
 // 64-bit integer type
 // ====================================================================================================================
-
 #ifdef _MSC_VER
 typedef       __int64             Int64;
-
 #if _MSC_VER <= 1200 // MS VC6
 typedef       __int64             UInt64;   // MS VC6 does not support unsigned __int64 to double conversion
@@ -629,26 +496,48 @@
 typedef       unsigned __int64    UInt64;
 #endif
-
 #else
-
 typedef       long long           Int64;
 typedef       unsigned long long  UInt64;
-
-#endif
-
-// ====================================================================================================================
-// Type definition
-// ====================================================================================================================
-
-typedef       UChar           Pxl;        ///< 8-bit pixel type
-typedef       Short           Pel;        ///< 16-bit pixel type
-typedef       Int             TCoeff;     ///< transform coefficient
-
-#if H_3D_VSO
+#endif
+// ====================================================================================================================
+// Named numerical types
+// ====================================================================================================================
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+typedef       Int             Pel;               ///< pixel type
+typedef       Int64           TCoeff;            ///< transform coefficient
+typedef       Int             TMatrixCoeff;      ///< transform matrix coefficient
+typedef       Short           TFilterCoeff;      ///< filter coefficient
+typedef       Int64           Intermediate_Int;  ///< used as intermediate value in calculations
+typedef       UInt64          Intermediate_UInt; ///< used as intermediate value in calculations
+#else
+typedef       Short           Pel;               ///< pixel type
+typedef       Int             TCoeff;            ///< transform coefficient
+typedef       Short           TMatrixCoeff;      ///< transform matrix coefficient
+typedef       Short           TFilterCoeff;      ///< filter coefficient
+typedef       Int             Intermediate_Int;  ///< used as intermediate value in calculations
+typedef       UInt            Intermediate_UInt; ///< used as intermediate value in calculations
+#endif
+#if FULL_NBIT
+typedef       UInt64          Distortion;        ///< distortion measurement
+#else
+typedef       UInt            Distortion;        ///< distortion measurement
+#endif
+#if NH_MV                         
+typedef std::vector< Int >        IntAry1d;
+typedef std::vector< IntAry1d >   IntAry2d; 
+typedef std::vector< IntAry2d >   IntAry3d; 
+typedef std::vector< IntAry3d >   IntAry4d; 
+typedef std::vector< IntAry4d >   IntAry5d; 
+typedef std::vector< Bool >        BoolAry1d;
+typedef std::vector< BoolAry1d >   BoolAry2d; 
+typedef std::vector< BoolAry2d >   BoolAry3d; 
+typedef std::vector< BoolAry3d >   BoolAry4d; 
+typedef std::vector< BoolAry4d >   BoolAry5d; 
+#endif
+#if NH_3D_VSO
 // ====================================================================================================================
 // Define Distortion Types
 // ====================================================================================================================
 typedef       Int64           RMDist;     ///< renderer model distortion
-
 #if H_3D_VSO_DIST_INT
 typedef       Int64            Dist;       ///< RDO distortion
@@ -663,212 +552,125 @@
 #endif
 #endif
-/// parameters for adaptive loop filter
-class TComPicSym;
-
-// Slice / Slice segment encoding modes
-enum SliceConstraint
-{
-  NO_SLICES              = 0,          ///< don't use slices / slice segments
-  FIXED_NUMBER_OF_LCU    = 1,          ///< Limit maximum number of largest coding tree blocks in a slice / slice segments
-  FIXED_NUMBER_OF_BYTES  = 2,          ///< Limit maximum number of bytes in a slice / slice segment
-  FIXED_NUMBER_OF_TILES  = 3,          ///< slices / slice segments span an integer number of tiles
-};
-
-enum SAOComponentIdx
-{
-  SAO_Y =0,
-  SAO_Cb,
-  SAO_Cr,
-  NUM_SAO_COMPONENTS
-};
-
-enum SAOMode //mode
-{
-  SAO_MODE_OFF = 0,
-  SAO_MODE_NEW,
-  SAO_MODE_MERGE,
-  NUM_SAO_MODES
-};
-
-enum SAOModeMergeTypes 
-{
-  SAO_MERGE_LEFT =0,
-  SAO_MERGE_ABOVE,
-  NUM_SAO_MERGE_TYPES
-};
-
-
-enum SAOModeNewTypes 
-{
-  SAO_TYPE_START_EO =0,
-  SAO_TYPE_EO_0 = SAO_TYPE_START_EO,
-  SAO_TYPE_EO_90,
-  SAO_TYPE_EO_135,
-  SAO_TYPE_EO_45,
-
-  SAO_TYPE_START_BO,
-  SAO_TYPE_BO = SAO_TYPE_START_BO,
-
-  NUM_SAO_NEW_TYPES
-};
-#define NUM_SAO_EO_TYPES_LOG2 2
-
-enum SAOEOClasses 
-{
-  SAO_CLASS_EO_FULL_VALLEY = 0,
-  SAO_CLASS_EO_HALF_VALLEY = 1,
-  SAO_CLASS_EO_PLAIN       = 2,
-  SAO_CLASS_EO_HALF_PEAK   = 3,
-  SAO_CLASS_EO_FULL_PEAK   = 4,
-  NUM_SAO_EO_CLASSES,
-};
-
-
-#define NUM_SAO_BO_CLASSES_LOG2  5
-enum SAOBOClasses
-{
-  //SAO_CLASS_BO_BAND0 = 0,
-  //SAO_CLASS_BO_BAND1,
-  //SAO_CLASS_BO_BAND2,
-  //...
-  //SAO_CLASS_BO_BAND31,
-
-  NUM_SAO_BO_CLASSES = (1<<NUM_SAO_BO_CLASSES_LOG2),
-};
-#define MAX_NUM_SAO_CLASSES  32  //(NUM_SAO_EO_GROUPS > NUM_SAO_BO_GROUPS)?NUM_SAO_EO_GROUPS:NUM_SAO_BO_GROUPS
-
-struct SAOOffset
-{
-  Int modeIdc; //NEW, MERGE, OFF
-  Int typeIdc; //NEW: EO_0, EO_90, EO_135, EO_45, BO. MERGE: left, above
-  Int typeAuxInfo; //BO: starting band index
-  Int offset[MAX_NUM_SAO_CLASSES];
-
-  SAOOffset();
-  ~SAOOffset();
-  Void reset();
-
-  const SAOOffset& operator= (const SAOOffset& src);
-};
-
-struct SAOBlkParam
-{
-
-  SAOBlkParam();
-  ~SAOBlkParam();
-  Void reset();
-  const SAOBlkParam& operator= (const SAOBlkParam& src);
-  SAOOffset& operator[](Int compIdx){ return offsetParam[compIdx];}
-private:
-  SAOOffset offsetParam[NUM_SAO_COMPONENTS];
-
-};
-
-/// parameters for deblocking filter
-typedef struct _LFCUParam
-{
-  Bool bInternalEdge;                     ///< indicates internal edge
-  Bool bLeftEdge;                         ///< indicates left edge
-  Bool bTopEdge;                          ///< indicates top edge
-} LFCUParam;
-
 // ====================================================================================================================
 // Enumeration
 // ====================================================================================================================
-
+enum RDPCMMode
+{
+  RDPCM_OFF             = 0,
+  RDPCM_HOR             = 1,
+  RDPCM_VER             = 2,
+  NUMBER_OF_RDPCM_MODES = 3
+};
+enum RDPCMSignallingMode
+{
+  RDPCM_SIGNAL_IMPLICIT            = 0,
+  RDPCM_SIGNAL_EXPLICIT            = 1,
+  NUMBER_OF_RDPCM_SIGNALLING_MODES = 2
+};
 /// supported slice type
 enum SliceType
 {
-  B_SLICE,
-  P_SLICE,
-  I_SLICE
-};
-
+  B_SLICE               = 0,
+  P_SLICE               = 1,
+  I_SLICE               = 2,
+  NUMBER_OF_SLICE_TYPES = 3
+};
 /// chroma formats (according to semantics of chroma_format_idc)
 enum ChromaFormat
 {
-  CHROMA_400  = 0,
-  CHROMA_420  = 1,
-  CHROMA_422  = 2,
-  CHROMA_444  = 3
-};
-
+  CHROMA_400        = 0,
+  CHROMA_420        = 1,
+  CHROMA_422        = 2,
+  CHROMA_444        = 3,
+  NUM_CHROMA_FORMAT = 4
+};
+enum ChannelType
+{
+  CHANNEL_TYPE_LUMA    = 0,
+  CHANNEL_TYPE_CHROMA  = 1,
+  MAX_NUM_CHANNEL_TYPE = 2
+};
+enum ComponentID
+{
+  COMPONENT_Y       = 0,
+  COMPONENT_Cb      = 1,
+  COMPONENT_Cr      = 2,
+  MAX_NUM_COMPONENT = 3
+};
+enum InputColourSpaceConversion // defined in terms of conversion prior to input of encoder.
+{
+  IPCOLOURSPACE_UNCHANGED               = 0,
+  IPCOLOURSPACE_YCbCrtoYCrCb            = 1, // Mainly used for debug!
+  IPCOLOURSPACE_YCbCrtoYYY              = 2, // Mainly used for debug!
+  IPCOLOURSPACE_RGBtoGBR                = 3,
+  NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS = 4
+};
+enum DeblockEdgeDir
+{
+  EDGE_VER     = 0,
+  EDGE_HOR     = 1,
+  NUM_EDGE_DIR = 2
+};
 /// supported partition shape
 enum PartSize
 {
-  SIZE_2Nx2N,           ///< symmetric motion partition,  2Nx2N
-  SIZE_2NxN,            ///< symmetric motion partition,  2Nx N
-  SIZE_Nx2N,            ///< symmetric motion partition,   Nx2N
-  SIZE_NxN,             ///< symmetric motion partition,   Nx N
-  SIZE_2NxnU,           ///< asymmetric motion partition, 2Nx( N/2) + 2Nx(3N/2)
-  SIZE_2NxnD,           ///< asymmetric motion partition, 2Nx(3N/2) + 2Nx( N/2)
-  SIZE_nLx2N,           ///< asymmetric motion partition, ( N/2)x2N + (3N/2)x2N
-  SIZE_nRx2N,           ///< asymmetric motion partition, (3N/2)x2N + ( N/2)x2N
-  SIZE_NONE = 15
-};
-
+  SIZE_2Nx2N           = 0,           ///< symmetric motion partition,  2Nx2N
+  SIZE_2NxN            = 1,           ///< symmetric motion partition,  2Nx N
+  SIZE_Nx2N            = 2,           ///< symmetric motion partition,   Nx2N
+  SIZE_NxN             = 3,           ///< symmetric motion partition,   Nx N
+  SIZE_2NxnU           = 4,           ///< asymmetric motion partition, 2Nx( N/2) + 2Nx(3N/2)
+  SIZE_2NxnD           = 5,           ///< asymmetric motion partition, 2Nx(3N/2) + 2Nx( N/2)
+  SIZE_nLx2N           = 6,           ///< asymmetric motion partition, ( N/2)x2N + (3N/2)x2N
+  SIZE_nRx2N           = 7,           ///< asymmetric motion partition, (3N/2)x2N + ( N/2)x2N
+  NUMBER_OF_PART_SIZES = 8
+};
 /// supported prediction type
 enum PredMode
 {
-  MODE_INTER,           ///< inter-prediction mode
-  MODE_INTRA,           ///< intra-prediction mode
-  MODE_NONE = 15
-};
-
-/// texture component type
-enum TextType
-{
-  TEXT_LUMA,            ///< luma
-  TEXT_CHROMA,          ///< chroma (U+V)
-  TEXT_CHROMA_U,        ///< chroma U
-  TEXT_CHROMA_V,        ///< chroma V
-  TEXT_ALL,             ///< Y+U+V
-  TEXT_NONE = 15
-};
-
+  MODE_INTER                 = 0,     ///< inter-prediction mode
+  MODE_INTRA                 = 1,     ///< intra-prediction mode
+  NUMBER_OF_PREDICTION_MODES = 2,
+};
 /// reference list index
 enum RefPicList
 {
-  REF_PIC_LIST_0 = 0,   ///< reference list 0
-  REF_PIC_LIST_1 = 1,   ///< reference list 1
-  REF_PIC_LIST_X = 100  ///< special mark
-};
-
+  REF_PIC_LIST_0               = 0,   ///< reference list 0
+  REF_PIC_LIST_1               = 1,   ///< reference list 1
+  NUM_REF_PIC_LIST_01          = 2,
+  REF_PIC_LIST_X               = 100  ///< special mark
+};
 /// distortion function index
 enum DFunc
 {
-  DF_DEFAULT  = 0,
-  DF_SSE      = 1,      ///< general size SSE
-  DF_SSE4     = 2,      ///<   4xM SSE
-  DF_SSE8     = 3,      ///<   8xM SSE
-  DF_SSE16    = 4,      ///<  16xM SSE
-  DF_SSE32    = 5,      ///<  32xM SSE
-  DF_SSE64    = 6,      ///<  64xM SSE
-  DF_SSE16N   = 7,      ///< 16NxM SSE
-  
-  DF_SAD      = 8,      ///< general size SAD
-  DF_SAD4     = 9,      ///<   4xM SAD
-  DF_SAD8     = 10,     ///<   8xM SAD
-  DF_SAD16    = 11,     ///<  16xM SAD
-  DF_SAD32    = 12,     ///<  32xM SAD
-  DF_SAD64    = 13,     ///<  64xM SAD
-  DF_SAD16N   = 14,     ///< 16NxM SAD
-  
-  DF_SADS     = 15,     ///< general size SAD with step
-  DF_SADS4    = 16,     ///<   4xM SAD with step
-  DF_SADS8    = 17,     ///<   8xM SAD with step
-  DF_SADS16   = 18,     ///<  16xM SAD with step
-  DF_SADS32   = 19,     ///<  32xM SAD with step
-  DF_SADS64   = 20,     ///<  64xM SAD with step
-  DF_SADS16N  = 21,     ///< 16NxM SAD with step
-  
-  DF_HADS     = 22,     ///< general size Hadamard with step
-  DF_HADS4    = 23,     ///<   4xM HAD with step
-  DF_HADS8    = 24,     ///<   8xM HAD with step
-  DF_HADS16   = 25,     ///<  16xM HAD with step
-  DF_HADS32   = 26,     ///<  32xM HAD with step
-  DF_HADS64   = 27,     ///<  64xM HAD with step
-  DF_HADS16N  = 28,     ///< 16NxM HAD with step
-#if H_3D_VSO
+  DF_DEFAULT         = 0,
+  DF_SSE             = 1,      ///< general size SSE
+  DF_SSE4            = 2,      ///<   4xM SSE
+  DF_SSE8            = 3,      ///<   8xM SSE
+  DF_SSE16           = 4,      ///<  16xM SSE
+  DF_SSE32           = 5,      ///<  32xM SSE
+  DF_SSE64           = 6,      ///<  64xM SSE
+  DF_SSE16N          = 7,      ///< 16NxM SSE
+  DF_SAD             = 8,      ///< general size SAD
+  DF_SAD4            = 9,      ///<   4xM SAD
+  DF_SAD8            = 10,     ///<   8xM SAD
+  DF_SAD16           = 11,     ///<  16xM SAD
+  DF_SAD32           = 12,     ///<  32xM SAD
+  DF_SAD64           = 13,     ///<  64xM SAD
+  DF_SAD16N          = 14,     ///< 16NxM SAD
+  DF_SADS            = 15,     ///< general size SAD with step
+  DF_SADS4           = 16,     ///<   4xM SAD with step
+  DF_SADS8           = 17,     ///<   8xM SAD with step
+  DF_SADS16          = 18,     ///<  16xM SAD with step
+  DF_SADS32          = 19,     ///<  32xM SAD with step
+  DF_SADS64          = 20,     ///<  64xM SAD with step
+  DF_SADS16N         = 21,     ///< 16NxM SAD with step
+  DF_HADS            = 22,     ///< general size Hadamard with step
+  DF_HADS4           = 23,     ///<   4xM HAD with step
+  DF_HADS8           = 24,     ///<   8xM HAD with step
+  DF_HADS16          = 25,     ///<  16xM HAD with step
+  DF_HADS32          = 26,     ///<  32xM HAD with step
+  DF_HADS64          = 27,     ///<  64xM HAD with step
+  DF_HADS16N         = 28,     ///< 16NxM HAD with step
+#if NH_3D_VSO
   DF_VSD      = 29,      ///< general size VSD
   DF_VSD4     = 30,      ///<   4xM VSD
@@ -879,20 +681,13 @@
   DF_VSD16N   = 35,      ///< 16NxM VSD
 #endif
-
-#if AMP_SAD
-  DF_SAD12    = 43,
-  DF_SAD24    = 44,
-  DF_SAD48    = 45,
-
-  DF_SADS12   = 46,
-  DF_SADS24   = 47,
-  DF_SADS48   = 48,
-
-  DF_SSE_FRAME = 50     ///< Frame-based SSE
-#else
-  DF_SSE_FRAME = 33     ///< Frame-based SSE
-#endif
-};
-
+  DF_SAD12           = 43,
+  DF_SAD24           = 44,
+  DF_SAD48           = 45,
+  DF_SADS12          = 46,
+  DF_SADS24          = 47,
+  DF_SADS48          = 48,
+  DF_SSE_FRAME       = 50,     ///< Frame-based SSE
+  DF_TOTAL_FUNCTIONS = 64
+};
 /// index for SBAC based RD optimization
 enum CI_IDX
@@ -906,5 +701,4 @@
   CI_NUM,               ///< total number
 };
-
 /// motion vector predictor direction used in AMVP
 enum MVP_DIR
@@ -916,6 +710,4 @@
   MD_ABOVE_LEFT         ///< MVP of above left block
 };
-
-/// merging candidates
 #if H_3D
 enum DefaultMergCandOrder
@@ -935,13 +727,103 @@
 };
 #endif
-
+enum StoredResidualType
+{
+  RESIDUAL_RECONSTRUCTED          = 0,
+  RESIDUAL_ENCODER_SIDE           = 1,
+  NUMBER_OF_STORED_RESIDUAL_TYPES = 2
+};
+enum TransformDirection
+{
+  TRANSFORM_FORWARD              = 0,
+  TRANSFORM_INVERSE              = 1,
+  TRANSFORM_NUMBER_OF_DIRECTIONS = 2
+};
+/// supported ME search methods
+enum MESearchMethod
+{
+  FULL_SEARCH                = 0,     ///< Full search
+  DIAMOND                    = 1,     ///< Fast search
+  SELECTIVE                  = 2      ///< Selective search
+};
 /// coefficient scanning type used in ACS
 enum COEFF_SCAN_TYPE
 {
-  SCAN_DIAG = 0,         ///< up-right diagonal scan
-  SCAN_HOR,              ///< horizontal first scan
-  SCAN_VER               ///< vertical first scan
-};
-
+  SCAN_DIAG = 0,        ///< up-right diagonal scan
+  SCAN_HOR  = 1,        ///< horizontal first scan
+  SCAN_VER  = 2,        ///< vertical first scan
+  SCAN_NUMBER_OF_TYPES = 3
+};
+enum COEFF_SCAN_GROUP_TYPE
+{
+  SCAN_UNGROUPED   = 0,
+  SCAN_GROUPED_4x4 = 1,
+  SCAN_NUMBER_OF_GROUP_TYPES = 2
+};
+enum SignificanceMapContextType
+{
+  CONTEXT_TYPE_4x4    = 0,
+  CONTEXT_TYPE_8x8    = 1,
+  CONTEXT_TYPE_NxN    = 2,
+  CONTEXT_TYPE_SINGLE = 3,
+  CONTEXT_NUMBER_OF_TYPES = 4
+};
+enum ScalingListMode
+{
+  SCALING_LIST_OFF,
+  SCALING_LIST_DEFAULT,
+  SCALING_LIST_FILE_READ
+};
+enum ScalingListSize
+{
+  SCALING_LIST_4x4 = 0,
+  SCALING_LIST_8x8,
+  SCALING_LIST_16x16,
+  SCALING_LIST_32x32,
+  SCALING_LIST_SIZE_NUM
+};
+// Slice / Slice segment encoding modes
+enum SliceConstraint
+{
+  NO_SLICES              = 0,          ///< don't use slices / slice segments
+  FIXED_NUMBER_OF_CTU    = 1,          ///< Limit maximum number of largest coding tree units in a slice / slice segments
+  FIXED_NUMBER_OF_BYTES  = 2,          ///< Limit maximum number of bytes in a slice / slice segment
+  FIXED_NUMBER_OF_TILES  = 3,          ///< slices / slice segments span an integer number of tiles
+};
+enum SAOMode //mode
+{
+  SAO_MODE_OFF = 0,
+  SAO_MODE_NEW,
+  SAO_MODE_MERGE,
+  NUM_SAO_MODES
+};
+enum SAOModeMergeTypes
+{
+  SAO_MERGE_LEFT =0,
+  SAO_MERGE_ABOVE,
+  NUM_SAO_MERGE_TYPES
+};
+enum SAOModeNewTypes
+{
+  SAO_TYPE_START_EO =0,
+  SAO_TYPE_EO_0 = SAO_TYPE_START_EO,
+  SAO_TYPE_EO_90,
+  SAO_TYPE_EO_135,
+  SAO_TYPE_EO_45,
+  SAO_TYPE_START_BO,
+  SAO_TYPE_BO = SAO_TYPE_START_BO,
+  NUM_SAO_NEW_TYPES
+};
+#define NUM_SAO_EO_TYPES_LOG2 2
+enum SAOEOClasses
+{
+  SAO_CLASS_EO_FULL_VALLEY = 0,
+  SAO_CLASS_EO_HALF_VALLEY = 1,
+  SAO_CLASS_EO_PLAIN       = 2,
+  SAO_CLASS_EO_HALF_PEAK   = 3,
+  SAO_CLASS_EO_FULL_PEAK   = 4,
+  NUM_SAO_EO_CLASSES,
+};
+#define NUM_SAO_BO_CLASSES_LOG2  5
+#define NUM_SAO_BO_CLASSES       (1<<NUM_SAO_BO_CLASSES_LOG2)
 namespace Profile
 {
@@ -952,7 +834,9 @@
     MAIN10 = 2,
     MAINSTILLPICTURE = 3,
-#if H_MV
-    MULTIVIEWMAIN = 6,
-#if H_3D
+    MAINREXT = 4,
+    HIGHTHROUGHPUTREXT = 5
+#if NH_MV
+    ,MULTIVIEWMAIN = 6,
+#if NH_3D
     MAIN3D = 8, 
 #endif
@@ -960,5 +844,4 @@
   };
 }
-
 namespace Level
 {
@@ -968,7 +851,7 @@
     HIGH = 1,
   };
-
   enum Name
   {
+    // code = (level * 30)
     NONE     = 0,
     LEVEL1   = 30,
@@ -985,42 +868,248 @@
     LEVEL6_1 = 183,
     LEVEL6_2 = 186,
+    LEVEL8_5 = 255,
   };
 }
+enum CostMode
+{
+  COST_STANDARD_LOSSY              = 0,
+  COST_SEQUENCE_LEVEL_LOSSLESS     = 1,
+  COST_LOSSLESS_CODING             = 2,
+  COST_MIXED_LOSSLESS_LOSSY_CODING = 3
+};
+enum SPSExtensionFlagIndex
+{
+  SPS_EXT__REXT           = 0,
+//SPS_EXT__MVHEVC         = 1, //for use in future versions
+//SPS_EXT__SHVC           = 2, //for use in future versions
+  NUM_SPS_EXTENSION_FLAGS = 8
+};
+enum PPSExtensionFlagIndex
+{
+  PPS_EXT__REXT           = 0,
+//PPS_EXT__MVHEVC         = 1, //for use in future versions
+//PPS_EXT__SHVC           = 2, //for use in future versions
+  NUM_PPS_EXTENSION_FLAGS = 8
+};
+// TODO: Existing names used for the different NAL unit types can be altered to better reflect the names in the spec.
+//       However, the names in the spec are not yet stable at this point. Once the names are stable, a cleanup
+//       effort can be done without use of macros to alter the names used to indicate the different NAL unit types.
+enum NalUnitType
+{
+  NAL_UNIT_CODED_SLICE_TRAIL_N = 0, // 0
+  NAL_UNIT_CODED_SLICE_TRAIL_R,     // 1
+  NAL_UNIT_CODED_SLICE_TSA_N,       // 2
+  NAL_UNIT_CODED_SLICE_TSA_R,       // 3
+  NAL_UNIT_CODED_SLICE_STSA_N,      // 4
+  NAL_UNIT_CODED_SLICE_STSA_R,      // 5
+  NAL_UNIT_CODED_SLICE_RADL_N,      // 6
+  NAL_UNIT_CODED_SLICE_RADL_R,      // 7
+  NAL_UNIT_CODED_SLICE_RASL_N,      // 8
+  NAL_UNIT_CODED_SLICE_RASL_R,      // 9
+  NAL_UNIT_RESERVED_VCL_N10,
+  NAL_UNIT_RESERVED_VCL_R11,
+  NAL_UNIT_RESERVED_VCL_N12,
+  NAL_UNIT_RESERVED_VCL_R13,
+  NAL_UNIT_RESERVED_VCL_N14,
+  NAL_UNIT_RESERVED_VCL_R15,
+  NAL_UNIT_CODED_SLICE_BLA_W_LP,    // 16
+  NAL_UNIT_CODED_SLICE_BLA_W_RADL,  // 17
+  NAL_UNIT_CODED_SLICE_BLA_N_LP,    // 18
+  NAL_UNIT_CODED_SLICE_IDR_W_RADL,  // 19
+  NAL_UNIT_CODED_SLICE_IDR_N_LP,    // 20
+  NAL_UNIT_CODED_SLICE_CRA,         // 21
+  NAL_UNIT_RESERVED_IRAP_VCL22,
+  NAL_UNIT_RESERVED_IRAP_VCL23,
+  NAL_UNIT_RESERVED_VCL24,
+  NAL_UNIT_RESERVED_VCL25,
+  NAL_UNIT_RESERVED_VCL26,
+  NAL_UNIT_RESERVED_VCL27,
+  NAL_UNIT_RESERVED_VCL28,
+  NAL_UNIT_RESERVED_VCL29,
+  NAL_UNIT_RESERVED_VCL30,
+  NAL_UNIT_RESERVED_VCL31,
+  NAL_UNIT_VPS,                     // 32
+  NAL_UNIT_SPS,                     // 33
+  NAL_UNIT_PPS,                     // 34
+  NAL_UNIT_ACCESS_UNIT_DELIMITER,   // 35
+  NAL_UNIT_EOS,                     // 36
+  NAL_UNIT_EOB,                     // 37
+  NAL_UNIT_FILLER_DATA,             // 38
+  NAL_UNIT_PREFIX_SEI,              // 39
+  NAL_UNIT_SUFFIX_SEI,              // 40
+  NAL_UNIT_RESERVED_NVCL41,
+  NAL_UNIT_RESERVED_NVCL42,
+  NAL_UNIT_RESERVED_NVCL43,
+  NAL_UNIT_RESERVED_NVCL44,
+  NAL_UNIT_RESERVED_NVCL45,
+  NAL_UNIT_RESERVED_NVCL46,
+  NAL_UNIT_RESERVED_NVCL47,
+  NAL_UNIT_UNSPECIFIED_48,
+  NAL_UNIT_UNSPECIFIED_49,
+  NAL_UNIT_UNSPECIFIED_50,
+  NAL_UNIT_UNSPECIFIED_51,
+  NAL_UNIT_UNSPECIFIED_52,
+  NAL_UNIT_UNSPECIFIED_53,
+  NAL_UNIT_UNSPECIFIED_54,
+  NAL_UNIT_UNSPECIFIED_55,
+  NAL_UNIT_UNSPECIFIED_56,
+  NAL_UNIT_UNSPECIFIED_57,
+  NAL_UNIT_UNSPECIFIED_58,
+  NAL_UNIT_UNSPECIFIED_59,
+  NAL_UNIT_UNSPECIFIED_60,
+  NAL_UNIT_UNSPECIFIED_61,
+  NAL_UNIT_UNSPECIFIED_62,
+  NAL_UNIT_UNSPECIFIED_63,
+  NAL_UNIT_INVALID,
+};
+#if NH_MV
+/// scalability types
+enum ScalabilityType
+{
+  DEPTH_ID = 0,    
+  VIEW_ORDER_INDEX  = 1,
+  DEPENDENCY_ID = 2,
+  AUX_ID = 3,
+};
+#endif
+#if NH_3D
+// Renderer
+enum BlenMod
+{
+  BLEND_NONE  = -1,
+  BLEND_AVRG  = 0,
+  BLEND_LEFT  = 1,
+  BLEND_RIGHT = 2,
+  BLEND_GEN   =  3
+};
+enum
+{
+  VIEWPOS_INVALID = -1,
+  VIEWPOS_LEFT    = 0,
+  VIEWPOS_RIGHT   = 1,
+  VIEWPOS_MERGED  = 2
+};
+#endif
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+/// parameters for adaptive loop filter
+class TComPicSym;
+#define MAX_NUM_SAO_CLASSES  32  //(NUM_SAO_EO_GROUPS > NUM_SAO_BO_GROUPS)?NUM_SAO_EO_GROUPS:NUM_SAO_BO_GROUPS
+struct SAOOffset
+{
+  SAOMode modeIdc; // NEW, MERGE, OFF
+  Int typeIdc;     // union of SAOModeMergeTypes and SAOModeNewTypes, depending on modeIdc.
+  Int typeAuxInfo; // BO: starting band index
+  Int offset[MAX_NUM_SAO_CLASSES];
+  SAOOffset();
+  ~SAOOffset();
+  Void reset();
+  const SAOOffset& operator= (const SAOOffset& src);
+};
+struct SAOBlkParam
+{
+  SAOBlkParam();
+  ~SAOBlkParam();
+  Void reset();
+  const SAOBlkParam& operator= (const SAOBlkParam& src);
+  SAOOffset& operator[](Int compIdx){ return offsetParam[compIdx];}
+private:
+  SAOOffset offsetParam[MAX_NUM_COMPONENT];
+};
+struct BitDepths
+{
+#if O0043_BEST_EFFORT_DECODING
+  Int recon[MAX_NUM_CHANNEL_TYPE]; ///< the bit depth used for reconstructing the video
+  Int stream[MAX_NUM_CHANNEL_TYPE];///< the bit depth used indicated in the SPS
+#else
+  Int recon[MAX_NUM_CHANNEL_TYPE]; ///< the bit depth as indicated in the SPS
+#endif
+};
+/// parameters for deblocking filter
+typedef struct _LFCUParam
+{
+  Bool bInternalEdge;                     ///< indicates internal edge
+  Bool bLeftEdge;                         ///< indicates left edge
+  Bool bTopEdge;                          ///< indicates top edge
+} LFCUParam;
+//TU settings for entropy encoding
+struct TUEntropyCodingParameters
+{
+  const UInt            *scan;
+  const UInt            *scanCG;
+        COEFF_SCAN_TYPE  scanType;
+        UInt             widthInGroups;
+        UInt             heightInGroups;
+        UInt             firstSignificanceMapContext;
+};
+struct TComPictureHash
+{
+  std::vector<UChar> hash;
+  Bool operator==(const TComPictureHash &other) const
+  {
+    if (other.hash.size() != hash.size())
+    {
+      return false;
+    }
+    for(UInt i=0; i<UInt(hash.size()); i++)
+    {
+      if (other.hash[i] != hash[i])
+      {
+        return false;
+      }
+    }
+    return true;
+  }
+  Bool operator!=(const TComPictureHash &other) const
+  {
+    return !(*this == other);
+  }
+};
+struct TComSEITimeSet
+{
+  TComSEITimeSet() : clockTimeStampFlag(false),
+                     numUnitFieldBasedFlag(false),
+                     countingType(0),
+                     fullTimeStampFlag(false),
+                     discontinuityFlag(false),
+                     cntDroppedFlag(false),
+                     numberOfFrames(0),
+                     secondsValue(0),
+                     minutesValue(0),
+                     hoursValue(0),
+                     secondsFlag(false),
+                     minutesFlag(false),
+                     hoursFlag(false),
+                     timeOffsetLength(0),
+                     timeOffsetValue(0)
+  { }
+  Bool clockTimeStampFlag;
+  Bool numUnitFieldBasedFlag;
+  Int  countingType;
+  Bool fullTimeStampFlag;
+  Bool discontinuityFlag;
+  Bool cntDroppedFlag;
+  Int  numberOfFrames;
+  Int  secondsValue;
+  Int  minutesValue;
+  Int  hoursValue;
+  Bool secondsFlag;
+  Bool minutesFlag;
+  Bool hoursFlag;
+  Int  timeOffsetLength;
+  Int  timeOffsetValue;
+};
+struct TComSEIMasteringDisplay
+{
+  Bool      colourVolumeSEIEnabled;
+  UInt      maxLuminance;
+  UInt      minLuminance;
+  UShort    primaries[3][2];
+  UShort    whitePoint[2];
+};
 //! \}
-
-#if H_MV
-
-/// scalability types
-  enum ScalabilityType
-  {
 #if H_3D
-    DEPTH_ID = 0,    
-#endif    
-    VIEW_ORDER_INDEX  = 1,
-    DEPENDENCY_ID = 2,
-    AUX_ID = 3,
-  };
-#endif
-#if H_3D
-  // Renderer
-  enum BlenMod
-  {
-    BLEND_NONE  = -1,
-    BLEND_AVRG  = 0,
-    BLEND_LEFT  = 1,
-    BLEND_RIGHT = 2,
-    BLEND_GEN   =  3
-  };
-
-  
-  enum
-  {
-    VIEWPOS_INVALID = -1,
-    VIEWPOS_LEFT    = 0,
-    VIEWPOS_RIGHT   = 1,
-    VIEWPOS_MERGED  = 2
-  };
-
-#define Log2( n ) ( log((double)n) / log(2.0) ) // Ed.(GT): This is very very bad and should be fixed to used integer arithmetics ( see gCeilLog2 ) moreover it should not be defined in the tool macro section! 
-#endif
-#endif
+#define !!! REMOVE THIS !!! Log2( n ) ( log((double)n) / log(2.0) ) // Ed.(GT): This is very very bad and should be fixed to used integer arithmetics ( see gCeilLog2 ) moreover it should not be defined in the tool macro section! 
+#endif
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/AnnexBread.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -42,4 +42,7 @@
 #include <vector>
 #include "AnnexBread.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
 
 using namespace std;
@@ -56,5 +59,5 @@
  * be correct at this point.
  */
-static void
+static Void
 _byteStreamNALUnit(
   InputByteStream& bs,
@@ -70,8 +73,14 @@
    * 0x00000001.
    */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::SStat &statBits=TComCodingStatistics::GetStatisticEP(STATS__NAL_UNIT_PACKING);
+#endif
   while ((bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) != 0x000001)
   &&     (bs.eofBeforeNBytes(32/8) || bs.peekBytes(32/8) != 0x00000001))
   {
     uint8_t leading_zero_8bits = bs.readByte();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    statBits.bits+=8; statBits.count++;
+#endif
     assert(leading_zero_8bits == 0);
     stats.m_numLeadingZero8BitsBytes++;
@@ -89,4 +98,7 @@
   {
     uint8_t zero_byte = bs.readByte();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    statBits.bits+=8; statBits.count++;
+#endif
     assert(zero_byte == 0);
     stats.m_numZeroByteBytes++;
@@ -100,4 +112,7 @@
   /* NB, (1) guarantees that the next three bytes are 0x00 00 01 */
   uint32_t start_code_prefix_one_3bytes = bs.readBytes(24/8);
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  statBits.bits+=24; statBits.count+=3;
+#endif
   assert(start_code_prefix_one_3bytes == 0x000001);
   stats.m_numStartCodePrefixBytes += 3;
@@ -117,9 +132,17 @@
    */
   /* NB, (unsigned)x > 2 implies n!=0 && n!=1 */
-  while (bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) > 2) 
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::SStat &bodyStats=TComCodingStatistics::GetStatisticEP(STATS__NAL_UNIT_TOTAL_BODY);
+#endif
+  while (bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) > 2)
   {
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    uint8_t thebyte=bs.readByte();bodyStats.bits+=8;bodyStats.count++;
+    nalUnit.push_back(thebyte);
+#else
     nalUnit.push_back(bs.readByte());
+#endif
   }
-  
+
   /* 5. When the current position in the byte stream is:
    *  - not at the end of the byte stream (as determined by unspecified means)
@@ -141,4 +164,7 @@
   {
     uint8_t trailing_zero_8bits = bs.readByte();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    statBits.bits+=8; statBits.count++;
+#endif
     assert(trailing_zero_8bits == 0);
     stats.m_numTrailingZero8BitsBytes++;
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/AnnexBread.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/AnnexBread.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/AnnexBread.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,9 +39,12 @@
 #pragma once
 
+#ifndef __ANNEXBREAD__
+#define __ANNEXBREAD__
+
 #include <stdint.h>
 #include <istream>
 #include <vector>
 
-#include "../TLibCommon/TypeDef.h"
+#include "TLibCommon/CommonDef.h"
 
 //! \ingroup TLibDecoder
@@ -72,5 +75,5 @@
    * modified externally to this class
    */
-  void reset()
+  Void reset()
   {
     m_NumFutureBytes = 0;
@@ -86,5 +89,7 @@
     assert(n <= 4);
     if (m_NumFutureBytes >= n)
+    {
       return false;
+    }
 
     n -= m_NumFutureBytes;
@@ -150,7 +155,13 @@
     uint32_t val = 0;
     for (UInt i = 0; i < n; i++)
+    {
       val = (val << 8) | readByte();
+    }
     return val;
   }
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  UInt GetNumBufferedBytes() const { return m_NumFutureBytes; }
+#endif
 
 private:
@@ -185,2 +196,4 @@
 
 //! \}
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/NALread.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/NALread.cpp	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -34,5 +34,5 @@
 /**
  \file     NALread.cpp
- \brief    reading funtionality for NAL units
+ \brief    reading functionality for NAL units
  */
 
@@ -45,4 +45,10 @@
 #include "TLibCommon/NAL.h"
 #include "TLibCommon/TComBitStream.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+#if ENC_DEC_TRACE && DEC_NUH_TRACE
+#include "TLibCommon/TComRom.h"
+#endif
 
 using namespace std;
@@ -50,5 +56,5 @@
 //! \ingroup TLibDecoder
 //! \{
-static void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, TComInputBitstream *bitstream, Bool isVclNalUnit)
+static Void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, TComInputBitstream *bitstream, Bool isVclNalUnit)
 {
   UInt zeroCount = 0;
@@ -66,4 +72,7 @@
       it_read++;
       zeroCount = 0;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+      TComCodingStatistics::IncrementStatisticEP(STATS__EMULATION_PREVENTION_3_BYTES, 8, 0);
+#endif
       if (it_read == nalUnitBuf.end())
       {
@@ -76,10 +85,10 @@
   }
   assert(zeroCount == 0);
-  
+
   if (isVclNalUnit)
   {
     // Remove cabac_zero_word from payload if present
     Int n = 0;
-    
+
     while (it_write[-1] == 0x00)
     {
@@ -87,8 +96,8 @@
       n++;
     }
-    
+
     if (n > 0)
     {
-      printf("\nDetected %d instances of cabac_zero_word", n/2);      
+      printf("\nDetected %d instances of cabac_zero_word\n", n/2);
     }
   }
@@ -97,36 +106,65 @@
 }
 
+#if ENC_DEC_TRACE && DEC_NUH_TRACE
+void xTraceNalUnitHeader(InputNALUnit& nalu)
+{
+  fprintf( g_hTrace, "*********** NAL UNIT (%s) ***********\n", nalUnitTypeToString(nalu.m_nalUnitType) );
+
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s u(%d)  : %u\n", "forbidden_zero_bit", 1, 0 ); 
+
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s u(%d)  : %u\n", "nal_unit_type", 6, nalu.m_nalUnitType ); 
+
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s u(%d)  : %u\n", "nuh_layer_id", 6, nalu.m_nuhLayerId );
+
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s u(%d)  : %u\n", "nuh_temporal_id_plus1", 3, nalu.m_temporalId + 1 );
+
+  fflush ( g_hTrace );
+}
+#endif
+
 Void readNalUnitHeader(InputNALUnit& nalu)
 {
-  TComInputBitstream& bs = *nalu.m_Bitstream;
+  TComInputBitstream& bs = nalu.getBitstream();
 
   Bool forbidden_zero_bit = bs.read(1);           // forbidden_zero_bit
   assert(forbidden_zero_bit == 0);
   nalu.m_nalUnitType = (NalUnitType) bs.read(6);  // nal_unit_type
-#if H_MV
-  nalu.m_layerId = bs.read(6);                 // layerId
+#if NH_MV
+  nalu.m_nuhLayerId = bs.read(6);                 // layerId
 #else
-  nalu.m_reservedZero6Bits = bs.read(6);       // nuh_reserved_zero_6bits
-  assert(nalu.m_reservedZero6Bits == 0);
+  nalu.m_nuhLayerId = bs.read(6);                 // nuh_layer_id
 #endif
   nalu.m_temporalId = bs.read(3) - 1;             // nuh_temporal_id_plus1
-
-  if ( nalu.m_temporalId )
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(STATS__NAL_UNIT_HEADER_BITS, 1+6+6+3, 0);
+#endif
+
+#if ENC_DEC_TRACE && DEC_NUH_TRACE
+  xTraceNalUnitHeader(nalu);
+#endif
+
+  // only check these rules for base layer
+  if (nalu.m_nuhLayerId == 0)
   {
-    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_W_LP
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_W_RADL
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_N_LP
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_W_RADL
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_N_LP
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA
-         && nalu.m_nalUnitType != NAL_UNIT_VPS
-         && nalu.m_nalUnitType != NAL_UNIT_SPS
-         && nalu.m_nalUnitType != NAL_UNIT_EOS
-         && nalu.m_nalUnitType != NAL_UNIT_EOB );
-  }
-  else
-  {
-#if H_MV
-
+    if ( nalu.m_temporalId )
+    {
+      assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_W_LP
+           && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_W_RADL
+           && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_N_LP
+           && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_W_RADL
+           && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_N_LP
+           && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA
+           && nalu.m_nalUnitType != NAL_UNIT_VPS
+           && nalu.m_nalUnitType != NAL_UNIT_SPS
+           && nalu.m_nalUnitType != NAL_UNIT_EOS
+           && nalu.m_nalUnitType != NAL_UNIT_EOB );
+    }
+    else
+    {
+#if NH_MV
     // If nal_unit_type is in the range of BLA_W_LP to RSV_IRAP_VCL23, inclusive, i.e. the coded 
     // slice segment belongs to an IRAP picture, TemporalId shall be equal to 0. 
@@ -139,13 +177,14 @@
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N    );
 
-    assert( nalu.m_layerId > 0 
+    assert( nalu.m_nuhLayerId > 0 
       || ( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_N ) );
 #else
-    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_N );
-#endif
+      assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
+           && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
+           && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
+           && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_N );
+#endif
+    }
   }
 }
@@ -154,13 +193,11 @@
  * a bitstream
  */
-void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf)
-{
-  /* perform anti-emulation prevention */
-  TComInputBitstream *pcBitstream = new TComInputBitstream(NULL);
-  convertPayloadToRBSP(nalUnitBuf, pcBitstream, (nalUnitBuf[0] & 64) == 0);
-  
-  nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf);
-  nalu.m_Bitstream->setEmulationPreventionByteLocation(pcBitstream->getEmulationPreventionByteLocation());
-  delete pcBitstream;
+Void read(InputNALUnit& nalu)
+{
+  TComInputBitstream &bitstream = nalu.getBitstream();
+  vector<uint8_t>& nalUnitBuf=bitstream.getFifo();
+  // perform anti-emulation prevention
+  convertPayloadToRBSP(nalUnitBuf, &bitstream, (nalUnitBuf[0] & 64) == 0);
+  bitstream.resetToStart();
   readNalUnitHeader(nalu);
 }
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/NALread.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/NALread.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/NALread.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -34,12 +34,15 @@
 /**
  \file     NALread.h
- \brief    reading funtionality for NAL units
+ \brief    reading functionality for NAL units
  */
 
 #pragma once
 
-#include "../TLibCommon/TypeDef.h"
-#include "../TLibCommon/TComBitStream.h"
-#include "../TLibCommon/NAL.h"
+#ifndef __NALREAD__
+#define __NALREAD__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/NAL.h"
 
 //! \ingroup TLibDecoder
@@ -50,13 +53,21 @@
  * bitstream object.
  */
-struct InputNALUnit : public NALUnit
+class InputNALUnit : public NALUnit
 {
-  InputNALUnit() : m_Bitstream(0) {};
-  ~InputNALUnit() { delete m_Bitstream; }
+  private:
+    TComInputBitstream m_Bitstream;
 
-  TComInputBitstream* m_Bitstream;
+  public:
+    InputNALUnit(const InputNALUnit &src) : NALUnit(src), m_Bitstream(src.m_Bitstream) {};
+    InputNALUnit() : m_Bitstream() {};
+    virtual ~InputNALUnit() { }
+    const TComInputBitstream &getBitstream() const { return m_Bitstream; }
+          TComInputBitstream &getBitstream()       { return m_Bitstream; }
 };
 
-void read(InputNALUnit& nalu, std::vector<uint8_t>& nalUnitBuf);
+Void read(InputNALUnit& nalu);
+Void readNalUnitHeader(InputNALUnit& nalu);
 
 //! \}
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SEIread.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SEIread.cpp	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -32,7 +32,7 @@
  */
 
-/** 
+/**
  \file     SEIread.cpp
- \brief    reading functionality for SEI messages
+ \brief    reading funtionality for SEI messages
  */
 
@@ -43,8 +43,12 @@
 #include "SyntaxElementParser.h"
 #include "SEIread.h"
+#include "TLibCommon/TComPicYuv.h"
+#include <iomanip>
+
 
 //! \ingroup TLibDecoder
 //! \{
 
+
 #if ENC_DEC_TRACE
 Void  xTraceSEIHeader()
@@ -55,64 +59,63 @@
 Void  xTraceSEIMessageType(SEI::PayloadType payloadType)
 {
-  switch (payloadType)
-  {
-  case SEI::DECODED_PICTURE_HASH:
-    fprintf( g_hTrace, "=========== Decoded picture hash SEI message ===========\n");
-    break;
-  case SEI::USER_DATA_UNREGISTERED:
-    fprintf( g_hTrace, "=========== User Data Unregistered SEI message ===========\n");
-    break;
-  case SEI::ACTIVE_PARAMETER_SETS:
-    fprintf( g_hTrace, "=========== Active Parameter sets SEI message ===========\n");
-    break;
-  case SEI::BUFFERING_PERIOD:
-    fprintf( g_hTrace, "=========== Buffering period SEI message ===========\n");
-    break;
-  case SEI::PICTURE_TIMING:
-    fprintf( g_hTrace, "=========== Picture timing SEI message ===========\n");
-    break;
-  case SEI::RECOVERY_POINT:
-    fprintf( g_hTrace, "=========== Recovery point SEI message ===========\n");
-    break;
-  case SEI::FRAME_PACKING:
-    fprintf( g_hTrace, "=========== Frame Packing Arrangement SEI message ===========\n");
-    break;
-  case SEI::DISPLAY_ORIENTATION:
-    fprintf( g_hTrace, "=========== Display Orientation SEI message ===========\n");
-    break;
-  case SEI::TEMPORAL_LEVEL0_INDEX:
-    fprintf( g_hTrace, "=========== Temporal Level Zero Index SEI message ===========\n");
-    break;
-  case SEI::REGION_REFRESH_INFO:
-    fprintf( g_hTrace, "=========== Gradual Decoding Refresh Information SEI message ===========\n");
-    break;
-  case SEI::DECODING_UNIT_INFO:
-    fprintf( g_hTrace, "=========== Decoding Unit Information SEI message ===========\n");
-    break;
-  case SEI::TONE_MAPPING_INFO:
-    fprintf( g_hTrace, "===========Tone Mapping Info SEI message ===========\n");
-    break;
-  case SEI::SOP_DESCRIPTION:
-    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
-    break;
-  case SEI::SCALABLE_NESTING:
-    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
-    break;
-#if H_MV
-  case SEI::SUB_BITSTREAM_PROPERTY:
-    fprintf( g_hTrace, "=========== Sub-bitstream property SEI message ===========\n");
-    break;
+  fprintf( g_hTrace, "=========== %s SEI message ===========\n", SEI::getSEIMessageString(payloadType));
+}
 #endif
-  default:
-    fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
-    break;
-  }
-}
-#endif
+
+Void SEIReader::sei_read_code(std::ostream *pOS, UInt uiLength, UInt& ruiCode, const Char *pSymbolName)
+{
+  READ_CODE(uiLength, ruiCode, pSymbolName);
+  if (pOS)
+  {
+    (*pOS) << "  " << std::setw(55) << pSymbolName << ": " << ruiCode << "\n";
+  }
+}
+
+Void SEIReader::sei_read_uvlc(std::ostream *pOS, UInt& ruiCode, const Char *pSymbolName)
+{
+  READ_UVLC(ruiCode, pSymbolName);
+  if (pOS)
+  {
+    (*pOS) << "  " << std::setw(55) << pSymbolName << ": " << ruiCode << "\n";
+  }
+}
+
+Void SEIReader::sei_read_svlc(std::ostream *pOS, Int& ruiCode, const Char *pSymbolName)
+{
+  READ_SVLC(ruiCode, pSymbolName);
+  if (pOS)
+  {
+    (*pOS) << "  " << std::setw(55) << pSymbolName << ": " << ruiCode << "\n";
+  }
+}
+
+Void SEIReader::sei_read_flag(std::ostream *pOS, UInt& ruiCode, const Char *pSymbolName)
+{
+  READ_FLAG(ruiCode, pSymbolName);
+  if (pOS)
+  {
+    (*pOS) << "  " << std::setw(55) << pSymbolName << ": " << (ruiCode?1:0) << "\n";
+  }
+}
+
+static inline Void output_sei_message_header(SEI &sei, std::ostream *pDecodedMessageOutputStream, UInt payloadSize)
+{
+  if (pDecodedMessageOutputStream)
+  {
+    std::string seiMessageHdr(SEI::getSEIMessageString(sei.payloadType())); seiMessageHdr+=" SEI message";
+    (*pDecodedMessageOutputStream) << std::setfill('-') << std::setw(seiMessageHdr.size()) << "-" << std::setfill(' ') << "\n" << seiMessageHdr << " (" << payloadSize << " bytes)"<< "\n";
+  }
+}
+
+#undef READ_CODE
+#undef READ_SVLC
+#undef READ_UVLC
+#undef READ_FLAG
+
 
 /**
  * unmarshal a single SEI message from bitstream bs
  */
-void SEIReader::parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps)
+Void SEIReader::parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 {
   setBitstream(bs);
@@ -121,16 +124,16 @@
   do
   {
-    xReadSEImessage(seis, nalUnitType, sps);
+    xReadSEImessage(seis, nalUnitType, sps, pDecodedMessageOutputStream);
+
     /* SEI messages are an integer number of bytes, something has failed
     * in the parsing if bitstream not byte-aligned */
     assert(!m_pcBitstream->getNumBitsUntilByteAligned());
-  } while (m_pcBitstream->getNumBitsLeft() > 8);
-
-  UInt rbspTrailingBits;
-  READ_CODE(8, rbspTrailingBits, "rbsp_trailing_bits");
-  assert(rbspTrailingBits == 0x80);
-}
-
-Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps)
+  }
+  while (m_pcBitstream->getNumBitsLeft() > 8);
+
+  xReadRbspTrailingBits();
+}
+
+Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 {
 #if ENC_DEC_TRACE
@@ -142,5 +145,5 @@
   do
   {
-    READ_CODE (8, val, "payload_type");
+    sei_read_code(NULL, 8, val, "payload_type");
     payloadType += val;
   } while (val==0xFF);
@@ -149,5 +152,5 @@
   do
   {
-    READ_CODE (8, val, "payload_size");
+    sei_read_code(NULL, 8, val, "payload_size");
     payloadSize += val;
   } while (val==0xFF);
@@ -174,10 +177,10 @@
     case SEI::USER_DATA_UNREGISTERED:
       sei = new SEIuserDataUnregistered;
-      xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize);
+      xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::ACTIVE_PARAMETER_SETS:
-      sei = new SEIActiveParameterSets; 
-      xParseSEIActiveParameterSets((SEIActiveParameterSets&) *sei, payloadSize); 
-      break; 
+      sei = new SEIActiveParameterSets;
+      xParseSEIActiveParameterSets((SEIActiveParameterSets&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
     case SEI::DECODING_UNIT_INFO:
       if (!sps)
@@ -187,8 +190,8 @@
       else
       {
-        sei = new SEIDecodingUnitInfo; 
-        xParseSEIDecodingUnitInfo((SEIDecodingUnitInfo&) *sei, payloadSize, sps);
-      }
-      break; 
+        sei = new SEIDecodingUnitInfo;
+        xParseSEIDecodingUnitInfo((SEIDecodingUnitInfo&) *sei, payloadSize, sps, pDecodedMessageOutputStream);
+      }
+      break;
     case SEI::BUFFERING_PERIOD:
       if (!sps)
@@ -199,5 +202,5 @@
       {
         sei = new SEIBufferingPeriod;
-        xParseSEIBufferingPeriod((SEIBufferingPeriod&) *sei, payloadSize, sps);
+        xParseSEIBufferingPeriod((SEIBufferingPeriod&) *sei, payloadSize, sps, pDecodedMessageOutputStream);
       }
       break;
@@ -210,44 +213,73 @@
       {
         sei = new SEIPictureTiming;
-        xParseSEIPictureTiming((SEIPictureTiming&)*sei, payloadSize, sps);
+        xParseSEIPictureTiming((SEIPictureTiming&)*sei, payloadSize, sps, pDecodedMessageOutputStream);
       }
       break;
     case SEI::RECOVERY_POINT:
       sei = new SEIRecoveryPoint;
-      xParseSEIRecoveryPoint((SEIRecoveryPoint&) *sei, payloadSize);
+      xParseSEIRecoveryPoint((SEIRecoveryPoint&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::FRAME_PACKING:
       sei = new SEIFramePacking;
-      xParseSEIFramePacking((SEIFramePacking&) *sei, payloadSize);
+      xParseSEIFramePacking((SEIFramePacking&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::SEGM_RECT_FRAME_PACKING:
+      sei = new SEISegmentedRectFramePacking;
+      xParseSEISegmentedRectFramePacking((SEISegmentedRectFramePacking&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::DISPLAY_ORIENTATION:
       sei = new SEIDisplayOrientation;
-      xParseSEIDisplayOrientation((SEIDisplayOrientation&) *sei, payloadSize);
+      xParseSEIDisplayOrientation((SEIDisplayOrientation&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::TEMPORAL_LEVEL0_INDEX:
       sei = new SEITemporalLevel0Index;
-      xParseSEITemporalLevel0Index((SEITemporalLevel0Index&) *sei, payloadSize);
+      xParseSEITemporalLevel0Index((SEITemporalLevel0Index&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::REGION_REFRESH_INFO:
       sei = new SEIGradualDecodingRefreshInfo;
-      xParseSEIGradualDecodingRefreshInfo((SEIGradualDecodingRefreshInfo&) *sei, payloadSize);
+      xParseSEIRegionRefreshInfo((SEIGradualDecodingRefreshInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::NO_DISPLAY:
+      sei = new SEINoDisplay;
+      xParseSEINoDisplay((SEINoDisplay&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::TONE_MAPPING_INFO:
       sei = new SEIToneMappingInfo;
-      xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize);
+      xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::SOP_DESCRIPTION:
       sei = new SEISOPDescription;
-      xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize);
+      xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::SCALABLE_NESTING:
       sei = new SEIScalableNesting;
-      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps);
-      break;
-#if H_MV
-     case SEI::SUB_BITSTREAM_PROPERTY:
-       sei = new SEISubBitstreamProperty;
-       xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei);
-       break;
+      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps, pDecodedMessageOutputStream);
+      break;
+    case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:
+      sei = new SEITempMotionConstrainedTileSets;
+      xParseSEITempMotionConstraintsTileSets((SEITempMotionConstrainedTileSets&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::TIME_CODE:
+      sei = new SEITimeCode;
+      xParseSEITimeCode((SEITimeCode&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::CHROMA_SAMPLING_FILTER_HINT:
+      sei = new SEIChromaSamplingFilterHint;
+      xParseSEIChromaSamplingFilterHint((SEIChromaSamplingFilterHint&) *sei, payloadSize/*, sps*/, pDecodedMessageOutputStream);
+      //}
+      break;
+    case SEI::KNEE_FUNCTION_INFO:
+      sei = new SEIKneeFunctionInfo;
+      xParseSEIKneeFunctionInfo((SEIKneeFunctionInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
+      sei = new SEIMasteringDisplayColourVolume;
+      xParseSEIMasteringDisplayColourVolume((SEIMasteringDisplayColourVolume&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+#if NH_MV
+    case SEI::SUB_BITSTREAM_PROPERTY:
+      sei = new SEISubBitstreamProperty;
+      xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei, payloadSize, pDecodedMessageOutputStream );
+      break;
 #endif
     default:
@@ -255,7 +287,12 @@
       {
         UInt seiByte;
-        READ_CODE (8, seiByte, "unknown prefix SEI payload byte");
+        sei_read_code (NULL, 8, seiByte, "unknown prefix SEI payload byte");
       }
       printf ("Unknown prefix SEI message (payloadType = %d) was found!\n", payloadType);
+      if (pDecodedMessageOutputStream)
+      {
+        (*pDecodedMessageOutputStream) << "Unknown prefix SEI message (payloadType = " << payloadType << ") was found!\n";
+      }
+      break;
     }
   }
@@ -266,9 +303,9 @@
       case SEI::USER_DATA_UNREGISTERED:
         sei = new SEIuserDataUnregistered;
-        xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize);
+        xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize, pDecodedMessageOutputStream);
         break;
       case SEI::DECODED_PICTURE_HASH:
         sei = new SEIDecodedPictureHash;
-        xParseSEIDecodedPictureHash((SEIDecodedPictureHash&) *sei, payloadSize);
+        xParseSEIDecodedPictureHash((SEIDecodedPictureHash&) *sei, payloadSize, pDecodedMessageOutputStream);
         break;
       default:
@@ -276,9 +313,15 @@
         {
           UInt seiByte;
-          READ_CODE (8, seiByte, "unknown suffix SEI payload byte");
+          sei_read_code( NULL, 8, seiByte, "unknown suffix SEI payload byte");
         }
         printf ("Unknown suffix SEI message (payloadType = %d) was found!\n", payloadType);
-    }
-  }
+        if (pDecodedMessageOutputStream)
+        {
+          (*pDecodedMessageOutputStream) << "Unknown suffix SEI message (payloadType = " << payloadType << ") was found!\n";
+        }
+        break;
+    }
+  }
+
   if (sei != NULL)
   {
@@ -299,5 +342,5 @@
     {
       UInt reservedPayloadExtensionData;
-      READ_CODE (1, reservedPayloadExtensionData, "reserved_payload_extension_data");
+      sei_read_code ( pDecodedMessageOutputStream, 1, reservedPayloadExtensionData, "reserved_payload_extension_data");
     }
 
@@ -314,17 +357,16 @@
     {
       UInt reservedPayloadExtensionData;
-      READ_FLAG (reservedPayloadExtensionData, "reserved_payload_extension_data");
+      sei_read_flag ( 0, reservedPayloadExtensionData, "reserved_payload_extension_data");
     }
 
     UInt dummy;
-    READ_FLAG (dummy, "payload_bit_equal_to_one"); payloadBitsRemaining--;
+    sei_read_flag( 0, dummy, "payload_bit_equal_to_one"); payloadBitsRemaining--;
     while (payloadBitsRemaining)
     {
-      READ_FLAG (dummy, "payload_bit_equal_to_zero"); payloadBitsRemaining--;
+      sei_read_flag( 0, dummy, "payload_bit_equal_to_zero"); payloadBitsRemaining--;
     }
   }
 
   /* restore primary bitstream for sei_message */
-  getBitstream()->deleteFifo();
   delete getBitstream();
   setBitstream(bs);
@@ -335,16 +377,18 @@
  * of payloasSize bytes into sei.
  */
-Void SEIReader::xParseSEIuserDataUnregistered(SEIuserDataUnregistered &sei, UInt payloadSize)
-{
-  assert(payloadSize >= 16);
+
+Void SEIReader::xParseSEIuserDataUnregistered(SEIuserDataUnregistered &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  assert(payloadSize >= ISO_IEC_11578_LEN);
   UInt val;
-
-  for (UInt i = 0; i < 16; i++)
-  {
-    READ_CODE (8, val, "uuid_iso_iec_11578");
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  for (UInt i = 0; i < ISO_IEC_11578_LEN; i++)
+  {
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "uuid_iso_iec_11578");
     sei.uuid_iso_iec_11578[i] = val;
   }
 
-  sei.userDataLength = payloadSize - 16;
+  sei.userDataLength = payloadSize - ISO_IEC_11578_LEN;
   if (!sei.userDataLength)
   {
@@ -356,6 +400,10 @@
   for (UInt i = 0; i < sei.userDataLength; i++)
   {
-    READ_CODE (8, val, "user_data" );
+    sei_read_code( NULL, 8, val, "user_data_payload_byte" );
     sei.userData[i] = val;
+  }
+  if (pDecodedMessageOutputStream)
+  {
+    (*pDecodedMessageOutputStream) << "  User data payload size: " << sei.userDataLength << "\n";
   }
 }
@@ -365,62 +413,72 @@
  * of payloadSize bytes into sei.
  */
-Void SEIReader::xParseSEIDecodedPictureHash(SEIDecodedPictureHash& sei, UInt /*payloadSize*/)
-{
+Void SEIReader::xParseSEIDecodedPictureHash(SEIDecodedPictureHash& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt bytesRead = 0;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
   UInt val;
-  READ_CODE (8, val, "hash_type");
-  sei.method = static_cast<SEIDecodedPictureHash::Method>(val);
-  for(Int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
-  {
-    if(SEIDecodedPictureHash::MD5 == sei.method)
-    {
-      for (UInt i = 0; i < 16; i++)
-      {
-        READ_CODE(8, val, "picture_md5");
-        sei.digest[yuvIdx][i] = val;
-      }
-    }
-    else if(SEIDecodedPictureHash::CRC == sei.method)
-    {
-      READ_CODE(16, val, "picture_crc");
-      sei.digest[yuvIdx][0] = val >> 8 & 0xFF;
-      sei.digest[yuvIdx][1] = val & 0xFF;
-    }
-    else if(SEIDecodedPictureHash::CHECKSUM == sei.method)
-    {
-      READ_CODE(32, val, "picture_checksum");
-      sei.digest[yuvIdx][0] = (val>>24) & 0xff;
-      sei.digest[yuvIdx][1] = (val>>16) & 0xff;
-      sei.digest[yuvIdx][2] = (val>>8)  & 0xff;
-      sei.digest[yuvIdx][3] =  val      & 0xff;
-    }
-  }
-}
-Void SEIReader::xParseSEIActiveParameterSets(SEIActiveParameterSets& sei, UInt /*payloadSize*/)
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "hash_type");
+  sei.method = static_cast<SEIDecodedPictureHash::Method>(val); bytesRead++;
+
+  const Char *traceString="\0";
+  switch (sei.method)
+  {
+    case SEIDecodedPictureHash::MD5: traceString="picture_md5"; break;
+    case SEIDecodedPictureHash::CRC: traceString="picture_crc"; break;
+    case SEIDecodedPictureHash::CHECKSUM: traceString="picture_checksum"; break;
+    default: assert(false); break;
+  }
+
+  if (pDecodedMessageOutputStream)
+  {
+    (*pDecodedMessageOutputStream) << "  " << std::setw(55) << traceString << ": " << std::hex << std::setfill('0');
+  }
+
+  sei.m_pictureHash.hash.clear();
+  for(;bytesRead < payloadSize; bytesRead++)
+  {
+    sei_read_code( NULL, 8, val, traceString);
+    sei.m_pictureHash.hash.push_back((UChar)val);
+    if (pDecodedMessageOutputStream)
+    {
+      (*pDecodedMessageOutputStream) << std::setw(2) << val;
+    }
+  }
+
+  if (pDecodedMessageOutputStream)
+  {
+    (*pDecodedMessageOutputStream) << std::dec << std::setfill(' ') << "\n";
+  }
+}
+
+Void SEIReader::xParseSEIActiveParameterSets(SEIActiveParameterSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   UInt val; 
-  READ_CODE(4, val, "active_video_parameter_set_id");   sei.activeVPSId = val; 
-  READ_FLAG(   val, "self_contained_cvs_flag");         sei.m_selfContainedCvsFlag = val ? true : false;
-  READ_FLAG(   val, "no_parameter_set_update_flag");    sei.m_noParameterSetUpdateFlag = val ? true : false;
-  READ_UVLC(   val, "num_sps_ids_minus1"); sei.numSpsIdsMinus1 = val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code( pDecodedMessageOutputStream, 4, val, "active_video_parameter_set_id");   sei.activeVPSId = val;
+  sei_read_flag( pDecodedMessageOutputStream,    val, "self_contained_cvs_flag");         sei.m_selfContainedCvsFlag     = (val != 0);
+  sei_read_flag( pDecodedMessageOutputStream,    val, "no_parameter_set_update_flag");    sei.m_noParameterSetUpdateFlag = (val != 0);
+  sei_read_uvlc( pDecodedMessageOutputStream,    val, "num_sps_ids_minus1");              sei.numSpsIdsMinus1 = val;
 
   sei.activeSeqParameterSetId.resize(sei.numSpsIdsMinus1 + 1);
   for (Int i=0; i < (sei.numSpsIdsMinus1 + 1); i++)
   {
-    READ_UVLC(val, "active_seq_parameter_set_id");      sei.activeSeqParameterSetId[i] = val; 
-  }
-
-  xParseByteAlign();
-}
-
-Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt /*payloadSize*/, TComSPS *sps)
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "active_seq_parameter_set_id[i]");    sei.activeSeqParameterSetId[i] = val;
+  }
+}
+
+Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 {
   UInt val;
-  READ_UVLC(val, "decoding_unit_idx");
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "decoding_unit_idx");
   sei.m_decodingUnitIdx = val;
 
-  TComVUI *vui = sps->getVuiParameters();
+  const TComVUI *vui = sps->getVuiParameters();
   if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
   {
-    READ_CODE( ( vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1 ), val, "du_spt_cpb_removal_delay");
+    sei_read_code( pDecodedMessageOutputStream, ( vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1 ), val, "du_spt_cpb_removal_delay_increment");
     sei.m_duSptCpbRemovalDelay = val;
   }
@@ -429,36 +487,39 @@
     sei.m_duSptCpbRemovalDelay = 0;
   }
-  READ_FLAG( val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = val ? true : false;
+  sei_read_flag( pDecodedMessageOutputStream, val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = (val != 0);
   if(sei.m_dpbOutputDuDelayPresentFlag)
   {
-    READ_CODE(vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, val, "pic_spt_dpb_output_du_delay"); 
+    sei_read_code( pDecodedMessageOutputStream, vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, val, "pic_spt_dpb_output_du_delay");
     sei.m_picSptDpbOutputDuDelay = val;
   }
-  xParseByteAlign();
-}
-
-Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt /*payloadSize*/, TComSPS *sps)
+}
+
+Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 {
   Int i, nalOrVcl;
   UInt code;
 
-  TComVUI *pVUI = sps->getVuiParameters();
-  TComHRD *pHRD = pVUI->getHrdParameters();
-
-  READ_UVLC( code, "bp_seq_parameter_set_id" );                         sei.m_bpSeqParameterSetId     = code;
+  const TComVUI *pVUI = sps->getVuiParameters();
+  const TComHRD *pHRD = pVUI->getHrdParameters();
+
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, code, "bp_seq_parameter_set_id" );                         sei.m_bpSeqParameterSetId     = code;
   if( !pHRD->getSubPicCpbParamsPresentFlag() )
   {
-    READ_FLAG( code, "irap_cpb_params_present_flag" );                   sei.m_rapCpbParamsPresentFlag = code;
+    sei_read_flag( pDecodedMessageOutputStream, code, "irap_cpb_params_present_flag" );                   sei.m_rapCpbParamsPresentFlag = code;
   }
   if( sei.m_rapCpbParamsPresentFlag )
   {
-    READ_CODE( pHRD->getCpbRemovalDelayLengthMinus1() + 1, code, "cpb_delay_offset" );      sei.m_cpbDelayOffset = code;
-    READ_CODE( pHRD->getDpbOutputDelayLengthMinus1()  + 1, code, "dpb_delay_offset" );      sei.m_dpbDelayOffset = code;
-  }
+    sei_read_code( pDecodedMessageOutputStream, pHRD->getCpbRemovalDelayLengthMinus1() + 1, code, "cpb_delay_offset" );      sei.m_cpbDelayOffset = code;
+    sei_read_code( pDecodedMessageOutputStream, pHRD->getDpbOutputDelayLengthMinus1()  + 1, code, "dpb_delay_offset" );      sei.m_dpbDelayOffset = code;
+  }
+
   //read splicing flag and cpb_removal_delay_delta
-  READ_FLAG( code, "concatenation_flag"); 
+  sei_read_flag( pDecodedMessageOutputStream, code, "concatenation_flag");
   sei.m_concatenationFlag = code;
-  READ_CODE( ( pHRD->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_delta_minus1" );
+  sei_read_code( pDecodedMessageOutputStream, ( pHRD->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_delta_minus1" );
   sei.m_auCpbRemovalDelayDelta = code + 1;
+
   for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
   {
@@ -468,13 +529,13 @@
       for( i = 0; i < ( pHRD->getCpbCntMinus1( 0 ) + 1 ); i ++ )
       {
-        READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_cpb_removal_delay" );
+        sei_read_code( pDecodedMessageOutputStream, ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, nalOrVcl?"vcl_initial_cpb_removal_delay":"nal_initial_cpb_removal_delay" );
         sei.m_initialCpbRemovalDelay[i][nalOrVcl] = code;
-        READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_cpb_removal_delay_offset" );
+        sei_read_code( pDecodedMessageOutputStream, ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, nalOrVcl?"vcl_initial_cpb_removal_offset":"vcl_initial_cpb_removal_offset" );
         sei.m_initialCpbRemovalDelayOffset[i][nalOrVcl] = code;
         if( pHRD->getSubPicCpbParamsPresentFlag() || sei.m_rapCpbParamsPresentFlag )
         {
-          READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_alt_cpb_removal_delay" );
+          sei_read_code( pDecodedMessageOutputStream, ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, nalOrVcl?"vcl_initial_alt_cpb_removal_delay":"vcl_initial_alt_cpb_removal_delay" );
           sei.m_initialAltCpbRemovalDelay[i][nalOrVcl] = code;
-          READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_alt_cpb_removal_delay_offset" );
+          sei_read_code( pDecodedMessageOutputStream, ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, nalOrVcl?"vcl_initial_alt_cpb_removal_offset":"vcl_initial_alt_cpb_removal_offset" );
           sei.m_initialAltCpbRemovalDelayOffset[i][nalOrVcl] = code;
         }
@@ -482,62 +543,56 @@
     }
   }
-  xParseByteAlign();
-}
-Void SEIReader::xParseSEIPictureTiming(SEIPictureTiming& sei, UInt /*payloadSize*/, TComSPS *sps)
+}
+
+Void SEIReader::xParseSEIPictureTiming(SEIPictureTiming& sei, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 {
   Int i;
   UInt code;
 
-  TComVUI *vui = sps->getVuiParameters();
-  TComHRD *hrd = vui->getHrdParameters();
+  const TComVUI *vui = sps->getVuiParameters();
+  const TComHRD *hrd = vui->getHrdParameters();
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
 
   if( vui->getFrameFieldInfoPresentFlag() )
   {
-    READ_CODE( 4, code, "pic_struct" );             sei.m_picStruct            = code;
-    READ_CODE( 2, code, "source_scan_type" );       sei.m_sourceScanType = code;
-    READ_FLAG(    code, "duplicate_flag" );         sei.m_duplicateFlag        = ( code == 1 ? true : false );
+    sei_read_code( pDecodedMessageOutputStream, 4, code, "pic_struct" );             sei.m_picStruct            = code;
+    sei_read_code( pDecodedMessageOutputStream, 2, code, "source_scan_type" );       sei.m_sourceScanType       = code;
+    sei_read_flag( pDecodedMessageOutputStream,    code, "duplicate_flag" );         sei.m_duplicateFlag        = (code == 1);
   }
 
   if( hrd->getCpbDpbDelaysPresentFlag())
   {
-    READ_CODE( ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_minus1" );
+    sei_read_code( pDecodedMessageOutputStream, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_minus1" );
     sei.m_auCpbRemovalDelay = code + 1;
-    READ_CODE( ( hrd->getDpbOutputDelayLengthMinus1() + 1 ), code, "pic_dpb_output_delay" );
+    sei_read_code( pDecodedMessageOutputStream, ( hrd->getDpbOutputDelayLengthMinus1() + 1 ), code, "pic_dpb_output_delay" );
     sei.m_picDpbOutputDelay = code;
 
     if(hrd->getSubPicCpbParamsPresentFlag())
     {
-      READ_CODE(hrd->getDpbOutputDelayDuLengthMinus1()+1, code, "pic_dpb_output_du_delay" );
+      sei_read_code( pDecodedMessageOutputStream, hrd->getDpbOutputDelayDuLengthMinus1()+1, code, "pic_dpb_output_du_delay" );
       sei.m_picDpbOutputDuDelay = code;
     }
+
     if( hrd->getSubPicCpbParamsPresentFlag() && hrd->getSubPicCpbParamsInPicTimingSEIFlag() )
     {
-      READ_UVLC( code, "num_decoding_units_minus1");
+      sei_read_uvlc( pDecodedMessageOutputStream, code, "num_decoding_units_minus1");
       sei.m_numDecodingUnitsMinus1 = code;
-      READ_FLAG( code, "du_common_cpb_removal_delay_flag" );
+      sei_read_flag( pDecodedMessageOutputStream, code, "du_common_cpb_removal_delay_flag" );
       sei.m_duCommonCpbRemovalDelayFlag = code;
       if( sei.m_duCommonCpbRemovalDelayFlag )
       {
-        READ_CODE( ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_common_cpb_removal_delay_minus1" );
+        sei_read_code( pDecodedMessageOutputStream, ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_common_cpb_removal_delay_increment_minus1" );
         sei.m_duCommonCpbRemovalDelayMinus1 = code;
       }
-      if( sei.m_numNalusInDuMinus1 != NULL )
-      {
-        delete sei.m_numNalusInDuMinus1;
-      }
-      sei.m_numNalusInDuMinus1 = new UInt[ ( sei.m_numDecodingUnitsMinus1 + 1 ) ];
-      if( sei.m_duCpbRemovalDelayMinus1  != NULL )
-      {
-        delete sei.m_duCpbRemovalDelayMinus1;
-      }
-      sei.m_duCpbRemovalDelayMinus1  = new UInt[ ( sei.m_numDecodingUnitsMinus1 + 1 ) ];
+      sei.m_numNalusInDuMinus1.resize(sei.m_numDecodingUnitsMinus1 + 1 );
+      sei.m_duCpbRemovalDelayMinus1.resize( sei.m_numDecodingUnitsMinus1 + 1 );
 
       for( i = 0; i <= sei.m_numDecodingUnitsMinus1; i ++ )
       {
-        READ_UVLC( code, "num_nalus_in_du_minus1");
+        sei_read_uvlc( pDecodedMessageOutputStream, code, "num_nalus_in_du_minus1[i]");
         sei.m_numNalusInDuMinus1[ i ] = code;
         if( ( !sei.m_duCommonCpbRemovalDelayFlag ) && ( i < sei.m_numDecodingUnitsMinus1 ) )
         {
-          READ_CODE( ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_cpb_removal_delay_minus1" );
+          sei_read_code( pDecodedMessageOutputStream, ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_cpb_removal_delay_minus1[i]" );
           sei.m_duCpbRemovalDelayMinus1[ i ] = code;
         }
@@ -545,105 +600,127 @@
     }
   }
-  xParseByteAlign();
-}
-Void SEIReader::xParseSEIRecoveryPoint(SEIRecoveryPoint& sei, UInt /*payloadSize*/)
+}
+
+Void SEIReader::xParseSEIRecoveryPoint(SEIRecoveryPoint& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   Int  iCode;
   UInt uiCode;
-  READ_SVLC( iCode,  "recovery_poc_cnt" );      sei.m_recoveryPocCnt     = iCode;
-  READ_FLAG( uiCode, "exact_matching_flag" );   sei.m_exactMatchingFlag  = uiCode;
-  READ_FLAG( uiCode, "broken_link_flag" );      sei.m_brokenLinkFlag     = uiCode;
-  xParseByteAlign();
-}
-Void SEIReader::xParseSEIFramePacking(SEIFramePacking& sei, UInt /*payloadSize*/)
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_svlc( pDecodedMessageOutputStream, iCode,  "recovery_poc_cnt" );      sei.m_recoveryPocCnt     = iCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "exact_matching_flag" );   sei.m_exactMatchingFlag  = uiCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "broken_link_flag" );      sei.m_brokenLinkFlag     = uiCode;
+}
+
+Void SEIReader::xParseSEIFramePacking(SEIFramePacking& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   UInt val;
-  READ_UVLC( val, "frame_packing_arrangement_id" );                 sei.m_arrangementId = val;
-  READ_FLAG( val, "frame_packing_arrangement_cancel_flag" );        sei.m_arrangementCancelFlag = val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "frame_packing_arrangement_id" );                 sei.m_arrangementId = val;
+  sei_read_flag( pDecodedMessageOutputStream, val, "frame_packing_arrangement_cancel_flag" );        sei.m_arrangementCancelFlag = val;
 
   if ( !sei.m_arrangementCancelFlag )
   {
-    READ_CODE( 7, val, "frame_packing_arrangement_type" );          sei.m_arrangementType = val;
+    sei_read_code( pDecodedMessageOutputStream, 7, val, "frame_packing_arrangement_type" );          sei.m_arrangementType = val;
     assert((sei.m_arrangementType > 2) && (sei.m_arrangementType < 6) );
-    READ_FLAG( val, "quincunx_sampling_flag" );                     sei.m_quincunxSamplingFlag = val;
-
-    READ_CODE( 6, val, "content_interpretation_type" );             sei.m_contentInterpretationType = val;
-    READ_FLAG( val, "spatial_flipping_flag" );                      sei.m_spatialFlippingFlag = val;
-    READ_FLAG( val, "frame0_flipped_flag" );                        sei.m_frame0FlippedFlag = val;
-    READ_FLAG( val, "field_views_flag" );                           sei.m_fieldViewsFlag = val;
-    READ_FLAG( val, "current_frame_is_frame0_flag" );               sei.m_currentFrameIsFrame0Flag = val;
-    READ_FLAG( val, "frame0_self_contained_flag" );                 sei.m_frame0SelfContainedFlag = val;
-    READ_FLAG( val, "frame1_self_contained_flag" );                 sei.m_frame1SelfContainedFlag = val;
+
+    sei_read_flag( pDecodedMessageOutputStream, val, "quincunx_sampling_flag" );                     sei.m_quincunxSamplingFlag = val;
+
+    sei_read_code( pDecodedMessageOutputStream, 6, val, "content_interpretation_type" );             sei.m_contentInterpretationType = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "spatial_flipping_flag" );                      sei.m_spatialFlippingFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame0_flipped_flag" );                        sei.m_frame0FlippedFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "field_views_flag" );                           sei.m_fieldViewsFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "current_frame_is_frame0_flag" );               sei.m_currentFrameIsFrame0Flag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame0_self_contained_flag" );                 sei.m_frame0SelfContainedFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame1_self_contained_flag" );                 sei.m_frame1SelfContainedFlag = val;
 
     if ( sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5)
     {
-      READ_CODE( 4, val, "frame0_grid_position_x" );                sei.m_frame0GridPositionX = val;
-      READ_CODE( 4, val, "frame0_grid_position_y" );                sei.m_frame0GridPositionY = val;
-      READ_CODE( 4, val, "frame1_grid_position_x" );                sei.m_frame1GridPositionX = val;
-      READ_CODE( 4, val, "frame1_grid_position_y" );                sei.m_frame1GridPositionY = val;
-    }
-
-    READ_CODE( 8, val, "frame_packing_arrangement_reserved_byte" );   sei.m_arrangementReservedByte = val;
-    READ_FLAG( val,  "frame_packing_arrangement_persistence_flag" );  sei.m_arrangementPersistenceFlag = val ? true : false;
-  }
-  READ_FLAG( val, "upsampled_aspect_ratio" );                       sei.m_upsampledAspectRatio = val;
-
-  xParseByteAlign();
-}
-
-Void SEIReader::xParseSEIDisplayOrientation(SEIDisplayOrientation& sei, UInt /*payloadSize*/)
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame0_grid_position_x" );                sei.m_frame0GridPositionX = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame0_grid_position_y" );                sei.m_frame0GridPositionY = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame1_grid_position_x" );                sei.m_frame1GridPositionX = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame1_grid_position_y" );                sei.m_frame1GridPositionY = val;
+    }
+
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "frame_packing_arrangement_reserved_byte" );   sei.m_arrangementReservedByte = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,  "frame_packing_arrangement_persistence_flag" );  sei.m_arrangementPersistenceFlag = (val != 0);
+  }
+  sei_read_flag( pDecodedMessageOutputStream, val, "upsampled_aspect_ratio_flag" );                  sei.m_upsampledAspectRatio = val;
+}
+
+Void SEIReader::xParseSEISegmentedRectFramePacking(SEISegmentedRectFramePacking& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   UInt val;
-  READ_FLAG( val,       "display_orientation_cancel_flag" );       sei.cancelFlag            = val;
-  if( !sei.cancelFlag ) 
-  {
-    READ_FLAG( val,     "hor_flip" );                              sei.horFlip               = val;
-    READ_FLAG( val,     "ver_flip" );                              sei.verFlip               = val;
-    READ_CODE( 16, val, "anticlockwise_rotation" );                sei.anticlockwiseRotation = val;
-    READ_FLAG( val,     "display_orientation_persistence_flag" );  sei.persistenceFlag       = val;
-  }
-  xParseByteAlign();
-}
-
-Void SEIReader::xParseSEITemporalLevel0Index(SEITemporalLevel0Index& sei, UInt /*payloadSize*/)
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val,       "segmented_rect_frame_packing_arrangement_cancel_flag" );       sei.m_arrangementCancelFlag            = val;
+  if( !sei.m_arrangementCancelFlag )
+  {
+    sei_read_code( pDecodedMessageOutputStream, 2, val, "segmented_rect_content_interpretation_type" );                sei.m_contentInterpretationType = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "segmented_rect_frame_packing_arrangement_persistence" );                              sei.m_arrangementPersistenceFlag               = val;
+  }
+}
+
+Void SEIReader::xParseSEIDisplayOrientation(SEIDisplayOrientation& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   UInt val;
-  READ_CODE ( 8, val, "tl0_idx" );  sei.tl0Idx = val;
-  READ_CODE ( 8, val, "rap_idx" );  sei.rapIdx = val;
-  xParseByteAlign();
-}
-
-Void SEIReader::xParseSEIGradualDecodingRefreshInfo(SEIGradualDecodingRefreshInfo& sei, UInt /*payloadSize*/)
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val,       "display_orientation_cancel_flag" );       sei.cancelFlag            = val;
+  if( !sei.cancelFlag )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, val,     "hor_flip" );                              sei.horFlip               = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "ver_flip" );                              sei.verFlip               = val;
+    sei_read_code( pDecodedMessageOutputStream, 16, val, "anticlockwise_rotation" );                sei.anticlockwiseRotation = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "display_orientation_persistence_flag" );  sei.persistenceFlag       = val;
+  }
+}
+
+Void SEIReader::xParseSEITemporalLevel0Index(SEITemporalLevel0Index& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   UInt val;
-  READ_FLAG( val, "gdr_foreground_flag" ); sei.m_gdrForegroundFlag = val ? 1 : 0;
-  xParseByteAlign();
-}
-
-Void SEIReader::xParseSEIToneMappingInfo(SEIToneMappingInfo& sei, UInt /*payloadSize*/)
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "temporal_sub_layer_zero_idx" );  sei.tl0Idx = val;
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "irap_pic_id" );  sei.rapIdx = val;
+}
+
+Void SEIReader::xParseSEIRegionRefreshInfo(SEIGradualDecodingRefreshInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val, "refreshed_region_flag" ); sei.m_gdrForegroundFlag = val ? 1 : 0;
+}
+
+Void SEIReader::xParseSEINoDisplay(SEINoDisplay& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei.m_noDisplay = true;
+}
+
+Void SEIReader::xParseSEIToneMappingInfo(SEIToneMappingInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   Int i;
   UInt val;
-  READ_UVLC( val, "tone_map_id" );                         sei.m_toneMapId = val;
-  READ_FLAG( val, "tone_map_cancel_flag" );                sei.m_toneMapCancelFlag = val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "tone_map_id" );                         sei.m_toneMapId = val;
+  sei_read_flag( pDecodedMessageOutputStream, val, "tone_map_cancel_flag" );                sei.m_toneMapCancelFlag = val;
 
   if ( !sei.m_toneMapCancelFlag )
   {
-    READ_FLAG( val, "tone_map_persistence_flag" );         sei.m_toneMapPersistenceFlag = val; 
-    READ_CODE( 8, val, "coded_data_bit_depth" );           sei.m_codedDataBitDepth = val;
-    READ_CODE( 8, val, "target_bit_depth" );               sei.m_targetBitDepth = val;
-    READ_UVLC( val, "model_id" );                          sei.m_modelId = val; 
+    sei_read_flag( pDecodedMessageOutputStream, val, "tone_map_persistence_flag" );         sei.m_toneMapPersistenceFlag = val;
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "coded_data_bit_depth" );           sei.m_codedDataBitDepth = val;
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "target_bit_depth" );               sei.m_targetBitDepth = val;
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "tone_map_model_id" );                 sei.m_modelId = val;
     switch(sei.m_modelId)
     {
     case 0:
       {
-        READ_CODE( 32, val, "min_value" );                 sei.m_minValue = val;
-        READ_CODE( 32, val, "max_value" );                 sei.m_maxValue = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "min_value" );                 sei.m_minValue = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "max_value" );                 sei.m_maxValue = val;
         break;
       }
     case 1:
       {
-        READ_CODE( 32, val, "sigmoid_midpoint" );          sei.m_sigmoidMidpoint = val;
-        READ_CODE( 32, val, "sigmoid_width" );             sei.m_sigmoidWidth = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "sigmoid_midpoint" );          sei.m_sigmoidMidpoint = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "sigmoid_width" );             sei.m_sigmoidWidth = val;
         break;
       }
@@ -654,5 +731,5 @@
         for(i = 0; i < num; i++)
         {
-          READ_CODE( ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "start_of_coded_interval" );
+          sei_read_code( pDecodedMessageOutputStream, ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "start_of_coded_interval[i]" );
           sei.m_startOfCodedInterval[i] = val;
         }
@@ -662,12 +739,12 @@
     case 3:
       {
-        READ_CODE( 16, val,  "num_pivots" );                       sei.m_numPivots = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val,  "num_pivots" );                       sei.m_numPivots = val;
         sei.m_codedPivotValue.resize(sei.m_numPivots);
         sei.m_targetPivotValue.resize(sei.m_numPivots);
         for(i = 0; i < sei.m_numPivots; i++ )
         {
-          READ_CODE( ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "coded_pivot_value" );
+          sei_read_code( pDecodedMessageOutputStream, ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "coded_pivot_value[i]" );
           sei.m_codedPivotValue[i] = val;
-          READ_CODE( ((( sei.m_targetBitDepth + 7 ) >> 3 ) << 3),    val, "target_pivot_value" );
+          sei_read_code( pDecodedMessageOutputStream, ((( sei.m_targetBitDepth + 7 ) >> 3 ) << 3),    val, "target_pivot_value[i]" );
           sei.m_targetPivotValue[i] = val;
         }
@@ -676,22 +753,22 @@
     case 4:
       {
-        READ_CODE( 8, val, "camera_iso_speed_idc" );                     sei.m_cameraIsoSpeedIdc = val;
+        sei_read_code( pDecodedMessageOutputStream, 8, val, "camera_iso_speed_idc" );                     sei.m_cameraIsoSpeedIdc = val;
         if( sei.m_cameraIsoSpeedIdc == 255) //Extended_ISO
         {
-          READ_CODE( 32,   val,   "camera_iso_speed_value" );            sei.m_cameraIsoSpeedValue = val;
-        }
-        READ_CODE( 8, val, "exposure_index_idc" );                       sei.m_exposureIndexIdc = val;
+          sei_read_code( pDecodedMessageOutputStream, 32,   val,   "camera_iso_speed_value" );            sei.m_cameraIsoSpeedValue = val;
+        }
+        sei_read_code( pDecodedMessageOutputStream, 8, val, "exposure_index_idc" );                       sei.m_exposureIndexIdc = val;
         if( sei.m_exposureIndexIdc == 255) //Extended_ISO
         {
-          READ_CODE( 32,   val,   "exposure_index_value" );              sei.m_exposureIndexValue = val;
-        }
-        READ_FLAG( val, "exposure_compensation_value_sign_flag" );       sei.m_exposureCompensationValueSignFlag = val;
-        READ_CODE( 16, val, "exposure_compensation_value_numerator" );   sei.m_exposureCompensationValueNumerator = val;
-        READ_CODE( 16, val, "exposure_compensation_value_denom_idc" );   sei.m_exposureCompensationValueDenomIdc = val;
-        READ_CODE( 32, val, "ref_screen_luminance_white" );              sei.m_refScreenLuminanceWhite = val;
-        READ_CODE( 32, val, "extended_range_white_level" );              sei.m_extendedRangeWhiteLevel = val;
-        READ_CODE( 16, val, "nominal_black_level_luma_code_value" );     sei.m_nominalBlackLevelLumaCodeValue = val;
-        READ_CODE( 16, val, "nominal_white_level_luma_code_value" );     sei.m_nominalWhiteLevelLumaCodeValue= val;
-        READ_CODE( 16, val, "extended_white_level_luma_code_value" );    sei.m_extendedWhiteLevelLumaCodeValue = val;
+          sei_read_code( pDecodedMessageOutputStream, 32,   val,   "exposure_index_value" );              sei.m_exposureIndexValue = val;
+        }
+        sei_read_flag( pDecodedMessageOutputStream, val, "exposure_compensation_value_sign_flag" );       sei.m_exposureCompensationValueSignFlag = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "exposure_compensation_value_numerator" );   sei.m_exposureCompensationValueNumerator = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "exposure_compensation_value_denom_idc" );   sei.m_exposureCompensationValueDenomIdc = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "ref_screen_luminance_white" );              sei.m_refScreenLuminanceWhite = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "extended_range_white_level" );              sei.m_extendedRangeWhiteLevel = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "nominal_black_level_code_value" );          sei.m_nominalBlackLevelLumaCodeValue = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "nominal_white_level_code_value" );          sei.m_nominalWhiteLevelLumaCodeValue= val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "extended_white_level_code_value" );         sei.m_extendedWhiteLevelLumaCodeValue = val;
         break;
       }
@@ -702,60 +779,58 @@
       }
     }//switch model id
-  }// if(!sei.m_toneMapCancelFlag) 
-
-  xParseByteAlign();
-}
-
-Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize)
+  }// if(!sei.m_toneMapCancelFlag)
+}
+
+Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   Int iCode;
   UInt uiCode;
-
-  READ_UVLC( uiCode,           "sop_seq_parameter_set_id"            ); sei.m_sopSeqParameterSetId = uiCode;
-  READ_UVLC( uiCode,           "num_pics_in_sop_minus1"              ); sei.m_numPicsInSopMinus1 = uiCode;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode,           "sop_seq_parameter_set_id"            ); sei.m_sopSeqParameterSetId = uiCode;
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode,           "num_pics_in_sop_minus1"              ); sei.m_numPicsInSopMinus1 = uiCode;
   for (UInt i = 0; i <= sei.m_numPicsInSopMinus1; i++)
   {
-    READ_CODE( 6, uiCode,                     "sop_desc_vcl_nalu_type" );  sei.m_sopDescVclNaluType[i] = uiCode;
-    READ_CODE( 3, sei.m_sopDescTemporalId[i], "sop_desc_temporal_id"   );  sei.m_sopDescTemporalId[i] = uiCode;
+    sei_read_code( pDecodedMessageOutputStream, 6, uiCode,                     "sop_vcl_nut[i]" );  sei.m_sopDescVclNaluType[i] = uiCode;
+    sei_read_code( pDecodedMessageOutputStream, 3, sei.m_sopDescTemporalId[i], "sop_temporal_id[i]"   );  sei.m_sopDescTemporalId[i] = uiCode;
     if (sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_W_RADL && sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_N_LP)
     {
-      READ_UVLC( sei.m_sopDescStRpsIdx[i],    "sop_desc_st_rps_idx"    ); sei.m_sopDescStRpsIdx[i] = uiCode;
+      sei_read_uvlc( pDecodedMessageOutputStream, sei.m_sopDescStRpsIdx[i],    "sop_short_term_rps_idx[i]"    ); sei.m_sopDescStRpsIdx[i] = uiCode;
     }
     if (i > 0)
     {
-      READ_SVLC( iCode,                       "sop_desc_poc_delta"     ); sei.m_sopDescPocDelta[i] = iCode;
-    }
-  }
-
-  xParseByteAlign();
-}
-
-Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps)
+      sei_read_svlc( pDecodedMessageOutputStream, iCode,                       "sop_poc_delta[i]"     ); sei.m_sopDescPocDelta[i] = iCode;
+    }
+  }
+}
+
+Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
 {
   UInt uiCode;
   SEIMessages seis;
-
-  READ_FLAG( uiCode,            "bitstream_subset_flag"         ); sei.m_bitStreamSubsetFlag = uiCode;
-  READ_FLAG( uiCode,            "nesting_op_flag"               ); sei.m_nestingOpFlag = uiCode;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_flag( pDecodedMessageOutputStream, uiCode,            "bitstream_subset_flag"         ); sei.m_bitStreamSubsetFlag = uiCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode,            "nesting_op_flag"               ); sei.m_nestingOpFlag = uiCode;
   if (sei.m_nestingOpFlag)
   {
-    READ_FLAG( uiCode,            "default_op_flag"               ); sei.m_defaultOpFlag = uiCode;
-    READ_UVLC( uiCode,            "nesting_num_ops_minus1"        ); sei.m_nestingNumOpsMinus1 = uiCode;
+    sei_read_flag( pDecodedMessageOutputStream, uiCode,            "default_op_flag"               ); sei.m_defaultOpFlag = uiCode;
+    sei_read_uvlc( pDecodedMessageOutputStream, uiCode,            "nesting_num_ops_minus1"        ); sei.m_nestingNumOpsMinus1 = uiCode;
     for (UInt i = sei.m_defaultOpFlag; i <= sei.m_nestingNumOpsMinus1; i++)
     {
-      READ_CODE( 3,        uiCode,  "nesting_max_temporal_id_plus1"   ); sei.m_nestingMaxTemporalIdPlus1[i] = uiCode;
-      READ_UVLC( uiCode,            "nesting_op_idx"                  ); sei.m_nestingOpIdx[i] = uiCode;
+      sei_read_code( pDecodedMessageOutputStream, 3,        uiCode,  "nesting_max_temporal_id_plus1[i]"   ); sei.m_nestingMaxTemporalIdPlus1[i] = uiCode;
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode,            "nesting_op_idx[i]"                  ); sei.m_nestingOpIdx[i] = uiCode;
     }
   }
   else
   {
-    READ_FLAG( uiCode,            "all_layers_flag"               ); sei.m_allLayersFlag       = uiCode;
+    sei_read_flag( pDecodedMessageOutputStream, uiCode,            "all_layers_flag"               ); sei.m_allLayersFlag       = uiCode;
     if (!sei.m_allLayersFlag)
     {
-      READ_CODE( 3,        uiCode,  "nesting_no_op_max_temporal_id_plus1"  ); sei.m_nestingNoOpMaxTemporalIdPlus1 = uiCode;
-      READ_UVLC( uiCode,            "nesting_num_layers_minus1"            ); sei.m_nestingNumLayersMinus1        = uiCode;
+      sei_read_code( pDecodedMessageOutputStream, 3,        uiCode,  "nesting_no_op_max_temporal_id_plus1"  ); sei.m_nestingNoOpMaxTemporalIdPlus1 = uiCode;
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode,            "nesting_num_layers_minus1"            ); sei.m_nestingNumLayersMinus1        = uiCode;
       for (UInt i = 0; i <= sei.m_nestingNumLayersMinus1; i++)
       {
-        READ_CODE( 6,           uiCode,     "nesting_layer_id"      ); sei.m_nestingLayerId[i]   = uiCode;
+        sei_read_code( pDecodedMessageOutputStream, 6,           uiCode,     "nesting_layer_id[i]"      ); sei.m_nestingLayerId[i]   = uiCode;
       }
     }
@@ -766,33 +841,38 @@
   {
     UInt code;
-    READ_FLAG( code, "nesting_zero_bit" );
-  }
-
-  sei.m_callerOwnsSEIs = false;
+    sei_read_flag( pDecodedMessageOutputStream, code, "nesting_zero_bit" );
+  }
 
   // read nested SEI messages
-  do {
-    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps);
+  do
+  {
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps, pDecodedMessageOutputStream);
   } while (m_pcBitstream->getNumBitsLeft() > 8);
 
-}
-#if H_MV
-Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei)
-{
-  UInt uiCode;
-  READ_CODE( 4, uiCode, "active_vps_id" );                      sei.m_activeVpsId = uiCode;
-  READ_UVLC(    uiCode, "num_additional_sub_streams_minus1" );  sei.m_numAdditionalSubStreams = uiCode + 1;
+  if (pDecodedMessageOutputStream)
+  {
+    (*pDecodedMessageOutputStream) << "End of scalable nesting SEI message\n";
+  }
+}
+
+#if NH_MV
+Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream )
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_code( pDecodedMessageOutputStream, 4, code, "active_vps_id" );                      sei.m_activeVpsId = code;
+  sei_read_uvlc( pDecodedMessageOutputStream, code, "num_additional_sub_streams_minus1" );     sei.m_numAdditionalSubStreams = code + 1;
 
   xResizeSubBitstreamPropertySeiArrays(sei);
   for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
   {
-    READ_CODE(  2, uiCode, "sub_bitstream_mode[i]"           ); sei.m_subBitstreamMode[i] = uiCode;
-    READ_UVLC(     uiCode, "output_layer_set_idx_to_vps[i]"  ); sei.m_outputLayerSetIdxToVps[i] = uiCode;
-    READ_CODE(  3, uiCode, "highest_sub_layer_id[i]"         ); sei.m_highestSublayerId[i] = uiCode;
-    READ_CODE( 16, uiCode, "avg_bit_rate[i]"                 ); sei.m_avgBitRate[i] = uiCode;
-    READ_CODE( 16, uiCode, "max_bit_rate[i]"                 ); sei.m_maxBitRate[i] = uiCode;
-  }
-  xParseByteAlign();
-}
+    sei_read_code( pDecodedMessageOutputStream,   2, code, "sub_bitstream_mode[i]"           ); sei.m_subBitstreamMode[i] = code;
+    sei_read_uvlc( pDecodedMessageOutputStream,  code, "output_layer_set_idx_to_vps[i]"      ); sei.m_outputLayerSetIdxToVps[i] = code;
+    sei_read_code( pDecodedMessageOutputStream,   3, code, "highest_sub_layer_id[i]"         ); sei.m_highestSublayerId[i] = code;
+    sei_read_code( pDecodedMessageOutputStream,  16, code, "avg_bit_rate[i]"                 ); sei.m_avgBitRate[i] = code;
+    sei_read_code( pDecodedMessageOutputStream,  16, code, "max_bit_rate[i]"                 ); sei.m_maxBitRate[i] = code;
+  }  
+}
+
 Void SEIReader::xResizeSubBitstreamPropertySeiArrays(SEISubBitstreamProperty &sei)
 {
@@ -805,15 +885,219 @@
 #endif
 
-Void SEIReader::xParseByteAlign()
+
+Void SEIReader::xParseSEITempMotionConstraintsTileSets(SEITempMotionConstrainedTileSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
   UInt code;
-  if( m_pcBitstream->getNumBitsRead() % 8 != 0 )
-  {
-    READ_FLAG( code, "bit_equal_to_one" );          assert( code == 1 );
-  }
-  while( m_pcBitstream->getNumBitsRead() % 8 != 0 )
-  {
-    READ_FLAG( code, "bit_equal_to_zero" );         assert( code == 0 );
-  }
-}
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, code, "mc_all_tiles_exact_sample_value_match_flag");  sei.m_mc_all_tiles_exact_sample_value_match_flag = (code != 0);
+  sei_read_flag( pDecodedMessageOutputStream, code, "each_tile_one_tile_set_flag");                 sei.m_each_tile_one_tile_set_flag                = (code != 0);
+
+  if(!sei.m_each_tile_one_tile_set_flag)
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "limited_tile_set_display_flag");  sei.m_limited_tile_set_display_flag = (code != 0);
+    sei_read_uvlc( pDecodedMessageOutputStream, code, "num_sets_in_message_minus1");     sei.setNumberOfTileSets(code + 1);
+
+    if(sei.getNumberOfTileSets() != 0)
+    {
+      for(Int i = 0; i < sei.getNumberOfTileSets(); i++)
+      {
+        sei_read_uvlc( pDecodedMessageOutputStream, code, "mcts_id");  sei.tileSetData(i).m_mcts_id = code;
+
+        if(sei.m_limited_tile_set_display_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code, "display_tile_set_flag");  sei.tileSetData(i).m_display_tile_set_flag = (code != 1);
+        }
+
+        sei_read_uvlc( pDecodedMessageOutputStream, code, "num_tile_rects_in_set_minus1");  sei.tileSetData(i).setNumberOfTileRects(code + 1);
+
+        for(Int j=0; j<sei.tileSetData(i).getNumberOfTileRects(); j++)
+        {
+          sei_read_uvlc( pDecodedMessageOutputStream, code, "top_left_tile_index");      sei.tileSetData(i).topLeftTileIndex(j)     = code;
+          sei_read_uvlc( pDecodedMessageOutputStream, code, "bottom_right_tile_index");  sei.tileSetData(i).bottomRightTileIndex(j) = code;
+        }
+
+        if(!sei.m_mc_all_tiles_exact_sample_value_match_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code, "exact_sample_value_match_flag");   sei.tileSetData(i).m_exact_sample_value_match_flag    = (code != 0);
+        }
+        sei_read_flag( pDecodedMessageOutputStream, code, "mcts_tier_level_idc_present_flag");  sei.tileSetData(i).m_mcts_tier_level_idc_present_flag = (code != 0);
+
+        if(sei.tileSetData(i).m_mcts_tier_level_idc_present_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code,    "mcts_tier_flag"); sei.tileSetData(i).m_mcts_tier_flag = (code != 0);
+          sei_read_code( pDecodedMessageOutputStream, 8, code, "mcts_level_idc"); sei.tileSetData(i).m_mcts_level_idc =  code;
+        }
+      }
+    }
+  }
+  else
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "max_mcs_tier_level_idc_present_flag");  sei.m_max_mcs_tier_level_idc_present_flag = code;
+    if(sei.m_max_mcs_tier_level_idc_present_flag)
+    {
+      sei_read_flag( pDecodedMessageOutputStream, code, "max_mcts_tier_flag");  sei.m_max_mcts_tier_flag = code;
+      sei_read_code( pDecodedMessageOutputStream, 8, code, "max_mcts_level_idc"); sei.m_max_mcts_level_idc = code;
+    }
+  }
+}
+
+Void SEIReader::xParseSEITimeCode(SEITimeCode& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_code( pDecodedMessageOutputStream, 2, code, "num_clock_ts"); sei.numClockTs = code;
+  for(Int i = 0; i < sei.numClockTs; i++)
+  {
+    TComSEITimeSet currentTimeSet;
+    sei_read_flag( pDecodedMessageOutputStream, code, "clock_time_stamp_flag[i]"); currentTimeSet.clockTimeStampFlag = code;
+    if(currentTimeSet.clockTimeStampFlag)
+    {
+      sei_read_flag( pDecodedMessageOutputStream, code, "nuit_field_based_flag"); currentTimeSet.numUnitFieldBasedFlag = code;
+      sei_read_code( pDecodedMessageOutputStream, 5, code, "counting_type"); currentTimeSet.countingType = code;
+      sei_read_flag( pDecodedMessageOutputStream, code, "full_timestamp_flag"); currentTimeSet.fullTimeStampFlag = code;
+      sei_read_flag( pDecodedMessageOutputStream, code, "discontinuity_flag"); currentTimeSet.discontinuityFlag = code;
+      sei_read_flag( pDecodedMessageOutputStream, code, "cnt_dropped_flag"); currentTimeSet.cntDroppedFlag = code;
+      sei_read_code( pDecodedMessageOutputStream, 9, code, "n_frames"); currentTimeSet.numberOfFrames = code;
+      if(currentTimeSet.fullTimeStampFlag)
+      {
+        sei_read_code( pDecodedMessageOutputStream, 6, code, "seconds_value"); currentTimeSet.secondsValue = code;
+        sei_read_code( pDecodedMessageOutputStream, 6, code, "minutes_value"); currentTimeSet.minutesValue = code;
+        sei_read_code( pDecodedMessageOutputStream, 5, code, "hours_value"); currentTimeSet.hoursValue = code;
+      }
+      else
+      {
+        sei_read_flag( pDecodedMessageOutputStream, code, "seconds_flag"); currentTimeSet.secondsFlag = code;
+        if(currentTimeSet.secondsFlag)
+        {
+          sei_read_code( pDecodedMessageOutputStream, 6, code, "seconds_value"); currentTimeSet.secondsValue = code;
+          sei_read_flag( pDecodedMessageOutputStream, code, "minutes_flag"); currentTimeSet.minutesFlag = code;
+          if(currentTimeSet.minutesFlag)
+          {
+            sei_read_code( pDecodedMessageOutputStream, 6, code, "minutes_value"); currentTimeSet.minutesValue = code;
+            sei_read_flag( pDecodedMessageOutputStream, code, "hours_flag"); currentTimeSet.hoursFlag = code;
+            if(currentTimeSet.hoursFlag)
+            {
+              sei_read_code( pDecodedMessageOutputStream, 5, code, "hours_value"); currentTimeSet.hoursValue = code;
+            }
+          }
+        }
+      }
+      sei_read_code( pDecodedMessageOutputStream, 5, code, "time_offset_length"); currentTimeSet.timeOffsetLength = code;
+      if(currentTimeSet.timeOffsetLength > 0)
+      {
+        sei_read_code( pDecodedMessageOutputStream, currentTimeSet.timeOffsetLength, code, "time_offset_value");
+        if((code & (1 << (currentTimeSet.timeOffsetLength-1))) == 0)
+        {
+          currentTimeSet.timeOffsetValue = code;
+        }
+        else
+        {
+          code &= (1<< (currentTimeSet.timeOffsetLength-1)) - 1;
+          currentTimeSet.timeOffsetValue = ~code + 1;
+        }
+      }
+    }
+    sei.timeSetArray[i] = currentTimeSet;
+  }
+}
+
+Void SEIReader::xParseSEIChromaSamplingFilterHint(SEIChromaSamplingFilterHint& sei, UInt payloadSize/*, TComSPS* sps*/, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt uiCode;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code( pDecodedMessageOutputStream, 8, uiCode, "ver_chroma_filter_idc"); sei.m_verChromaFilterIdc = uiCode;
+  sei_read_code( pDecodedMessageOutputStream, 8, uiCode, "hor_chroma_filter_idc"); sei.m_horChromaFilterIdc = uiCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "ver_filtering_process_flag"); sei.m_verFilteringProcessFlag = uiCode;
+  if(sei.m_verChromaFilterIdc == 1 || sei.m_horChromaFilterIdc == 1)
+  {
+    sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "target_format_idc"); sei.m_targetFormatIdc = uiCode;
+    if(sei.m_verChromaFilterIdc == 1)
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_vertical_filters"); sei.m_numVerticalFilters = uiCode;
+      if(sei.m_numVerticalFilters > 0)
+      {
+        sei.m_verTapLengthMinus1 = (Int*)malloc(sei.m_numVerticalFilters * sizeof(Int));
+        sei.m_verFilterCoeff = (Int**)malloc(sei.m_numVerticalFilters * sizeof(Int*));
+        for(Int i = 0; i < sei.m_numVerticalFilters; i ++)
+        {
+          sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "ver_tap_length_minus_1"); sei.m_verTapLengthMinus1[i] = uiCode;
+          sei.m_verFilterCoeff[i] = (Int*)malloc(sei.m_verTapLengthMinus1[i] * sizeof(Int));
+          for(Int j = 0; j < sei.m_verTapLengthMinus1[i]; j ++)
+          {
+            sei_read_svlc( pDecodedMessageOutputStream, sei.m_verFilterCoeff[i][j], "ver_filter_coeff");
+          }
+        }
+      }
+    }
+    if(sei.m_horChromaFilterIdc == 1)
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_horizontal_filters"); sei.m_numHorizontalFilters = uiCode;
+      if(sei.m_numHorizontalFilters  > 0)
+      {
+        sei.m_horTapLengthMinus1 = (Int*)malloc(sei.m_numHorizontalFilters * sizeof(Int));
+        sei.m_horFilterCoeff = (Int**)malloc(sei.m_numHorizontalFilters * sizeof(Int*));
+        for(Int i = 0; i < sei.m_numHorizontalFilters; i ++)
+        {
+          sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "hor_tap_length_minus_1"); sei.m_horTapLengthMinus1[i] = uiCode;
+          sei.m_horFilterCoeff[i] = (Int*)malloc(sei.m_horTapLengthMinus1[i] * sizeof(Int));
+          for(Int j = 0; j < sei.m_horTapLengthMinus1[i]; j ++)
+          {
+            sei_read_svlc( pDecodedMessageOutputStream, sei.m_horFilterCoeff[i][j], "hor_filter_coeff");
+          }
+        }
+      }
+    }
+  }
+}
+
+Void SEIReader::xParseSEIKneeFunctionInfo(SEIKneeFunctionInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  Int i;
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "knee_function_id" );                   sei.m_kneeId = val;
+  sei_read_flag( pDecodedMessageOutputStream, val, "knee_function_cancel_flag" );          sei.m_kneeCancelFlag = val;
+  if ( !sei.m_kneeCancelFlag )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, val, "knee_function_persistence_flag" );   sei.m_kneePersistenceFlag = val;
+    sei_read_code( pDecodedMessageOutputStream, 32, val, "input_d_range" );                sei.m_kneeInputDrange = val;
+    sei_read_code( pDecodedMessageOutputStream, 32, val, "input_disp_luminance" );         sei.m_kneeInputDispLuminance = val;
+    sei_read_code( pDecodedMessageOutputStream, 32, val, "output_d_range" );               sei.m_kneeOutputDrange = val;
+    sei_read_code( pDecodedMessageOutputStream, 32, val, "output_disp_luminance" );        sei.m_kneeOutputDispLuminance = val;
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "num_knee_points_minus1" );           sei.m_kneeNumKneePointsMinus1 = val;
+    assert( sei.m_kneeNumKneePointsMinus1 > 0 );
+    sei.m_kneeInputKneePoint.resize(sei.m_kneeNumKneePointsMinus1+1);
+    sei.m_kneeOutputKneePoint.resize(sei.m_kneeNumKneePointsMinus1+1);
+    for(i = 0; i <= sei.m_kneeNumKneePointsMinus1; i++ )
+    {
+      sei_read_code( pDecodedMessageOutputStream, 10, val, "input_knee_point" );           sei.m_kneeInputKneePoint[i] = val;
+      sei_read_code( pDecodedMessageOutputStream, 10, val, "output_knee_point" );          sei.m_kneeOutputKneePoint[i] = val;
+    }
+  }
+}
+
+Void SEIReader::xParseSEIMasteringDisplayColourVolume(SEIMasteringDisplayColourVolume& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[0]" ); sei.values.primaries[0][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[0]" ); sei.values.primaries[0][1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[1]" ); sei.values.primaries[1][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[1]" ); sei.values.primaries[1][1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[2]" ); sei.values.primaries[2][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[2]" ); sei.values.primaries[2][1] = code;
+
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "white_point_x" ); sei.values.whitePoint[0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "white_point_y" ); sei.values.whitePoint[1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 32, code, "max_display_mastering_luminance" ); sei.values.maxLuminance = code;
+  sei_read_code( pDecodedMessageOutputStream, 32, code, "min_display_mastering_luminance" ); sei.values.minLuminance = code;
+}
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SEIread.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SEIread.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -56,26 +56,37 @@
   SEIReader() {};
   virtual ~SEIReader() {};
-  Void parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps);
+  Void parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
 protected:
-  Void xReadSEImessage                (SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps);
-  Void xParseSEIuserDataUnregistered  (SEIuserDataUnregistered &sei, UInt payloadSize);
-  Void xParseSEIActiveParameterSets   (SEIActiveParameterSets  &sei, UInt payloadSize);
-  Void xParseSEIDecodingUnitInfo      (SEIDecodingUnitInfo& sei, UInt payloadSize, TComSPS *sps);
-  Void xParseSEIDecodedPictureHash    (SEIDecodedPictureHash& sei, UInt payloadSize);
-  Void xParseSEIBufferingPeriod       (SEIBufferingPeriod& sei, UInt payloadSize, TComSPS *sps);
-  Void xParseSEIPictureTiming         (SEIPictureTiming& sei, UInt payloadSize, TComSPS *sps);
-  Void xParseSEIRecoveryPoint         (SEIRecoveryPoint& sei, UInt payloadSize);
-  Void xParseSEIFramePacking          (SEIFramePacking& sei, UInt payloadSize);
-  Void xParseSEIDisplayOrientation    (SEIDisplayOrientation &sei, UInt payloadSize);
-  Void xParseSEITemporalLevel0Index   (SEITemporalLevel0Index &sei, UInt payloadSize);
-  Void xParseSEIGradualDecodingRefreshInfo (SEIGradualDecodingRefreshInfo &sei, UInt payloadSize);
-  Void xParseSEIToneMappingInfo       (SEIToneMappingInfo& sei, UInt payloadSize);
-  Void xParseSEISOPDescription        (SEISOPDescription &sei, UInt payloadSize);
-  Void xParseSEIScalableNesting       (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps);
-#if H_MV
-  Void  xParseSEISubBitstreamProperty   (SEISubBitstreamProperty &sei);
-  Void  xResizeSubBitstreamPropertySeiArrays(SEISubBitstreamProperty &sei);
+  Void xReadSEImessage                        (SEIMessages& seis, const NalUnitType nalUnitType, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIuserDataUnregistered          (SEIuserDataUnregistered &sei,          UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIActiveParameterSets           (SEIActiveParameterSets  &sei,          UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIDecodingUnitInfo              (SEIDecodingUnitInfo& sei,              UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIDecodedPictureHash            (SEIDecodedPictureHash& sei,            UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIBufferingPeriod               (SEIBufferingPeriod& sei,               UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIPictureTiming                 (SEIPictureTiming& sei,                 UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIRecoveryPoint                 (SEIRecoveryPoint& sei,                 UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIFramePacking                  (SEIFramePacking& sei,                  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEISegmentedRectFramePacking     (SEISegmentedRectFramePacking& sei,     UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIDisplayOrientation            (SEIDisplayOrientation &sei,            UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEITemporalLevel0Index           (SEITemporalLevel0Index &sei,           UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIRegionRefreshInfo             (SEIGradualDecodingRefreshInfo &sei,    UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEINoDisplay                     (SEINoDisplay &sei,                     UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIToneMappingInfo               (SEIToneMappingInfo& sei,               UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEISOPDescription                (SEISOPDescription &sei,                UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIScalableNesting               (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEITempMotionConstraintsTileSets (SEITempMotionConstrainedTileSets& sei, UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEITimeCode                      (SEITimeCode& sei,                      UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIChromaSamplingFilterHint      (SEIChromaSamplingFilterHint& sei,      UInt payloadSize/*,TComSPS* */,       std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIKneeFunctionInfo              (SEIKneeFunctionInfo& sei,              UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIMasteringDisplayColourVolume  (SEIMasteringDisplayColourVolume& sei,  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+#if NH_MV
+  Void  xParseSEISubBitstreamProperty         (SEISubBitstreamProperty &sei        ,  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void  xResizeSubBitstreamPropertySeiArrays  (SEISubBitstreamProperty &sei);
 #endif
-  Void xParseByteAlign();
+
+  Void sei_read_code(std::ostream *pOS, UInt uiLength, UInt& ruiCode, const Char *pSymbolName);
+  Void sei_read_uvlc(std::ostream *pOS,                UInt& ruiCode, const Char *pSymbolName);
+  Void sei_read_svlc(std::ostream *pOS,                Int&  ruiCode, const Char *pSymbolName);
+  Void sei_read_flag(std::ostream *pOS,                UInt& ruiCode, const Char *pSymbolName);
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1200)
@@ -2,5 +2,5 @@
 * 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.  
+* granted under this license.
 *
 * Copyright (c) 2010-2015, ITU/ISO/IEC
@@ -43,4 +43,7 @@
 #include "TLibCommon/TComBitStream.h"
 #include "SyntaxElementParser.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
 
 #if ENC_DEC_TRACE
@@ -48,5 +51,9 @@
 Void  SyntaxElementParser::xReadCodeTr           (UInt length, UInt& rValue, const Char *pSymbolName)
 {
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadCode (length, rValue, pSymbolName);
+#else
   xReadCode (length, rValue);
+#endif
 #if H_MV_ENC_DEC_TRAC
   if ( g_disableHLSTrace || !g_HLSTraceEnable )
@@ -61,12 +68,11 @@
   }
 #endif
-
   if (length < 10)
   {
-    fprintf( g_hTrace, "%-50s u(%d)  : %u\n", pSymbolName, length, rValue ); 
+    fprintf( g_hTrace, "%-50s u(%d)  : %u\n", pSymbolName, length, rValue );
   }
   else
   {
-    fprintf( g_hTrace, "%-50s u(%d) : %u\n", pSymbolName, length, rValue ); 
+    fprintf( g_hTrace, "%-50s u(%d) : %u\n", pSymbolName, length, rValue );
   }
   fflush ( g_hTrace );
@@ -75,7 +81,11 @@
 Void  SyntaxElementParser::xReadUvlcTr           (UInt& rValue, const Char *pSymbolName)
 {
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadUvlc (rValue, pSymbolName);
+#else
   xReadUvlc (rValue);
-#if H_MV_ENC_DEC_TRAC
-  if ( g_disableHLSTrace  || !g_HLSTraceEnable )
+#endif
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace || !g_HLSTraceEnable )
   {
     return; 
@@ -88,5 +98,5 @@
   }
 #endif
-  fprintf( g_hTrace, "%-50s ue(v) : %u\n", pSymbolName, rValue ); 
+  fprintf( g_hTrace, "%-50s ue(v) : %u\n", pSymbolName, rValue );
   fflush ( g_hTrace );
 }
@@ -94,7 +104,11 @@
 Void  SyntaxElementParser::xReadSvlcTr           (Int& rValue, const Char *pSymbolName)
 {
-  xReadSvlc(rValue);
-#if H_MV_ENC_DEC_TRAC
-  if ( g_disableHLSTrace  || !g_HLSTraceEnable  )
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadSvlc (rValue, pSymbolName);
+#else
+  xReadSvlc (rValue);
+#endif
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace || !g_HLSTraceEnable )
   {
     return; 
@@ -107,6 +121,5 @@
   }
 #endif
-
-  fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, rValue ); 
+  fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, rValue );
   fflush ( g_hTrace );
 }
@@ -114,7 +127,11 @@
 Void  SyntaxElementParser::xReadFlagTr           (UInt& rValue, const Char *pSymbolName)
 {
-  xReadFlag(rValue);
-#if H_MV_ENC_DEC_TRAC
-  if ( g_disableHLSTrace  || !g_HLSTraceEnable )
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadFlag (rValue, pSymbolName);
+#else
+  xReadFlag (rValue);
+#endif
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace || !g_HLSTraceEnable )
   {
     return; 
@@ -127,6 +144,16 @@
   }
 #endif
-  fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, rValue ); 
+  fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, rValue );
   fflush ( g_hTrace );
+}
+
+Void  xTraceAccessUnitDelimiter ()
+{
+  fprintf( g_hTrace, "=========== Access Unit Delimiter ===========\n");
+}
+
+Void xTraceFillerData ()
+{
+  fprintf( g_hTrace, "=========== Filler Data ===========\n");
 }
 
@@ -137,12 +164,22 @@
 // Protected member functions
 // ====================================================================================================================
-
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode, const Char *pSymbolName)
+#else
 Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode)
+#endif
 {
   assert ( uiLength > 0 );
   m_pcBitstream->read (uiLength, ruiCode);
-}
-
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, uiLength, ruiCode);
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadUvlc( UInt& ruiVal, const Char *pSymbolName)
+#else
 Void SyntaxElementParser::xReadUvlc( UInt& ruiVal)
+#endif
 {
   UInt uiVal = 0;
@@ -150,4 +187,7 @@
   UInt uiLength;
   m_pcBitstream->read( 1, uiCode );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  UInt totalLen=1;
+#endif
 
   if( 0 == uiCode )
@@ -164,13 +204,26 @@
 
     uiVal += (1 << uiLength)-1;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    totalLen+=uiLength+uiLength;
+#endif
   }
 
   ruiVal = uiVal;
-}
-
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, Int(totalLen), ruiVal);
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadSvlc( Int& riVal, const Char *pSymbolName)
+#else
 Void SyntaxElementParser::xReadSvlc( Int& riVal)
+#endif
 {
   UInt uiBits = 0;
   m_pcBitstream->read( 1, uiBits );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  UInt totalLen=1;
+#endif
   if( 0 == uiBits )
   {
@@ -187,4 +240,7 @@
     uiBits += (1 << uiLength);
     riVal = ( uiBits & 1) ? -(Int)(uiBits>>1) : (Int)(uiBits>>1);
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    totalLen+=uiLength+uiLength;
+#endif
   }
   else
@@ -192,9 +248,63 @@
     riVal = 0;
   }
-}
-
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, Int(totalLen), riVal);
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadFlag (UInt& ruiCode, const Char *pSymbolName)
+#else
 Void SyntaxElementParser::xReadFlag (UInt& ruiCode)
+#endif
 {
   m_pcBitstream->read( 1, ruiCode );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, 1, Int(ruiCode));
+#endif
+}
+
+Void SyntaxElementParser::xReadRbspTrailingBits()
+{
+  UInt bit;
+  READ_FLAG( bit, "rbsp_stop_one_bit");
+  assert (bit==1);
+  Int cnt = 0;
+  while (m_pcBitstream->getNumBitsUntilByteAligned())
+  {
+    READ_FLAG( bit, "rbsp_alignment_zero_bit");
+    assert (bit==0);
+    cnt++;
+  }
+  assert(cnt<8);
+}
+
+Void AUDReader::parseAccessUnitDelimiter(TComInputBitstream* bs, UInt &picType)
+{
+  setBitstream(bs);
+
+#if ENC_DEC_TRACE
+  xTraceAccessUnitDelimiter();
+#endif
+
+  READ_CODE (3, picType, "pic_type");
+  xReadRbspTrailingBits();
+}
+
+Void FDReader::parseFillerData(TComInputBitstream* bs, UInt &fdSize)
+{
+  setBitstream(bs);
+#if ENC_DEC_TRACE
+  xTraceFillerData();
+#endif
+  UInt ffByte;
+  fdSize = 0;
+  while( m_pcBitstream->getNumBitsLeft() >8 )
+  {
+    READ_CODE (8, ffByte, "ff_byte");
+    assert (ffByte==0xff);
+    fdSize++;
+  }
+  xReadRbspTrailingBits();
 }
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SyntaxElementParser.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -43,5 +43,5 @@
 #endif // _MSC_VER > 1000
 
-#include "../TLibCommon/TComRom.h"
+#include "TLibCommon/TComRom.h"
 
 #if ENC_DEC_TRACE
@@ -54,8 +54,19 @@
 #else
 
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+
+#define READ_CODE(length, code, name)     xReadCode ( length, code, name )
+#define READ_UVLC(        code, name)     xReadUvlc (         code, name )
+#define READ_SVLC(        code, name)     xReadSvlc (         code, name )
+#define READ_FLAG(        code, name)     xReadFlag (         code, name )
+
+#else
+
 #define READ_CODE(length, code, name)     xReadCode ( length, code )
 #define READ_UVLC(        code, name)     xReadUvlc (         code )
 #define READ_SVLC(        code, name)     xReadSvlc (         code )
 #define READ_FLAG(        code, name)     xReadFlag (         code )
+
+#endif
 
 #endif
@@ -78,8 +89,15 @@
   virtual ~SyntaxElementParser() {};
 
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  Void  xReadCode    ( UInt   length, UInt& val, const Char *pSymbolName );
+  Void  xReadUvlc    ( UInt&  val, const Char *pSymbolName );
+  Void  xReadSvlc    ( Int&   val, const Char *pSymbolName );
+  Void  xReadFlag    ( UInt&  val, const Char *pSymbolName );
+#else
   Void  xReadCode    ( UInt   length, UInt& val );
   Void  xReadUvlc    ( UInt&  val );
   Void  xReadSvlc    ( Int&   val );
   Void  xReadFlag    ( UInt&  val );
+#endif
 #if ENC_DEC_TRACE
   Void  xReadCodeTr  (UInt  length, UInt& rValue, const Char *pSymbolName);
@@ -91,5 +109,25 @@
   Void  setBitstream ( TComInputBitstream* p )   { m_pcBitstream = p; }
   TComInputBitstream* getBitstream() { return m_pcBitstream; }
+
+protected:
+  Void xReadRbspTrailingBits();
 };
+
+class AUDReader: public SyntaxElementParser
+{
+public:
+  AUDReader() {};
+  virtual ~AUDReader() {};
+  Void parseAccessUnitDelimiter(TComInputBitstream* bs, UInt &picType);
+};
+
+class FDReader: public SyntaxElementParser
+{
+public:
+  FDReader() {};
+  virtual ~FDReader() {};
+  Void parseFillerData(TComInputBitstream* bs, UInt &fdSize);
+};
+
 
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,9 +36,13 @@
 */
 
-#ifndef __TDEC_BIN_CODER__
-#define __TDEC_BIN_CODER__
+#ifndef __TDECBINCODER__
+#define __TDECBINCODER__
 
 #include "TLibCommon/ContextModel.h"
 #include "TLibCommon/TComBitStream.h"
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+class TComCodingStatisticsClassType;
+#endif
 
 //! \ingroup TLibDecoder
@@ -55,15 +59,25 @@
   virtual Void  finish            ()                                          = 0;
 
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel, const class TComCodingStatisticsClassType &whichStat )  = 0;
+  virtual Void  decodeBinEP       ( UInt& ruiBin                          , const class TComCodingStatisticsClassType &whichStat )  = 0;
+  virtual Void  decodeBinsEP      ( UInt& ruiBins, Int numBins            , const class TComCodingStatisticsClassType &whichStat )  = 0;
+#else
   virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel )  = 0;
   virtual Void  decodeBinEP       ( UInt& ruiBin                           )  = 0;
   virtual Void  decodeBinsEP      ( UInt& ruiBins, Int numBins             )  = 0;
+#endif
+
+  virtual Void  align             ()                                          = 0;
+
   virtual Void  decodeBinTrm      ( UInt& ruiBin                           )  = 0;
-  
-  virtual Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode)              = 0;
+
+  virtual Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode)             = 0;
 
   virtual ~TDecBinIf() {}
 
-  virtual Void  copyState         ( TDecBinIf* pcTDecBinIf )                  = 0;
-  virtual TDecBinCABAC*   getTDecBinCABAC   ()  { return 0; }
+  virtual Void  copyState         ( const TDecBinIf* pcTDecBinIf )            = 0;
+  virtual TDecBinCABAC*   getTDecBinCABAC   ()             { return 0; }
+  virtual const TDecBinCABAC*   getTDecBinCABAC   () const { return 0; }
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,5 +37,8 @@
 
 #include "TDecBinCoderCABAC.h"
-#include "../TLibCommon/TComRom.h"
+#include "TLibCommon/Debug.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
 
 //! \ingroup TLibDecoder
@@ -67,4 +70,7 @@
 {
   assert( m_pcTComBitstream->getNumBitsUntilByteAligned() == 0 );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::UpdateCABACStat(STATS__CABAC_INITIALISATION, 512, 510, 0);
+#endif
   m_uiRange    = 510;
   m_bitsNeeded = -8;
@@ -89,7 +95,7 @@
  */
 Void
-TDecBinCABAC::copyState( TDecBinIf* pcTDecBinIf )
-{
-  TDecBinCABAC* pcTDecBinCABAC = pcTDecBinIf->getTDecBinCABAC();
+TDecBinCABAC::copyState( const TDecBinIf* pcTDecBinIf )
+{
+  const TDecBinCABAC* pcTDecBinCABAC = pcTDecBinIf->getTDecBinCABAC();
   m_uiRange   = pcTDecBinCABAC->m_uiRange;
   m_uiValue   = pcTDecBinCABAC->m_uiValue;
@@ -98,29 +104,38 @@
 
 
-Void
-TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel )
-{
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel, const TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel )
+#endif
+{
+#if DEBUG_CABAC_BINS
+  const UInt startingRange = m_uiRange;
+#endif
+
   UInt uiLPS = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) - 4 ];
   m_uiRange -= uiLPS;
   UInt scaledRange = m_uiRange << 7;
-  
+
   if( m_uiValue < scaledRange )
   {
     // MPS path
     ruiBin = rcCtxModel.getMps();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::UpdateCABACStat(whichStat, m_uiRange+uiLPS, m_uiRange, Int(ruiBin));
+#endif
     rcCtxModel.updateMPS();
-    
-    if ( scaledRange >= ( 256 << 7 ) )
-    {
-      return;
-    }
-    
-    m_uiRange = scaledRange >> 6;
-    m_uiValue += m_uiValue;
-    
-    if ( ++m_bitsNeeded == 0 )
-    {
-      m_bitsNeeded = -8;
-      m_uiValue += m_pcTComBitstream->readByte();      
+
+    if ( scaledRange < ( 256 << 7 ) )
+    {
+      m_uiRange = scaledRange >> 6;
+      m_uiValue += m_uiValue;
+
+      if ( ++m_bitsNeeded == 0 )
+      {
+        m_bitsNeeded = -8;
+        m_uiValue += m_pcTComBitstream->readByte();
+      }
     }
   }
@@ -128,12 +143,15 @@
   {
     // LPS path
+    ruiBin      = 1 - rcCtxModel.getMps();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::UpdateCABACStat(whichStat, m_uiRange+uiLPS, uiLPS, Int(ruiBin));
+#endif
     Int numBits = TComCABACTables::sm_aucRenormTable[ uiLPS >> 3 ];
     m_uiValue   = ( m_uiValue - scaledRange ) << numBits;
     m_uiRange   = uiLPS << numBits;
-    ruiBin      = 1 - rcCtxModel.getMps();
     rcCtxModel.updateLPS();
-    
+
     m_bitsNeeded += numBits;
-    
+
     if ( m_bitsNeeded >= 0 )
     {
@@ -142,11 +160,43 @@
     }
   }
-}
-
-Void
-TDecBinCABAC::decodeBinEP( UInt& ruiBin )
-{
+
+#if DEBUG_CABAC_BINS
+  if ((g_debugCounter + debugCabacBinWindow) >= debugCabacBinTargetLine)
+  {
+    std::cout << g_debugCounter << ": coding bin value " << ruiBin << ", range = [" << startingRange << "->" << m_uiRange << "]\n";
+  }
+
+  if (g_debugCounter >= debugCabacBinTargetLine)
+  {
+    Char breakPointThis;
+    breakPointThis = 7;
+  }
+  if (g_debugCounter >= (debugCabacBinTargetLine + debugCabacBinWindow))
+  {
+    exit(0);
+  }
+  g_debugCounter++;
+#endif
+}
+
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecBinCABAC::decodeBinEP( UInt& ruiBin, const TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecBinCABAC::decodeBinEP( UInt& ruiBin )
+#endif
+{
+  if (m_uiRange == 256)
+  {
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    decodeAlignedBinsEP(ruiBin, 1, whichStat);
+#else
+    decodeAlignedBinsEP(ruiBin, 1);
+#endif
+    return;
+  }
+
   m_uiValue += m_uiValue;
-  
+
   if ( ++m_bitsNeeded >= 0 )
   {
@@ -154,5 +204,5 @@
     m_uiValue += m_pcTComBitstream->readByte();
   }
-  
+
   ruiBin = 0;
   UInt scaledRange = m_uiRange << 7;
@@ -162,14 +212,33 @@
     m_uiValue -= scaledRange;
   }
-}
-
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(whichStat, 1, Int(ruiBin));
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecBinCABAC::decodeBinsEP( UInt& ruiBin, Int numBins, const TComCodingStatisticsClassType &whichStat )
+#else
 Void TDecBinCABAC::decodeBinsEP( UInt& ruiBin, Int numBins )
-{
+#endif
+{
+  if (m_uiRange == 256)
+  {
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    decodeAlignedBinsEP(ruiBin, numBins, whichStat);
+#else
+    decodeAlignedBinsEP(ruiBin, numBins);
+#endif
+    return;
+  }
+
   UInt bins = 0;
-  
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  Int origNumBins=numBins;
+#endif
   while ( numBins > 8 )
   {
     m_uiValue = ( m_uiValue << 8 ) + ( m_pcTComBitstream->readByte() << ( 8 + m_bitsNeeded ) );
-    
+
     UInt scaledRange = m_uiRange << 15;
     for ( Int i = 0; i < 8; i++ )
@@ -185,8 +254,8 @@
     numBins -= 8;
   }
-  
+
   m_bitsNeeded += numBins;
   m_uiValue <<= numBins;
-  
+
   if ( m_bitsNeeded >= 0 )
   {
@@ -194,5 +263,5 @@
     m_bitsNeeded -= 8;
   }
-  
+
   UInt scaledRange = m_uiRange << ( numBins + 7 );
   for ( Int i = 0; i < numBins; i++ )
@@ -206,6 +275,62 @@
     }
   }
-  
+
   ruiBin = bins;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(whichStat, origNumBins, Int(ruiBin));
+#endif
+}
+
+Void TDecBinCABAC::align()
+{
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::UpdateCABACStat(STATS__CABAC_EP_BIT_ALIGNMENT, m_uiRange, 256, 0);
+#endif
+  m_uiRange = 256;
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecBinCABAC::decodeAlignedBinsEP( UInt& ruiBins, Int numBins, const class TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecBinCABAC::decodeAlignedBinsEP( UInt& ruiBins, Int numBins )
+#endif
+{
+  Int binsRemaining = numBins;
+  ruiBins = 0;
+
+  assert(m_uiRange == 256); //aligned decode only works when range = 256
+
+  while (binsRemaining > 0)
+  {
+    const UInt binsToRead = std::min<UInt>(binsRemaining, 8); //read bytes if able to take advantage of the system's byte-read function
+    const UInt binMask    = (1 << binsToRead) - 1;
+
+    //The MSB of m_uiValue is known to be 0 because range is 256. Therefore:
+    // > The comparison against the symbol range of 128 is simply a test on the next-most-significant bit
+    // > "Subtracting" the symbol range if the decoded bin is 1 simply involves clearing that bit.
+    //
+    //As a result, the required bins are simply the <binsToRead> next-most-significant bits of m_uiValue
+    //(m_uiValue is stored MSB-aligned in a 16-bit buffer - hence the shift of 15)
+    //
+    //   m_uiValue = |0|V|V|V|V|V|V|V|V|B|B|B|B|B|B|B|        (V = usable bit, B = potential buffered bit (buffer refills when m_bitsNeeded >= 0))
+    //
+    const UInt newBins = (m_uiValue >> (15 - binsToRead)) & binMask;
+
+    ruiBins   = (ruiBins   << binsToRead) | newBins;
+    m_uiValue = (m_uiValue << binsToRead) & 0x7FFF;
+
+    binsRemaining -= binsToRead;
+    m_bitsNeeded  += binsToRead;
+
+    if (m_bitsNeeded >= 0)
+    {
+      m_uiValue    |= m_pcTComBitstream->readByte() << m_bitsNeeded;
+      m_bitsNeeded -= 8;
+    }
+  }
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(whichStat, numBins, Int(ruiBins));
+#endif
 }
 
@@ -218,17 +343,24 @@
   {
     ruiBin = 1;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::UpdateCABACStat(STATS__CABAC_TRM_BITS, m_uiRange+2, 2, ruiBin);
+    TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS, -m_bitsNeeded, 0);
+#endif
   }
   else
   {
     ruiBin = 0;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::UpdateCABACStat(STATS__CABAC_TRM_BITS, m_uiRange+2, m_uiRange, ruiBin);
+#endif
     if ( scaledRange < ( 256 << 7 ) )
     {
       m_uiRange = scaledRange >> 6;
       m_uiValue += m_uiValue;
-      
+
       if ( ++m_bitsNeeded == 0 )
       {
         m_bitsNeeded = -8;
-        m_uiValue += m_pcTComBitstream->readByte();      
+        m_uiValue += m_pcTComBitstream->readByte();
       }
     }
@@ -245,4 +377,7 @@
   assert ( uiLength > 0 );
   m_pcTComBitstream->read (uiLength, ruiCode);
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(STATS__CABAC_PCM_CODE_BITS, uiLength, ruiCode);
+#endif
 }
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,6 +36,6 @@
 */
 
-#ifndef __TDEC_BIN_CODER_CABAC__
-#define __TDEC_BIN_CODER_CABAC__
+#ifndef __TDECBINCODERCABAC__
+#define __TDECBINCODERCABAC__
 
 #include "TLibCommon/TComCABACTables.h"
@@ -50,20 +50,32 @@
   TDecBinCABAC ();
   virtual ~TDecBinCABAC();
-  
+
   Void  init              ( TComInputBitstream* pcTComBitstream );
   Void  uninit            ();
-  
+
   Void  start             ();
   Void  finish            ();
-  
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  Void  decodeBin          ( UInt& ruiBin, ContextModel& rcCtxModel, const class TComCodingStatisticsClassType &whichStat );
+  Void  decodeBinEP        ( UInt& ruiBin                          , const class TComCodingStatisticsClassType &whichStat );
+  Void  decodeBinsEP       ( UInt& ruiBin, Int numBins             , const class TComCodingStatisticsClassType &whichStat );
+  Void  decodeAlignedBinsEP( UInt& ruiBins, Int numBins            , const class TComCodingStatisticsClassType &whichStat );
+#else
   Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel );
   Void  decodeBinEP       ( UInt& ruiBin                           );
   Void  decodeBinsEP      ( UInt& ruiBin, Int numBins              );
+  Void  decodeAlignedBinsEP( UInt& ruiBins, Int numBins             );
+#endif
+
+  Void  align             ();
+
   Void  decodeBinTrm      ( UInt& ruiBin                           );
-  
+
   Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode );
-  
-  Void  copyState         ( TDecBinIf* pcTDecBinIf );
-  TDecBinCABAC* getTDecBinCABAC()  { return this; }
+
+  Void  copyState         ( const TDecBinIf* pcTDecBinIf );
+  TDecBinCABAC* getTDecBinCABAC()             { return this; }
+  const TDecBinCABAC* getTDecBinCABAC() const { return this; }
 
 private:
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1200)
@@ -2,5 +2,5 @@
 * 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.  
+* granted under this license.
 *
 * Copyright (c) 2010-2015, ITU/ISO/IEC
@@ -39,52 +39,33 @@
 #include "SEIread.h"
 #include "TDecSlice.h"
-#if H_3D
+#include "TLibCommon/TComChromaFormat.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+#if NH_MV
 #include "TDecTop.h"
 #endif
+
 //! \ingroup TLibDecoder
 //! \{
 
 #if ENC_DEC_TRACE
-
-Void  xTraceSPSHeader (TComSPS *pSPS)
-{
-#if H_MV_ENC_DEC_TRAC
-  if ( g_disableHLSTrace )
-  {
-    return; 
-  }
-  // To avoid mismatches
-  fprintf( g_hTrace, "=========== Sequence Parameter Set LayerId: %d ===========\n", pSPS->getLayerId() );
-#else
-  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
-#endif
-}
-
-Void  xTracePPSHeader (TComPPS *pPPS)
-{
-#if H_MV_ENC_DEC_TRAC
-  if ( g_disableHLSTrace )
-  {
-    return; 
-  }
-  fprintf( g_hTrace, "=========== Picture Parameter Set LayerId: %d ===========\n", pPPS->getLayerId() );
-#else
-  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
-#endif
-}
-
-Void  xTraceSliceHeader (TComSlice *pSlice)
-{
-#if H_MV_ENC_DEC_TRAC
-  if ( g_disableHLSTrace )
-  {
-    return; 
-  }
-#endif
-  fprintf( g_hTrace, "=========== Slice ===========\n");
-}
-
-#endif
-
+#if !H_MV_ENC_DEC_TRAC
+Void  xTraceVPSHeader ()
+{
+  fprintf( g_hTrace, "=========== Video Parameter Set     ===========\n" );
+}
+
+Void  xTraceSPSHeader ()
+{
+  fprintf( g_hTrace, "=========== Sequence Parameter Set  ===========\n" );
+}
+
+Void  xTracePPSHeader ()
+{
+  fprintf( g_hTrace, "=========== Picture Parameter Set  ===========\n");
+}
+#endif
+#endif
 // ====================================================================================================================
 // Constructor / destructor / create / destroy
@@ -97,4 +78,5 @@
 TDecCavlc::~TDecCavlc()
 {
+
 }
 
@@ -103,5 +85,5 @@
 // ====================================================================================================================
 
-void TDecCavlc::parseShortTermRefPicSet( TComSPS* sps, TComReferencePictureSet* rps, Int idx )
+Void TDecCavlc::parseShortTermRefPicSet( TComSPS* sps, TComReferencePictureSet* rps, Int idx )
 {
   UInt code;
@@ -117,5 +99,5 @@
   }
 
-  if (interRPSPred) 
+  if (interRPSPred)
   {
     UInt bit;
@@ -138,7 +120,7 @@
     for(Int j=0 ; j <= rpsRef->getNumberOfPictures(); j++)
     {
-      READ_CODE(1, bit, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1 
+      READ_CODE(1, bit, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1
       Int refIdc = bit;
-      if (refIdc == 0) 
+      if (refIdc == 0)
       {
         READ_CODE(1, bit, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
@@ -155,13 +137,13 @@
           k0++;
         }
-        else 
+        else
         {
           k1++;
         }
         k++;
-      }  
-      rps->setRefIdc(j,refIdc);  
-    }
-    rps->setNumRefIdc(rpsRef->getNumberOfPictures()+1);  
+      }
+      rps->setRefIdc(j,refIdc);
+    }
+    rps->setNumRefIdc(rpsRef->getNumberOfPictures()+1);
     rps->setNumberOfPictures(k);
     rps->setNumberOfNegativePictures(k0);
@@ -199,12 +181,12 @@
 }
 
-#if H_3D
-Void TDecCavlc::parsePPS(TComPPS* pcPPS, TComVPS* pcVPS )
+Void TDecCavlc::parsePPS(TComPPS* pcPPS)
+{
+#if ENC_DEC_TRACE
+#if H_MV_ENC_DEC_TRAC
+  tracePSHeader( "PPS", pcPPS->getLayerId() ); 
 #else
-Void TDecCavlc::parsePPS(TComPPS* pcPPS)
-#endif
-{
-#if ENC_DEC_TRACE  
-  xTracePPSHeader (pcPPS);
+  xTracePPSHeader ();
+#endif
 #endif
   UInt  uiCode;
@@ -215,13 +197,15 @@
   assert(uiCode <= 63);
   pcPPS->setPPSId (uiCode);
-  
+
   READ_UVLC( uiCode, "pps_seq_parameter_set_id");
   assert(uiCode <= 15);
   pcPPS->setSPSId (uiCode);
-  
+
   READ_FLAG( uiCode, "dependent_slice_segments_enabled_flag"    );    pcPPS->setDependentSliceSegmentsEnabledFlag   ( uiCode == 1 );
+
   READ_FLAG( uiCode, "output_flag_present_flag" );                    pcPPS->setOutputFlagPresentFlag( uiCode==1 );
 
   READ_CODE(3, uiCode, "num_extra_slice_header_bits");                pcPPS->setNumExtraSliceHeaderBits(uiCode);
+
   READ_FLAG ( uiCode, "sign_data_hiding_flag" ); pcPPS->setSignHideFlag( uiCode );
 
@@ -231,13 +215,13 @@
   assert(uiCode <= 14);
   pcPPS->setNumRefIdxL0DefaultActive(uiCode+1);
-  
+
   READ_UVLC(uiCode, "num_ref_idx_l1_default_active_minus1");
   assert(uiCode <= 14);
   pcPPS->setNumRefIdxL1DefaultActive(uiCode+1);
-  
+
   READ_SVLC(iCode, "init_qp_minus26" );                            pcPPS->setPicInitQPMinus26(iCode);
   READ_FLAG( uiCode, "constrained_intra_pred_flag" );              pcPPS->setConstrainedIntraPred( uiCode ? true : false );
-  READ_FLAG( uiCode, "transform_skip_enabled_flag" );               
-  pcPPS->setUseTransformSkip ( uiCode ? true : false ); 
+  READ_FLAG( uiCode, "transform_skip_enabled_flag" );
+  pcPPS->setUseTransformSkip ( uiCode ? true : false );
 
   READ_FLAG( uiCode, "cu_qp_delta_enabled_flag" );            pcPPS->setUseDQP( uiCode ? true : false );
@@ -252,12 +236,14 @@
   }
   READ_SVLC( iCode, "pps_cb_qp_offset");
-  pcPPS->setChromaCbQpOffset(iCode);
-  assert( pcPPS->getChromaCbQpOffset() >= -12 );
-  assert( pcPPS->getChromaCbQpOffset() <=  12 );
+  pcPPS->setQpOffset(COMPONENT_Cb, iCode);
+  assert( pcPPS->getQpOffset(COMPONENT_Cb) >= -12 );
+  assert( pcPPS->getQpOffset(COMPONENT_Cb) <=  12 );
 
   READ_SVLC( iCode, "pps_cr_qp_offset");
-  pcPPS->setChromaCrQpOffset(iCode);
-  assert( pcPPS->getChromaCrQpOffset() >= -12 );
-  assert( pcPPS->getChromaCrQpOffset() <=  12 );
+  pcPPS->setQpOffset(COMPONENT_Cr, iCode);
+  assert( pcPPS->getQpOffset(COMPONENT_Cr) >= -12 );
+  assert( pcPPS->getQpOffset(COMPONENT_Cr) <=  12 );
+
+  assert(MAX_NUM_COMPONENT<=3);
 
   READ_FLAG( uiCode, "pps_slice_chroma_qp_offsets_present_flag" );
@@ -273,5 +259,5 @@
   READ_FLAG( uiCode, "tiles_enabled_flag"               );    pcPPS->setTilesEnabledFlag            ( uiCode == 1 );
   READ_FLAG( uiCode, "entropy_coding_sync_enabled_flag" );    pcPPS->setEntropyCodingSyncEnabledFlag( uiCode == 1 );
-  
+
   if( pcPPS->getTilesEnabledFlag() )
   {
@@ -280,29 +266,38 @@
     READ_FLAG ( uiCode, "uniform_spacing_flag" );                   pcPPS->setTileUniformSpacingFlag( uiCode == 1 );
 
-    if( !pcPPS->getTileUniformSpacingFlag())
-    {
-      std::vector<Int> columnWidth(pcPPS->getNumTileColumnsMinus1());
-      for(UInt i=0; i<pcPPS->getNumTileColumnsMinus1(); i++)
-      { 
-        READ_UVLC( uiCode, "column_width_minus1" );  
-        columnWidth[i] = uiCode+1;
-      }
-      pcPPS->setTileColumnWidth(columnWidth);
-
-      std::vector<Int> rowHeight (pcPPS->getTileNumRowsMinus1());
-      for(UInt i=0; i<pcPPS->getTileNumRowsMinus1(); i++)
-      {
-        READ_UVLC( uiCode, "row_height_minus1" );
-        rowHeight[i] = uiCode + 1;
-      }
-      pcPPS->setTileRowHeight(rowHeight);
-    }
-
-    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getTileNumRowsMinus1() !=0)
+    const UInt tileColumnsMinus1 = pcPPS->getNumTileColumnsMinus1();
+    const UInt tileRowsMinus1    = pcPPS->getNumTileRowsMinus1();
+ 
+    if ( !pcPPS->getTileUniformSpacingFlag())
+    {
+      if (tileColumnsMinus1 > 0)
+      {
+        std::vector<Int> columnWidth(tileColumnsMinus1);
+        for(UInt i = 0; i < tileColumnsMinus1; i++)
+        { 
+          READ_UVLC( uiCode, "column_width_minus1" );  
+          columnWidth[i] = uiCode+1;
+        }
+        pcPPS->setTileColumnWidth(columnWidth);
+      }
+
+      if (tileRowsMinus1 > 0)
+      {
+        std::vector<Int> rowHeight (tileRowsMinus1);
+        for(UInt i = 0; i < tileRowsMinus1; i++)
+        {
+          READ_UVLC( uiCode, "row_height_minus1" );
+          rowHeight[i] = uiCode + 1;
+        }
+        pcPPS->setTileRowHeight(rowHeight);
+      }
+    }
+
+    if ((tileColumnsMinus1 + tileRowsMinus1) != 0)
     {
       READ_FLAG ( uiCode, "loop_filter_across_tiles_enabled_flag" );   pcPPS->setLoopFilterAcrossTilesEnabledFlag( uiCode ? true : false );
     }
   }
-  READ_FLAG( uiCode, "loop_filter_across_slices_enabled_flag" );       pcPPS->setLoopFilterAcrossSlicesEnabledFlag( uiCode ? true : false );
+  READ_FLAG( uiCode, "pps_loop_filter_across_slices_enabled_flag" );   pcPPS->setLoopFilterAcrossSlicesEnabledFlag( uiCode ? true : false );
   READ_FLAG( uiCode, "deblocking_filter_control_present_flag" );       pcPPS->setDeblockingFilterControlPresentFlag( uiCode ? true : false );
   if(pcPPS->getDeblockingFilterControlPresentFlag())
@@ -319,6 +314,7 @@
   if(pcPPS->getScalingListPresentFlag ())
   {
-    parseScalingList( pcPPS->getScalingList() );
-  }
+    parseScalingList( &(pcPPS->getScalingList()) );
+  }
+
   READ_FLAG( uiCode, "lists_modification_present_flag");
   pcPPS->setListsModificationPresentFlag(uiCode);
@@ -329,62 +325,180 @@
   READ_FLAG( uiCode, "slice_segment_header_extension_present_flag");
   pcPPS->setSliceHeaderExtensionPresentFlag(uiCode);
-  
-#if H_MV
+
   READ_FLAG( uiCode, "pps_extension_present_flag");
-#else
-  READ_FLAG( uiCode, "pps_extension_flag");
-#endif
   if (uiCode)
   {
-
-#if H_MV
+#if NH_MV
     READ_FLAG( uiCode, "pps_range_extensions_flag" ); pcPPS->setPpsRangeExtensionsFlag( uiCode == 1 );
     READ_FLAG( uiCode, "pps_multilayer_extension_flag" ); pcPPS->setPpsMultilayerExtensionFlag( uiCode == 1 );
-#if !H_3D
-    READ_CODE( 6, uiCode, "pps_extension_6bits" ); pcPPS->setPpsExtension6bits( uiCode );
-#else
     READ_FLAG( uiCode, "pps_3d_extension_flag" ); pcPPS->setPps3dExtensionFlag( uiCode == 1 );
     READ_CODE( 5, uiCode, "pps_extension_5bits" ); pcPPS->setPpsExtension5bits( uiCode );
-#endif
     if ( pcPPS->getPpsRangeExtensionsFlag() )
     { 
-      assert(0); 
-    }
+      TComPPSRExt &ppsRangeExtension = pcPPS->getPpsRangeExtension();      
+
+      if (pcPPS->getUseTransformSkip())
+      {
+        READ_UVLC( uiCode, "log2_max_transform_skip_block_size_minus2");
+        ppsRangeExtension.setLog2MaxTransformSkipBlockSize(uiCode+2);
+      }
+
+      READ_FLAG( uiCode, "cross_component_prediction_enabled_flag");
+      ppsRangeExtension.setCrossComponentPredictionEnabledFlag(uiCode != 0);
+
+      READ_FLAG( uiCode, "chroma_qp_offset_list_enabled_flag");
+      if (uiCode == 0)
+      {
+        ppsRangeExtension.clearChromaQpOffsetList();
+        ppsRangeExtension.setDiffCuChromaQpOffsetDepth(0);
+      }
+      else
+      {
+        READ_UVLC(uiCode, "diff_cu_chroma_qp_offset_depth"); ppsRangeExtension.setDiffCuChromaQpOffsetDepth(uiCode);
+        UInt tableSizeMinus1 = 0;
+        READ_UVLC(tableSizeMinus1, "chroma_qp_offset_list_len_minus1");
+        assert(tableSizeMinus1 < MAX_QP_OFFSET_LIST_SIZE);
+
+        for (Int cuChromaQpOffsetIdx = 0; cuChromaQpOffsetIdx <= (tableSizeMinus1); cuChromaQpOffsetIdx++)
+        {
+          Int cbOffset;
+          Int crOffset;
+          READ_SVLC(cbOffset, "cb_qp_offset_list[i]");
+          assert(cbOffset >= -12 && cbOffset <= 12);
+          READ_SVLC(crOffset, "cr_qp_offset_list[i]");
+          assert(crOffset >= -12 && crOffset <= 12);
+          // table uses +1 for index (see comment inside the function)
+          ppsRangeExtension.setChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1, cbOffset, crOffset);
+        }
+        assert(ppsRangeExtension.getChromaQpOffsetListLen() == tableSizeMinus1 + 1);
+      }
+
+      READ_UVLC( uiCode, "log2_sao_offset_scale_luma");
+      ppsRangeExtension.setLog2SaoOffsetScale(CHANNEL_TYPE_LUMA, uiCode);
+      READ_UVLC( uiCode, "log2_sao_offset_scale_chroma");
+      ppsRangeExtension.setLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA, uiCode);    }
 
     if ( pcPPS->getPpsMultilayerExtensionFlag() )
     { 
-      parsePPSMultilayerExtension( pcPPS ); 
-    }
-#if !H_3D
-    if ( pcPPS->getPpsExtension6bits() )
-    {
-#else
+      parsePpsMultilayerExtension( pcPPS ); 
+    }
+
     if ( pcPPS->getPps3dExtensionFlag() )
     { 
-      parsePPSExtension( pcPPS, pcVPS );
-    }
+#if NH_3D
+      parsePps3dExtension( pcPPS );
+#endif
+    }
+#if NH_3D
     if ( pcPPS->getPpsExtension5bits() )
-    {
-#endif
-
-#endif
-
+#else
+    if ( pcPPS->getPpsExtension5bits() || pcPPS->getPps3dExtensionFlag() )
+#endif
+    {
       while ( xMoreRbspData() )
       {
         READ_FLAG( uiCode, "pps_extension_data_flag");
       }
-#if H_MV
-    }
-#endif
-  }
-}
-
-
+    }
+
+#else
+#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
+    static const char *syntaxStrings[]={ "pps_range_extension_flag",
+                                         "pps_multilayer_extension_flag",
+                                         "pps_extension_6bits[0]",
+                                         "pps_extension_6bits[1]",
+                                         "pps_extension_6bits[2]",
+                                         "pps_extension_6bits[3]",
+                                         "pps_extension_6bits[4]",
+                                         "pps_extension_6bits[5]" };
+#endif
+
+    Bool pps_extension_flags[NUM_PPS_EXTENSION_FLAGS];
+    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
+    {
+      READ_FLAG( uiCode, syntaxStrings[i] );
+      pps_extension_flags[i] = uiCode!=0;
+    }
+
+    Bool bSkipTrailingExtensionBits=false;
+    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
+    {
+      if (pps_extension_flags[i])
+      {
+        switch (PPSExtensionFlagIndex(i))
+        {
+          case PPS_EXT__REXT:
+            {
+              TComPPSRExt &ppsRangeExtension = pcPPS->getPpsRangeExtension();
+            assert(!bSkipTrailingExtensionBits);
+
+            if (pcPPS->getUseTransformSkip())
+            {
+              READ_UVLC( uiCode, "log2_max_transform_skip_block_size_minus2");
+                ppsRangeExtension.setLog2MaxTransformSkipBlockSize(uiCode+2);
+            }
+
+            READ_FLAG( uiCode, "cross_component_prediction_enabled_flag");
+              ppsRangeExtension.setCrossComponentPredictionEnabledFlag(uiCode != 0);
+
+            READ_FLAG( uiCode, "chroma_qp_offset_list_enabled_flag");
+            if (uiCode == 0)
+            {
+                ppsRangeExtension.clearChromaQpOffsetList();
+                ppsRangeExtension.setDiffCuChromaQpOffsetDepth(0);
+            }
+            else
+            {
+                READ_UVLC(uiCode, "diff_cu_chroma_qp_offset_depth"); ppsRangeExtension.setDiffCuChromaQpOffsetDepth(uiCode);
+              UInt tableSizeMinus1 = 0;
+              READ_UVLC(tableSizeMinus1, "chroma_qp_offset_list_len_minus1");
+              assert(tableSizeMinus1 < MAX_QP_OFFSET_LIST_SIZE);
+
+              for (Int cuChromaQpOffsetIdx = 0; cuChromaQpOffsetIdx <= (tableSizeMinus1); cuChromaQpOffsetIdx++)
+              {
+                Int cbOffset;
+                Int crOffset;
+                READ_SVLC(cbOffset, "cb_qp_offset_list[i]");
+                assert(cbOffset >= -12 && cbOffset <= 12); 
+                READ_SVLC(crOffset, "cr_qp_offset_list[i]");
+                assert(crOffset >= -12 && crOffset <= 12);
+                // table uses +1 for index (see comment inside the function)
+                  ppsRangeExtension.setChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1, cbOffset, crOffset);
+              }
+                assert(ppsRangeExtension.getChromaQpOffsetListLen() == tableSizeMinus1 + 1);
+            }
+
+            READ_UVLC( uiCode, "log2_sao_offset_scale_luma");
+              ppsRangeExtension.setLog2SaoOffsetScale(CHANNEL_TYPE_LUMA, uiCode);
+            READ_UVLC( uiCode, "log2_sao_offset_scale_chroma");
+              ppsRangeExtension.setLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA, uiCode);
+            }
+            break;
+          default:
+            bSkipTrailingExtensionBits=true;
+            break;
+        }
+      }
+    }
+    if (bSkipTrailingExtensionBits)
+    {
+      while ( xMoreRbspData() )
+      {
+        READ_FLAG( uiCode, "pps_extension_data_flag");
+      }
+    }
+#endif
+  }
+  xReadRbspTrailingBits();
+}
+
+#if NH_3D
+Void TDecCavlc::parsePps3dExtension( TComPPS* pcPPS )
+{
 #if H_3D
-Void TDecCavlc::parsePPSExtension( TComPPS* pcPPS, TComVPS* pcVPS )
-{
-  //Ed.(GT): pcVPS should not be used here. Needs to be fixed. 
   UInt uiCode = 0; 
+  //
   TComDLT* pcDLT = new TComDLT;
+  //Ed.(GT): PPSs are copied in HM16.4. This would cause that the only the DLT pointer is copied. Therefore, a deep copy of the DLT needs to be implemented. Another option would be to use a vectors for the DLT arrays in TComDLT.
 
   READ_FLAG(uiCode, "dlt_present_flag");
@@ -399,4 +513,5 @@
     pcDLT->setDepthViewBitDepth( (uiCode+8) );
 
+    //Ed.(GT): Please remove parsing dependency from VPS here !
     for( Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
     {
@@ -524,6 +639,8 @@
 
   pcPPS->setDLT( pcDLT );
-}
-#endif
+#endif
+}
+#endif
+
 
 Void  TDecCavlc::parseVUI(TComVUI* pcVUI, TComSPS *pcSPS)
@@ -552,5 +669,5 @@
 
   READ_FLAG(     uiCode, "video_signal_type_present_flag");           pcVUI->setVideoSignalTypePresentFlag(uiCode);
-#if H_MV
+#if NH_MV
   assert( pcSPS->getLayerId() == 0 || !pcVUI->getVideoSignalTypePresentFlag() ); 
 #endif
@@ -564,5 +681,5 @@
       READ_CODE(8, uiCode, "colour_primaries");                       pcVUI->setColourPrimaries(uiCode);
       READ_CODE(8, uiCode, "transfer_characteristics");               pcVUI->setTransferCharacteristics(uiCode);
-      READ_CODE(8, uiCode, "matrix_coefficients");                    pcVUI->setMatrixCoefficients(uiCode);
+      READ_CODE(8, uiCode, "matrix_coeffs");                          pcVUI->setMatrixCoefficients(uiCode);
     }
   }
@@ -585,5 +702,5 @@
   {
     Window &defDisp = pcVUI->getDefaultDisplayWindow();
-#if H_MV
+#if NH_MV
     defDisp.setScaledFlag( false ); 
     READ_UVLC(   uiCode, "def_disp_win_left_offset" );                defDisp.setWindowLeftOffset  ( uiCode );
@@ -598,4 +715,5 @@
 #endif
   }
+
   TimingInfo *timingInfo = pcVUI->getTimingInfo();
   READ_FLAG(       uiCode, "vui_timing_info_present_flag");         timingInfo->setTimingInfoPresentFlag      (uiCode ? true : false);
@@ -609,10 +727,12 @@
       READ_UVLC(   uiCode, "vui_num_ticks_poc_diff_one_minus1");    timingInfo->setNumTicksPocDiffOneMinus1   (uiCode);
     }
-  READ_FLAG(     uiCode, "hrd_parameters_present_flag");              pcVUI->setHrdParametersPresentFlag(uiCode);
-  if( pcVUI->getHrdParametersPresentFlag() )
-  {
-    parseHrdParameters( pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
-  }
-  }
+
+    READ_FLAG(     uiCode, "vui_hrd_parameters_present_flag");        pcVUI->setHrdParametersPresentFlag(uiCode);
+    if( pcVUI->getHrdParametersPresentFlag() )
+    {
+      parseHrdParameters( pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
+    }
+  }
+
   READ_FLAG(     uiCode, "bitstream_restriction_flag");               pcVUI->setBitstreamRestrictionFlag(uiCode);
   if (pcVUI->getBitstreamRestrictionFlag())
@@ -621,8 +741,8 @@
     READ_FLAG(   uiCode, "motion_vectors_over_pic_boundaries_flag");  pcVUI->setMotionVectorsOverPicBoundariesFlag(uiCode);
     READ_FLAG(   uiCode, "restricted_ref_pic_lists_flag");            pcVUI->setRestrictedRefPicListsFlag(uiCode);
-    READ_UVLC( uiCode, "min_spatial_segmentation_idc");            pcVUI->setMinSpatialSegmentationIdc(uiCode);
+    READ_UVLC(   uiCode, "min_spatial_segmentation_idc");             pcVUI->setMinSpatialSegmentationIdc(uiCode);
     assert(uiCode < 4096);
     READ_UVLC(   uiCode, "max_bytes_per_pic_denom" );                 pcVUI->setMaxBytesPerPicDenom(uiCode);
-    READ_UVLC(   uiCode, "max_bits_per_mincu_denom" );                pcVUI->setMaxBitsPerMinCuDenom(uiCode);
+    READ_UVLC(   uiCode, "max_bits_per_min_cu_denom" );               pcVUI->setMaxBitsPerMinCuDenom(uiCode);
     READ_UVLC(   uiCode, "log2_max_mv_length_horizontal" );           pcVUI->setLog2MaxMvLengthHorizontal(uiCode);
     READ_UVLC(   uiCode, "log2_max_mv_length_vertical" );             pcVUI->setLog2MaxMvLengthVertical(uiCode);
@@ -639,9 +759,9 @@
     if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
     {
-      READ_FLAG( uiCode, "sub_pic_cpb_params_present_flag" );         hrd->setSubPicCpbParamsPresentFlag( uiCode == 1 ? true : false );
+      READ_FLAG( uiCode, "sub_pic_hrd_params_present_flag" );         hrd->setSubPicCpbParamsPresentFlag( uiCode == 1 ? true : false );
       if( hrd->getSubPicCpbParamsPresentFlag() )
       {
         READ_CODE( 8, uiCode, "tick_divisor_minus2" );                hrd->setTickDivisorMinus2( uiCode );
-        READ_CODE( 5, uiCode, "du_cpb_removal_delay_length_minus1" ); hrd->setDuCpbRemovalDelayLengthMinus1( uiCode );
+        READ_CODE( 5, uiCode, "du_cpb_removal_delay_increment_length_minus1" ); hrd->setDuCpbRemovalDelayLengthMinus1( uiCode );
         READ_FLAG( uiCode, "sub_pic_cpb_params_in_pic_timing_sei_flag" ); hrd->setSubPicCpbParamsInPicTimingSEIFlag( uiCode == 1 ? true : false );
         READ_CODE( 5, uiCode, "dpb_output_delay_du_length_minus1"  ); hrd->setDpbOutputDelayDuLengthMinus1( uiCode );
@@ -670,6 +790,8 @@
       hrd->setFixedPicRateWithinCvsFlag( i, true );
     }
+
     hrd->setLowDelayHrdFlag( i, 0 ); // Infered to be 0 when not present
     hrd->setCpbCntMinus1   ( i, 0 ); // Infered to be 0 when not present
+
     if( hrd->getFixedPicRateWithinCvsFlag( i ) )
     {
@@ -677,11 +799,12 @@
     }
     else
-    {      
+    {
       READ_FLAG( uiCode, "low_delay_hrd_flag" );                      hrd->setLowDelayHrdFlag( i, uiCode == 1 ? true : false  );
     }
     if (!hrd->getLowDelayHrdFlag( i ))
     {
-      READ_UVLC( uiCode, "cpb_cnt_minus1" );                          hrd->setCpbCntMinus1( i, uiCode );      
-    }
+      READ_UVLC( uiCode, "cpb_cnt_minus1" );                          hrd->setCpbCntMinus1( i, uiCode );
+    }
+
     for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
     {
@@ -707,6 +830,10 @@
 Void TDecCavlc::parseSPS(TComSPS* pcSPS)
 {
-#if ENC_DEC_TRACE  
-  xTraceSPSHeader (pcSPS);
+#if ENC_DEC_TRACE
+#if H_MV_ENC_DEC_TRAC
+  tracePSHeader( "SPS", pcSPS->getLayerId() ); 
+#else
+  xTraceSPSHeader ();
+#endif
 #endif
 
@@ -714,11 +841,11 @@
   READ_CODE( 4,  uiCode, "sps_video_parameter_set_id");          pcSPS->setVPSId        ( uiCode );
 
-#if H_MV
+#if NH_MV
   if ( pcSPS->getLayerId() == 0 )
   {
 #endif
-    READ_CODE( 3,  uiCode, "sps_max_sub_layers_minus1" );          pcSPS->setMaxTLayers   ( uiCode+1 );
-    assert(uiCode <= 6);
-#if H_MV
+  READ_CODE( 3,  uiCode, "sps_max_sub_layers_minus1" );          pcSPS->setMaxTLayers   ( uiCode+1 );
+  assert(uiCode <= 6);
+#if NH_MV
   }
   else
@@ -731,13 +858,13 @@
 #endif
 
-    READ_FLAG( uiCode, "sps_temporal_id_nesting_flag" );               pcSPS->setTemporalIdNestingFlag ( uiCode > 0 ? true : false );
-    if ( pcSPS->getMaxTLayers() == 1 )
-    {
-      // sps_temporal_id_nesting_flag must be 1 when sps_max_sub_layers_minus1 is 0
-      assert( uiCode == 1 );
-    }
-
-    parsePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
-#if H_MV
+  READ_FLAG( uiCode, "sps_temporal_id_nesting_flag" );           pcSPS->setTemporalIdNestingFlag ( uiCode > 0 ? true : false );
+  if ( pcSPS->getMaxTLayers() == 1 )
+  {
+    // sps_temporal_id_nesting_flag must be 1 when sps_max_sub_layers_minus1 is 0
+    assert( uiCode == 1 );
+  }
+
+  parsePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
+#if NH_MV
     pcSPS->getPTL()->inferGeneralValues ( true, 0, NULL ); 
     pcSPS->getPTL()->inferSubLayerValues( pcSPS->getMaxTLayers() - 1, 0, NULL );
@@ -746,5 +873,5 @@
   READ_UVLC(     uiCode, "sps_seq_parameter_set_id" );           pcSPS->setSPSId( uiCode );
   assert(uiCode <= 15);
-#if H_MV
+#if NH_MV
   if ( pcSPS->getMultiLayerExtSpsFlag() )
   {
@@ -758,22 +885,19 @@
   {
 #endif
-    READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( uiCode );
-    assert(uiCode <= 3);
-    // in the first version we only support chroma_format_idc equal to 1 (4:2:0), so separate_colour_plane_flag cannot appear in the bitstream
-#if !H_3D_DISABLE_CHROMA
-    assert (uiCode == 1);
-#endif
-    if( uiCode == 3 )
-    {
-      READ_FLAG(     uiCode, "separate_colour_plane_flag");        assert(uiCode == 0);
-    }
-
-    READ_UVLC (    uiCode, "pic_width_in_luma_samples" );          pcSPS->setPicWidthInLumaSamples ( uiCode    );
-    READ_UVLC (    uiCode, "pic_height_in_luma_samples" );         pcSPS->setPicHeightInLumaSamples( uiCode    );
+
+  READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( ChromaFormat(uiCode) );
+  assert(uiCode <= 3);
+  if( pcSPS->getChromaFormatIdc() == CHROMA_444 )
+  {
+    READ_FLAG(     uiCode, "separate_colour_plane_flag");        assert(uiCode == 0);
+  }
+
+  READ_UVLC (    uiCode, "pic_width_in_luma_samples" );          pcSPS->setPicWidthInLumaSamples ( uiCode    );
+  READ_UVLC (    uiCode, "pic_height_in_luma_samples" );         pcSPS->setPicHeightInLumaSamples( uiCode    );
   READ_FLAG(     uiCode, "conformance_window_flag");
   if (uiCode != 0)
   {
     Window &conf = pcSPS->getConformanceWindow();
-#if H_MV
+#if NH_MV
     // Needs to be scaled later, when ChromaFormatIdc is known. 
     conf.setScaledFlag( false ); 
@@ -791,18 +915,43 @@
   }
 
-#if H_MV
+#if NH_MV
   if ( !pcSPS->getMultiLayerExtSpsFlag() )
   { 
 #endif
-    READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
-    assert(uiCode <= 6);
-    pcSPS->setBitDepthY( uiCode + 8 );
-    pcSPS->setQpBDOffsetY( (Int) (6*uiCode) );
-
-    READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
-    assert(uiCode <= 6);
-    pcSPS->setBitDepthC( uiCode + 8 );
-    pcSPS->setQpBDOffsetC( (Int) (6*uiCode) );
-#if H_MV
+
+  READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+#if O0043_BEST_EFFORT_DECODING
+  pcSPS->setStreamBitDepth(CHANNEL_TYPE_LUMA, 8 + uiCode);
+  const UInt forceDecodeBitDepth = pcSPS->getForceDecodeBitDepth();
+  if (forceDecodeBitDepth != 0)
+  {
+    uiCode = forceDecodeBitDepth - 8;
+  }
+#endif
+  assert(uiCode <= 8);
+  pcSPS->setBitDepth(CHANNEL_TYPE_LUMA, 8 + uiCode);
+
+#if O0043_BEST_EFFORT_DECODING
+  pcSPS->setQpBDOffset(CHANNEL_TYPE_LUMA, (Int) (6*(pcSPS->getStreamBitDepth(CHANNEL_TYPE_LUMA)-8)) );
+#else
+  pcSPS->setQpBDOffset(CHANNEL_TYPE_LUMA, (Int) (6*uiCode) );
+#endif
+
+  READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
+#if O0043_BEST_EFFORT_DECODING
+  pcSPS->setStreamBitDepth(CHANNEL_TYPE_CHROMA, 8 + uiCode);
+  if (forceDecodeBitDepth != 0)
+  {
+    uiCode = forceDecodeBitDepth - 8;
+  }
+#endif
+  assert(uiCode <= 8);
+  pcSPS->setBitDepth(CHANNEL_TYPE_CHROMA, 8 + uiCode);
+#if O0043_BEST_EFFORT_DECODING
+  pcSPS->setQpBDOffset(CHANNEL_TYPE_CHROMA,  (Int) (6*(pcSPS->getStreamBitDepth(CHANNEL_TYPE_CHROMA)-8)) );
+#else
+  pcSPS->setQpBDOffset(CHANNEL_TYPE_CHROMA,  (Int) (6*uiCode) );
+#endif
+#if NH_MV
   }
 #endif
@@ -811,52 +960,52 @@
   assert(uiCode <= 12);
 
-#if H_MV
+#if NH_MV
   if ( !pcSPS->getMultiLayerExtSpsFlag()) 
   {  
 #endif
-    UInt subLayerOrderingInfoPresentFlag;
-    READ_FLAG(subLayerOrderingInfoPresentFlag, "sps_sub_layer_ordering_info_present_flag");
-
-    for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
-    {
-      READ_UVLC ( uiCode, "sps_max_dec_pic_buffering_minus1[i]");
-      pcSPS->setMaxDecPicBuffering( uiCode + 1, i);
-      READ_UVLC ( uiCode, "sps_num_reorder_pics[i]" );
-      pcSPS->setNumReorderPics(uiCode, i);
-      READ_UVLC ( uiCode, "sps_max_latency_increase_plus1[i]");
-      pcSPS->setMaxLatencyIncrease( uiCode, i );
-
-      if (!subLayerOrderingInfoPresentFlag)
-      {
-        for (i++; i <= pcSPS->getMaxTLayers()-1; i++)
-        {
-          pcSPS->setMaxDecPicBuffering(pcSPS->getMaxDecPicBuffering(0), i);
-          pcSPS->setNumReorderPics(pcSPS->getNumReorderPics(0), i);
-          pcSPS->setMaxLatencyIncrease(pcSPS->getMaxLatencyIncrease(0), i);
-        }
-        break;
-      }
-    }
-#if H_MV
-  }
-#endif
-
-  READ_UVLC( uiCode, "log2_min_coding_block_size_minus3" );
+  UInt subLayerOrderingInfoPresentFlag;
+  READ_FLAG(subLayerOrderingInfoPresentFlag, "sps_sub_layer_ordering_info_present_flag");
+
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+    READ_UVLC ( uiCode, "sps_max_dec_pic_buffering_minus1[i]");
+    pcSPS->setMaxDecPicBuffering( uiCode + 1, i);
+    READ_UVLC ( uiCode, "sps_max_num_reorder_pics[i]" );
+    pcSPS->setNumReorderPics(uiCode, i);
+    READ_UVLC ( uiCode, "sps_max_latency_increase_plus1[i]");
+    pcSPS->setMaxLatencyIncrease( uiCode, i );
+
+    if (!subLayerOrderingInfoPresentFlag)
+    {
+      for (i++; i <= pcSPS->getMaxTLayers()-1; i++)
+      {
+        pcSPS->setMaxDecPicBuffering(pcSPS->getMaxDecPicBuffering(0), i);
+        pcSPS->setNumReorderPics(pcSPS->getNumReorderPics(0), i);
+        pcSPS->setMaxLatencyIncrease(pcSPS->getMaxLatencyIncrease(0), i);
+      }
+      break;
+    }
+  }
+#if NH_MV
+  }
+#endif
+
+  READ_UVLC( uiCode, "log2_min_luma_coding_block_size_minus3" );
   Int log2MinCUSize = uiCode + 3;
   pcSPS->setLog2MinCodingBlockSize(log2MinCUSize);
-  READ_UVLC( uiCode, "log2_diff_max_min_coding_block_size" );
+  READ_UVLC( uiCode, "log2_diff_max_min_luma_coding_block_size" );
   pcSPS->setLog2DiffMaxMinCodingBlockSize(uiCode);
-
+  
   if (pcSPS->getPTL()->getGeneralPTL()->getLevelIdc() >= Level::LEVEL5)
   {
     assert(log2MinCUSize + pcSPS->getLog2DiffMaxMinCodingBlockSize() >= 5);
   }
-
+  
   Int maxCUDepthDelta = uiCode;
-  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + maxCUDepthDelta) ); 
+  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + maxCUDepthDelta) );
   pcSPS->setMaxCUHeight ( 1<<(log2MinCUSize + maxCUDepthDelta) );
-  READ_UVLC( uiCode, "log2_min_transform_block_size_minus2" );   pcSPS->setQuadtreeTULog2MinSize( uiCode + 2 );
-
-  READ_UVLC( uiCode, "log2_diff_max_min_transform_block_size" ); pcSPS->setQuadtreeTULog2MaxSize( uiCode + pcSPS->getQuadtreeTULog2MinSize() );
+  READ_UVLC( uiCode, "log2_min_luma_transform_block_size_minus2" );   pcSPS->setQuadtreeTULog2MinSize( uiCode + 2 );
+
+  READ_UVLC( uiCode, "log2_diff_max_min_luma_transform_block_size" ); pcSPS->setQuadtreeTULog2MaxSize( uiCode + pcSPS->getQuadtreeTULog2MinSize() );
   pcSPS->setMaxTrSize( 1<<(uiCode + pcSPS->getQuadtreeTULog2MinSize()) );
 
@@ -865,10 +1014,10 @@
 
   Int addCuDepth = max (0, log2MinCUSize - (Int)pcSPS->getQuadtreeTULog2MinSize() );
-  pcSPS->setMaxCUDepth( maxCUDepthDelta + addCuDepth ); 
+  pcSPS->setMaxTotalCUDepth( maxCUDepthDelta + addCuDepth  + getMaxCUDepthOffset(pcSPS->getChromaFormatIdc(), pcSPS->getQuadtreeTULog2MinSize()) );
 
   READ_FLAG( uiCode, "scaling_list_enabled_flag" );                 pcSPS->setScalingListFlag ( uiCode );
   if(pcSPS->getScalingListFlag())
   {
-#if H_MV
+#if NH_MV
     if ( pcSPS->getMultiLayerExtSpsFlag() )
     {    
@@ -883,10 +1032,10 @@
     {    
 #endif
-      READ_FLAG( uiCode, "sps_scaling_list_data_present_flag" );                 pcSPS->setScalingListPresentFlag ( uiCode );
-      if(pcSPS->getScalingListPresentFlag ())
-      {
-        parseScalingList( pcSPS->getScalingList() );
-      }
-#if H_MV
+    READ_FLAG( uiCode, "sps_scaling_list_data_present_flag" );                 pcSPS->setScalingListPresentFlag ( uiCode );
+    if(pcSPS->getScalingListPresentFlag ())
+    {
+      parseScalingList( &(pcSPS->getScalingList()) );
+    }
+#if NH_MV
     }
 #endif
@@ -898,6 +1047,6 @@
   if( pcSPS->getUsePCM() )
   {
-    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_luma_minus1" );          pcSPS->setPCMBitDepthLuma   ( 1 + uiCode );
-    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_chroma_minus1" );        pcSPS->setPCMBitDepthChroma ( 1 + uiCode );
+    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_luma_minus1" );          pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_LUMA, 1 + uiCode );
+    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_chroma_minus1" );        pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_CHROMA, 1 + uiCode );
     READ_UVLC( uiCode, "log2_min_pcm_luma_coding_block_size_minus3" );   pcSPS->setPCMLog2MinSize (uiCode+3);
     READ_UVLC( uiCode, "log2_diff_max_min_pcm_luma_coding_block_size" ); pcSPS->setPCMLog2MaxSize ( uiCode+pcSPS->getPCMLog2MinSize() );
@@ -918,7 +1067,7 @@
   }
   READ_FLAG( uiCode, "long_term_ref_pics_present_flag" );          pcSPS->setLongTermRefsPresent(uiCode);
-  if (pcSPS->getLongTermRefsPresent()) 
-  {
-    READ_UVLC( uiCode, "num_long_term_ref_pic_sps" );
+  if (pcSPS->getLongTermRefsPresent())
+  {
+    READ_UVLC( uiCode, "num_long_term_ref_pics_sps" );
     pcSPS->setNumLongTermRefPicSPS(uiCode);
     for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
@@ -941,96 +1090,154 @@
   }
 
-
-#if H_MV
   READ_FLAG( uiCode, "sps_extension_present_flag");
+#if NH_MV
   pcSPS->setSpsExtensionPresentFlag( uiCode ); 
   if (pcSPS->getSpsExtensionPresentFlag( ) )
+  {  
+    READ_FLAG( uiCode, "sps_range_extensions_flag" );     pcSPS->setSpsRangeExtensionsFlag( uiCode == 1 );
+    READ_FLAG( uiCode, "sps_multilayer_extension_flag" ); pcSPS->setSpsMultilayerExtensionFlag( uiCode == 1 );
+    READ_FLAG( uiCode   , "sps_3d_extension_flag" );      pcSPS->setSps3dExtensionFlag( uiCode == 1 );
+    READ_CODE( 5, uiCode, "sps_extension_5bits" )  ;      pcSPS->setSpsExtension5bits( uiCode );
+
+    if ( pcSPS->getSpsRangeExtensionsFlag() )
+    {
+              TComSPSRExt &spsRangeExtension = pcSPS->getSpsRangeExtension();
+              READ_FLAG( uiCode, "transform_skip_rotation_enabled_flag");     spsRangeExtension.setTransformSkipRotationEnabledFlag(uiCode != 0);
+              READ_FLAG( uiCode, "transform_skip_context_enabled_flag");      spsRangeExtension.setTransformSkipContextEnabledFlag (uiCode != 0);
+              READ_FLAG( uiCode, "implicit_rdpcm_enabled_flag");              spsRangeExtension.setRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT, (uiCode != 0));
+              READ_FLAG( uiCode, "explicit_rdpcm_enabled_flag");              spsRangeExtension.setRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT, (uiCode != 0));
+              READ_FLAG( uiCode, "extended_precision_processing_flag");       spsRangeExtension.setExtendedPrecisionProcessingFlag (uiCode != 0);
+              READ_FLAG( uiCode, "intra_smoothing_disabled_flag");            spsRangeExtension.setIntraSmoothingDisabledFlag      (uiCode != 0);
+              READ_FLAG( uiCode, "high_precision_offsets_enabled_flag");      spsRangeExtension.setHighPrecisionOffsetsEnabledFlag (uiCode != 0);
+              READ_FLAG( uiCode, "persistent_rice_adaptation_enabled_flag");  spsRangeExtension.setPersistentRiceAdaptationEnabledFlag (uiCode != 0);
+              READ_FLAG( uiCode, "cabac_bypass_alignment_enabled_flag");      spsRangeExtension.setCabacBypassAlignmentEnabledFlag  (uiCode != 0);
+    }
+
+    if ( pcSPS->getSpsMultilayerExtensionFlag() )
+    {
+      parseSpsMultilayerExtension( pcSPS ); 
+    }
+
+    if ( pcSPS->getSps3dExtensionFlag() )
+    {
+#if NH_3D
+      parseSps3dExtension( pcSPS ); 
+#endif
+    }
+
+#if NH_3D
+    if ( pcSPS->getSpsExtension5bits() )
 #else
-  READ_FLAG( uiCode, "sps_extension_flag");
+    if ( pcSPS->getSpsExtension5bits() || pcSPS->getSps3dExtensionFlag() )
+#endif
+    { 
+      while ( xMoreRbspData() )
+      {
+        READ_FLAG( uiCode, "sps_extension_data_flag");
+      }
+    }
+  }
+#else
   if (uiCode)
-#endif
-  {
-#if H_MV
-    READ_FLAG( uiCode, "sps_range_extensions_flag" ); pcSPS->setSpsRangeExtensionsFlag( uiCode == 1 );
-    READ_FLAG( uiCode, "sps_multilayer_extension_flag" ); pcSPS->setSpsMultilayerExtensionFlag( uiCode == 1 );
-#if !H_3D
-    READ_CODE( 6, uiCode, "sps_extension_6bits" ); pcSPS->setSpsExtension6bits( uiCode );
-#else
-    READ_FLAG( uiCode, "sps_3d_extension_flag" ); pcSPS->setSps3dExtensionFlag( uiCode == 1 );
-    READ_CODE( 5, uiCode, "sps_extension_5bits" ); pcSPS->setSpsExtension5bits( uiCode );
-#endif
-  }
-
-  if ( pcSPS->getSpsRangeExtensionsFlag() )
-  {
-    assert( 0 ); 
-  }
-
-  if ( pcSPS->getSpsMultilayerExtensionFlag() )
-  {
-    parseSPSExtension( pcSPS ); 
-  }
-
-#if H_3D
-  if ( pcSPS->getSps3dExtensionFlag() )
-  {
-    parseSPS3dExtension( pcSPS ); 
-  }
-
-  if ( pcSPS->getSpsExtension5bits() )
-  { 
-#else
-  if ( pcSPS->getSpsExtension6bits() )
-  { 
-#endif
-
-#endif
-    while ( xMoreRbspData() )
-    {
-      READ_FLAG( uiCode, "sps_extension_data_flag");
-    }
-  }
-}
-
-#if H_MV
-Void TDecCavlc::parseSPSExtension( TComSPS* pcSPS )
+  {
+
+#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
+    static const char *syntaxStrings[]={ "sps_range_extension_flag",
+                                         "sps_multilayer_extension_flag",
+                                         "sps_extension_6bits[0]",
+                                         "sps_extension_6bits[1]",
+                                         "sps_extension_6bits[2]",
+                                         "sps_extension_6bits[3]",
+                                         "sps_extension_6bits[4]",
+                                         "sps_extension_6bits[5]" };
+#endif
+    Bool sps_extension_flags[NUM_SPS_EXTENSION_FLAGS];
+
+    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
+    {
+      READ_FLAG( uiCode, syntaxStrings[i] );
+      sps_extension_flags[i] = uiCode!=0;
+    }
+
+    Bool bSkipTrailingExtensionBits=false;
+    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
+    {
+      if (sps_extension_flags[i])
+      {
+        switch (SPSExtensionFlagIndex(i))
+        {
+          case SPS_EXT__REXT:
+            assert(!bSkipTrailingExtensionBits);
+            {
+              TComSPSRExt &spsRangeExtension = pcSPS->getSpsRangeExtension();
+              READ_FLAG( uiCode, "transform_skip_rotation_enabled_flag");     spsRangeExtension.setTransformSkipRotationEnabledFlag(uiCode != 0);
+              READ_FLAG( uiCode, "transform_skip_context_enabled_flag");      spsRangeExtension.setTransformSkipContextEnabledFlag (uiCode != 0);
+              READ_FLAG( uiCode, "implicit_rdpcm_enabled_flag");              spsRangeExtension.setRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT, (uiCode != 0));
+              READ_FLAG( uiCode, "explicit_rdpcm_enabled_flag");              spsRangeExtension.setRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT, (uiCode != 0));
+              READ_FLAG( uiCode, "extended_precision_processing_flag");       spsRangeExtension.setExtendedPrecisionProcessingFlag (uiCode != 0);
+              READ_FLAG( uiCode, "intra_smoothing_disabled_flag");            spsRangeExtension.setIntraSmoothingDisabledFlag      (uiCode != 0);
+              READ_FLAG( uiCode, "high_precision_offsets_enabled_flag");      spsRangeExtension.setHighPrecisionOffsetsEnabledFlag (uiCode != 0);
+              READ_FLAG( uiCode, "persistent_rice_adaptation_enabled_flag");  spsRangeExtension.setPersistentRiceAdaptationEnabledFlag (uiCode != 0);
+              READ_FLAG( uiCode, "cabac_bypass_alignment_enabled_flag");      spsRangeExtension.setCabacBypassAlignmentEnabledFlag  (uiCode != 0);
+            }
+            break;
+          default:
+            bSkipTrailingExtensionBits=true;
+            break;
+        }
+      }
+    }
+    if (bSkipTrailingExtensionBits)
+    {
+      while ( xMoreRbspData() )
+      {
+        READ_FLAG( uiCode, "sps_extension_data_flag");
+      }
+    }
+  }
+#endif
+  xReadRbspTrailingBits();
+}
+
+#if NH_MV
+Void TDecCavlc::parseSpsMultilayerExtension( TComSPS* pcSPS )
 {
   UInt uiCode; 
-  READ_FLAG( uiCode, "inter_view_mv_vert_constraint_flag" );    pcSPS->setInterViewMvVertConstraintFlag(uiCode == 1 ? true : false);
-  
-}
-
-#if H_3D
-Void TDecCavlc::parseSPS3dExtension( TComSPS* pcSPS )
+  READ_FLAG( uiCode, "inter_view_mv_vert_constraint_flag" );    pcSPS->setInterViewMvVertConstraintFlag(uiCode == 1 ? true : false);  
+}
+
+#if NH_3D
+Void TDecCavlc::parseSps3dExtension( TComSPS* pcSPS )
 { 
-  TComSps3dExtension* sps3dExt = pcSPS->getSps3dExtension(); 
+  TComSps3dExtension sps3dExt; 
   UInt uiCode; 
   for( Int d = 0; d  <=  1; d++ )
   {
-    READ_FLAG( uiCode, "iv_mv_pred_flag" ); sps3dExt->setIvMvPredFlag( d, uiCode == 1 );
-    READ_FLAG( uiCode, "iv_mv_scaling_flag" ); sps3dExt->setIvMvScalingFlag( d, uiCode == 1 );
+    READ_FLAG( uiCode, "iv_mv_pred_flag" ); sps3dExt.setIvMvPredFlag( d, uiCode == 1 );
+    READ_FLAG( uiCode, "iv_mv_scaling_flag" ); sps3dExt.setIvMvScalingFlag( d, uiCode == 1 );
     if( d  ==  0 )
     {
-      READ_UVLC( uiCode, "log2_sub_pb_size_minus3" ); sps3dExt->setLog2SubPbSizeMinus3( d, uiCode );
-      READ_FLAG( uiCode, "iv_res_pred_flag" ); sps3dExt->setIvResPredFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "depth_refinement_flag" ); sps3dExt->setDepthRefinementFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "view_synthesis_pred_flag" ); sps3dExt->setViewSynthesisPredFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "depth_based_blk_part_flag" ); sps3dExt->setDepthBasedBlkPartFlag( d, uiCode == 1 );
+      READ_UVLC( uiCode, "log2_sub_pb_size_minus3" ); sps3dExt.setLog2SubPbSizeMinus3( d, uiCode );
+      READ_FLAG( uiCode, "iv_res_pred_flag" ); sps3dExt.setIvResPredFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "depth_refinement_flag" ); sps3dExt.setDepthRefinementFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "view_synthesis_pred_flag" ); sps3dExt.setViewSynthesisPredFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "depth_based_blk_part_flag" ); sps3dExt.setDepthBasedBlkPartFlag( d, uiCode == 1 );
     }
     else 
     {
-      READ_FLAG( uiCode, "mpi_flag" ); sps3dExt->setMpiFlag( d, uiCode == 1 );
-      READ_UVLC( uiCode, "log2_mpi_sub_pb_size_minus3" ); sps3dExt->setLog2MpiSubPbSizeMinus3( d, uiCode );
-      READ_FLAG( uiCode, "intra_contour_flag" ); sps3dExt->setIntraContourFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "intra_sdc_wedge_flag" ); sps3dExt->setIntraSdcWedgeFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "qt_pred_flag" ); sps3dExt->setQtPredFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "inter_sdc_flag" ); sps3dExt->setInterSdcFlag( d, uiCode == 1 );
-      READ_FLAG( uiCode, "intra_skip_flag" ); sps3dExt->setDepthIntraSkipFlag( d, uiCode == 1 );
-    }
-  }
-}
-#endif
-
-Void TDecCavlc::parsePPSMultilayerExtension(TComPPS* pcPPS)
+      READ_FLAG( uiCode, "mpi_flag" ); sps3dExt.setMpiFlag( d, uiCode == 1 );
+      READ_UVLC( uiCode, "log2_mpi_sub_pb_size_minus3" ); sps3dExt.setLog2MpiSubPbSizeMinus3( d, uiCode );
+      READ_FLAG( uiCode, "intra_contour_flag" ); sps3dExt.setIntraContourFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "intra_sdc_wedge_flag" ); sps3dExt.setIntraSdcWedgeFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "qt_pred_flag" ); sps3dExt.setQtPredFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "inter_sdc_flag" ); sps3dExt.setInterSdcFlag( d, uiCode == 1 );
+      READ_FLAG( uiCode, "intra_skip_flag" ); sps3dExt.setDepthIntraSkipFlag( d, uiCode == 1 );
+    }
+  }
+  pcSPS->setSps3dExtension( sps3dExt ); 
+}
+#endif
+
+Void TDecCavlc::parsePpsMultilayerExtension(TComPPS* pcPPS)
 {
   UInt uiCode = 0; 
@@ -1087,25 +1294,33 @@
 Void TDecCavlc::parseVPS(TComVPS* pcVPS)
 {
+#if ENC_DEC_TRACE
+#if H_MV_ENC_DEC_TRAC
+  tracePSHeader( "VPS", getDecTop()->getLayerId() ); 
+#else
+  xTraceVPSHeader ();
+#endif
+#endif
+
   UInt  uiCode;
-  
+
   READ_CODE( 4,  uiCode,  "vps_video_parameter_set_id" );         pcVPS->setVPSId( uiCode );
-#if H_MV
+#if NH_MV
   READ_FLAG( uiCode, "vps_base_layer_internal_flag" );            pcVPS->setVpsBaseLayerInternalFlag( uiCode == 1 );
   READ_FLAG( uiCode, "vps_base_layer_available_flag" );           pcVPS->setVpsBaseLayerAvailableFlag( uiCode == 1 );
 #else
-  READ_CODE( 2,  uiCode,  "vps_reserved_three_2bits" );           assert(uiCode == 3);
-#endif
-#if H_MV
+  READ_FLAG( uiCode,      "vps_base_layer_internal_flag" );       assert(uiCode == 1);
+  READ_FLAG( uiCode,      "vps_base_layer_available_flag" );      assert(uiCode == 1);
+#endif
+#if NH_MV
   READ_CODE( 6,  uiCode,  "vps_max_layers_minus1" );              pcVPS->setMaxLayersMinus1( std::min( uiCode, (UInt) ( MAX_NUM_LAYER_IDS-1) )  );
 #else
-  READ_CODE( 6,  uiCode,  "vps_reserved_zero_6bits" );            assert(uiCode == 0);
+  READ_CODE( 6,  uiCode,  "vps_max_layers_minus1" );
 #endif
   READ_CODE( 3,  uiCode,  "vps_max_sub_layers_minus1" );          pcVPS->setMaxTLayers( uiCode + 1 );    assert(uiCode+1 <= MAX_TLAYER);
   READ_FLAG(     uiCode,  "vps_temporal_id_nesting_flag" );       pcVPS->setTemporalNestingFlag( uiCode ? true:false );
   assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
-
-  READ_CODE( 16, uiCode,  "vps_reserved_ffff_16bits" );           assert(uiCode == 0xffff);
+  READ_CODE( 16, uiCode,  "vps_reserved_0xffff_16bits" );         assert(uiCode == 0xffff);
   parsePTL ( pcVPS->getPTL(), true, pcVPS->getMaxTLayers()-1);
-#if H_MV
+#if NH_MV
   pcVPS->getPTL()->inferGeneralValues ( true, 0, NULL );
   pcVPS->getPTL()->inferSubLayerValues( pcVPS->getMaxTLayers() - 1, 0, NULL );
@@ -1115,6 +1330,6 @@
   for(UInt i = 0; i <= pcVPS->getMaxTLayers()-1; i++)
   {
-    READ_UVLC( uiCode,  "vps_max_dec_pic_buffering_minus1[i]" );     pcVPS->setMaxDecPicBuffering( uiCode + 1, i );
-    READ_UVLC( uiCode,  "vps_num_reorder_pics[i]" );          pcVPS->setNumReorderPics( uiCode, i );
+    READ_UVLC( uiCode,  "vps_max_dec_pic_buffering_minus1[i]" );    pcVPS->setMaxDecPicBuffering( uiCode + 1, i );
+    READ_UVLC( uiCode,  "vps_max_num_reorder_pics[i]" );            pcVPS->setNumReorderPics( uiCode, i );
     READ_UVLC( uiCode,  "vps_max_latency_increase_plus1[i]" );      pcVPS->setMaxLatencyIncrease( uiCode, i );
 
@@ -1132,5 +1347,5 @@
 
   assert( pcVPS->getNumHrdParameters() < MAX_VPS_OP_SETS_PLUS1 );
-#if H_MV
+#if NH_MV
   assert( pcVPS->getVpsMaxLayerId() < MAX_VPS_NUH_LAYER_ID_PLUS1 );
   READ_CODE( 6, uiCode, "vps_max_layer_id" );   pcVPS->setVpsMaxLayerId( uiCode );
@@ -1142,6 +1357,6 @@
 #else
   assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
-  READ_CODE( 6, uiCode, "vps_max_nuh_reserved_zero_layer_id" );   pcVPS->setMaxNuhReservedZeroLayerId( uiCode );
-  READ_UVLC(    uiCode, "vps_max_op_sets_minus1" );               pcVPS->setMaxOpSets( uiCode + 1 );
+  READ_CODE( 6, uiCode, "vps_max_layer_id" );                        pcVPS->setMaxNuhReservedZeroLayerId( uiCode );
+  READ_UVLC(    uiCode, "vps_num_layer_sets_minus1" );               pcVPS->setMaxOpSets( uiCode + 1 );
   for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
   {
@@ -1150,10 +1365,11 @@
 #endif
     {
-      READ_FLAG( uiCode, "layer_id_included_flag[opsIdx][i]" );     pcVPS->setLayerIdIncludedFlag( uiCode == 1 ? true : false, opsIdx, i );
-    }
-  }
-#if H_MV
+      READ_FLAG( uiCode, "layer_id_included_flag[opsIdx][i]" );   pcVPS->setLayerIdIncludedFlag( uiCode == 1 ? true : false, opsIdx, i );
+    }
+  }
+#if NH_MV
   pcVPS->deriveLayerSetLayerIdList(); 
 #endif
+
   TimingInfo *timingInfo = pcVPS->getTimingInfo();
   READ_FLAG(       uiCode, "vps_timing_info_present_flag");         timingInfo->setTimingInfoPresentFlag      (uiCode ? true : false);
@@ -1167,4 +1383,5 @@
       READ_UVLC(   uiCode, "vps_num_ticks_poc_diff_one_minus1");    timingInfo->setNumTicksPocDiffOneMinus1   (uiCode);
     }
+
     READ_UVLC( uiCode, "vps_num_hrd_parameters" );                  pcVPS->setNumHrdParameters( uiCode );
 
@@ -1175,8 +1392,8 @@
     for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
     {
-      READ_UVLC( uiCode, "hrd_op_set_idx" );                       pcVPS->setHrdOpSetIdx( uiCode, i );
+      READ_UVLC( uiCode, "hrd_layer_set_idx[i]" );                  pcVPS->setHrdOpSetIdx( uiCode, i );
       if( i > 0 )
       {
-        READ_FLAG( uiCode, "cprms_present_flag[i]" );              pcVPS->setCprmsPresentFlag( uiCode == 1 ? true : false, i );
+        READ_FLAG( uiCode, "cprms_present_flag[i]" );               pcVPS->setCprmsPresentFlag( uiCode == 1 ? true : false, i );
       }
       else
@@ -1188,5 +1405,5 @@
     }
   }
-#if H_MV
+#if NH_MV
   READ_FLAG( uiCode,  "vps_extension_flag" );                      pcVPS->setVpsExtensionFlag( uiCode == 1 ? true : false );
   if ( pcVPS->getVpsExtensionFlag() )
@@ -1196,5 +1413,5 @@
 #endif
   {
-#if H_MV
+#if NH_MV
     m_pcBitstream->readOutTrailingBits();
     parseVPSExtension( pcVPS );   
@@ -1202,5 +1419,5 @@
     if (uiCode)
     {
-#if H_3D
+#if NH_3D
       READ_FLAG( uiCode,  "vps_3d_extension_flag" );
       if ( uiCode )
@@ -1208,5 +1425,5 @@
         m_pcBitstream->readOutTrailingBits();
         pcVPS->createCamPars(pcVPS->getNumViews());
-        parseVPS3dExtension( pcVPS );   
+        parseVps3dExtension( pcVPS );   
       }
       READ_FLAG( uiCode,  "vps_extension3_flag" );
@@ -1219,15 +1436,16 @@
           READ_FLAG( uiCode, "vps_extension_data_flag");
         }
-#if H_MV
-#if H_3D
-      }
-#endif
-    }
-#endif
-  }
-  return; 
-}
-
-#if H_MV
+#if NH_MV
+#if NH_3D
+      }
+#endif
+    }
+#endif
+  }
+
+  xReadRbspTrailingBits();
+}
+
+#if NH_MV
 Void TDecCavlc::parseVPSExtension( TComVPS* pcVPS )
 {
@@ -1306,5 +1524,5 @@
   }
 
-#if H_3D
+#if NH_3D
   pcVPS->initViewCompLayer( ); 
 #endif
@@ -1441,12 +1659,13 @@
   READ_UVLC( uiCode, "vps_num_rep_formats_minus1" ); pcVPS->setVpsNumRepFormatsMinus1( uiCode );
 
+  std::vector<TComRepFormat> repFormats;
+  repFormats.resize( pcVPS->getVpsNumRepFormatsMinus1() + 1 ); 
   for (Int i = 0; i <= pcVPS->getVpsNumRepFormatsMinus1(); i++ )
-  { 
-    assert( pcVPS->getRepFormat(i) == NULL ); 
-    TComRepFormat* curRepFormat = new TComRepFormat(); 
-    TComRepFormat* prevRepFormat = i > 0 ? pcVPS->getRepFormat( i - 1) : NULL; 
-    parseRepFormat( i, curRepFormat ,  prevRepFormat); 
-    pcVPS->setRepFormat(i, curRepFormat ); 
-  }
+  {     
+    TComRepFormat* curRepFormat = &repFormats[i]; 
+    TComRepFormat* prevRepFormat = i > 0 ? &repFormats[ i - 1] : NULL; 
+    parseRepFormat( i, curRepFormat ,  prevRepFormat);     
+  }
+  pcVPS->setRepFormat( repFormats ); 
 
   if ( pcVPS->getVpsNumRepFormatsMinus1() > 0 )
@@ -1514,19 +1733,21 @@
   }
   READ_FLAG( uiCode, "vps_vui_present_flag" );  pcVPS->setVpsVuiPresentFlag( uiCode == 1 );
+  
+  TComVPSVUI vpsVui;
   if( pcVPS->getVpsVuiPresentFlag() )
   {
     m_pcBitstream->readOutTrailingBits(); // vps_vui_alignment_bit_equal_to_one
-    parseVPSVUI( pcVPS ); 
+    parseVPSVUI( pcVPS, &vpsVui ); 
   }     
   else
-  {
-    TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
-    assert( pcVPSVUI ); 
-    pcVPSVUI->inferVpsVui( false ); 
-  }
+  {    
+    // inference of syntax elements that differ from default inference (as done in constructor), when VPS VUI is not present    
+    vpsVui.setCrossLayerIrapAlignedFlag( false ); 
+  }
+  pcVPS->setVPSVUI( vpsVui ); 
   pcVPS->checkVPSExtensionSyntax(); 
 }
 
-Void TDecCavlc::parseRepFormat( Int i, TComRepFormat* pcRepFormat, TComRepFormat* pcPrevRepFormat )
+Void TDecCavlc::parseRepFormat( Int i, TComRepFormat* pcRepFormat, const TComRepFormat* pcPrevRepFormat )
 {
   assert( pcRepFormat ); 
@@ -1552,5 +1773,5 @@
   else
   {
-    pcRepFormat->inferChromaAndBitDepth(pcPrevRepFormat, false ); 
+    pcRepFormat->inferChromaAndBitDepth(pcPrevRepFormat ); 
   }
   READ_FLAG( uiCode, "conformance_window_vps_flag" ); pcRepFormat->setConformanceWindowVpsFlag( uiCode == 1 );
@@ -1565,25 +1786,24 @@
 
 
-Void TDecCavlc::parseVPSVUI( TComVPS* pcVPS )
+Void TDecCavlc::parseVPSVUI( const TComVPS* pcVPS, TComVPSVUI* vpsVui )
 {
   assert( pcVPS ); 
-
-  TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
-
-  assert( pcVPSVUI ); 
+  assert( vpsVui ); 
+  
+  vpsVui->init(pcVPS->getNumAddLayerSets(),pcVPS->getMaxSubLayersMinus1() + 1, pcVPS->getMaxLayersMinus1() + 1 );  
 
   UInt uiCode; 
-  READ_FLAG( uiCode, "cross_layer_pic_type_aligned_flag" ); pcVPSVUI->setCrossLayerPicTypeAlignedFlag( uiCode == 1 );
-  if ( !pcVPSVUI->getCrossLayerPicTypeAlignedFlag() )
+  READ_FLAG( uiCode, "cross_layer_pic_type_aligned_flag" ); vpsVui->setCrossLayerPicTypeAlignedFlag( uiCode == 1 );
+  if ( !vpsVui->getCrossLayerPicTypeAlignedFlag() )
   {  
-    READ_FLAG( uiCode, "cross_layer_irap_aligned_flag" ); pcVPSVUI->setCrossLayerIrapAlignedFlag( uiCode == 1 );
-  }
-  if( pcVPSVUI->getCrossLayerIrapAlignedFlag( ) )
-  {
-    READ_FLAG( uiCode, "all_layers_idr_aligned_flag" ); pcVPSVUI->setAllLayersIdrAlignedFlag( uiCode == 1 );
-  }
-  READ_FLAG( uiCode, "bit_rate_present_vps_flag" ); pcVPSVUI->setBitRatePresentVpsFlag( uiCode == 1 );
-  READ_FLAG( uiCode, "pic_rate_present_vps_flag" ); pcVPSVUI->setPicRatePresentVpsFlag( uiCode == 1 );
-  if( pcVPSVUI->getBitRatePresentVpsFlag( )  ||  pcVPSVUI->getPicRatePresentVpsFlag( ) )
+    READ_FLAG( uiCode, "cross_layer_irap_aligned_flag" ); vpsVui->setCrossLayerIrapAlignedFlag( uiCode == 1 );
+  }
+  if( vpsVui->getCrossLayerIrapAlignedFlag( ) )
+  {
+    READ_FLAG( uiCode, "all_layers_idr_aligned_flag" ); vpsVui->setAllLayersIdrAlignedFlag( uiCode == 1 );
+  }
+  READ_FLAG( uiCode, "bit_rate_present_vps_flag" ); vpsVui->setBitRatePresentVpsFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "pic_rate_present_vps_flag" ); vpsVui->setPicRatePresentVpsFlag( uiCode == 1 );
+  if( vpsVui->getBitRatePresentVpsFlag( )  ||  vpsVui->getPicRatePresentVpsFlag( ) )
   {
     for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i  <  pcVPS->getNumLayerSets(); i++ )
@@ -1591,56 +1811,57 @@
       for( Int j = 0; j  <=  pcVPS->getMaxSubLayersInLayerSetMinus1( i ); j++ ) 
       {
-        if( pcVPSVUI->getBitRatePresentVpsFlag( ) )
-        {
-          READ_FLAG( uiCode, "bit_rate_present_flag" ); pcVPSVUI->setBitRatePresentFlag( i, j, uiCode == 1 );            
-        }
-        if( pcVPSVUI->getPicRatePresentVpsFlag( )  )
-        {
-          READ_FLAG( uiCode, "pic_rate_present_flag" ); pcVPSVUI->setPicRatePresentFlag( i, j, uiCode == 1 );
-        }
-        if( pcVPSVUI->getBitRatePresentFlag( i, j ) )
-        {
-          READ_CODE( 16, uiCode, "avg_bit_rate" ); pcVPSVUI->setAvgBitRate( i, j, uiCode );
-          READ_CODE( 16, uiCode, "max_bit_rate" ); pcVPSVUI->setMaxBitRate( i, j, uiCode );
-        }
-        if( pcVPSVUI->getPicRatePresentFlag( i, j ) )
-        {
-          READ_CODE( 2,  uiCode, "constant_pic_rate_idc" ); pcVPSVUI->setConstantPicRateIdc( i, j, uiCode );
-          READ_CODE( 16, uiCode, "avg_pic_rate" );          pcVPSVUI->setAvgPicRate( i, j, uiCode );
-        }
-      }
-    }
-  }
-
-  READ_FLAG( uiCode, "video_signal_info_idx_present_flag" ); pcVPSVUI->setVideoSignalInfoIdxPresentFlag( uiCode == 1 );
-  if( pcVPSVUI->getVideoSignalInfoIdxPresentFlag() )
-  {
-    READ_CODE( 4, uiCode, "vps_num_video_signal_info_minus1" ); pcVPSVUI->setVpsNumVideoSignalInfoMinus1( uiCode );
+        if( vpsVui->getBitRatePresentVpsFlag( ) )
+        {
+          READ_FLAG( uiCode, "bit_rate_present_flag" ); vpsVui->setBitRatePresentFlag( i, j, uiCode == 1 );            
+        }
+        if( vpsVui->getPicRatePresentVpsFlag( )  )
+        {
+          READ_FLAG( uiCode, "pic_rate_present_flag" ); vpsVui->setPicRatePresentFlag( i, j, uiCode == 1 );
+        }
+        if( vpsVui->getBitRatePresentFlag( i, j ) )
+        {
+          READ_CODE( 16, uiCode, "avg_bit_rate" ); vpsVui->setAvgBitRate( i, j, uiCode );
+          READ_CODE( 16, uiCode, "max_bit_rate" ); vpsVui->setMaxBitRate( i, j, uiCode );
+        }
+        if( vpsVui->getPicRatePresentFlag( i, j ) )
+        {
+          READ_CODE( 2,  uiCode, "constant_pic_rate_idc" ); vpsVui->setConstantPicRateIdc( i, j, uiCode );
+          READ_CODE( 16, uiCode, "avg_pic_rate" );          vpsVui->setAvgPicRate( i, j, uiCode );
+        }
+      }
+    }
+  }
+
+  READ_FLAG( uiCode, "video_signal_info_idx_present_flag" ); vpsVui->setVideoSignalInfoIdxPresentFlag( uiCode == 1 );
+  if( vpsVui->getVideoSignalInfoIdxPresentFlag() )
+  {
+    READ_CODE( 4, uiCode, "vps_num_video_signal_info_minus1" ); vpsVui->setVpsNumVideoSignalInfoMinus1( uiCode );
   }
   else
   {
-    pcVPSVUI->setVpsNumVideoSignalInfoMinus1( pcVPS->getMaxLayersMinus1() - pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1 ); 
-  }
-
-  for( Int i = 0; i <= pcVPSVUI->getVpsNumVideoSignalInfoMinus1(); i++ )
-  {
-    assert( pcVPSVUI->getVideoSignalInfo( i ) == NULL ); 
-    TComVideoSignalInfo* curVideoSignalInfo = new TComVideoSignalInfo();     
-    parseVideoSignalInfo( curVideoSignalInfo ); 
-    pcVPSVUI->setVideoSignalInfo(i, curVideoSignalInfo ); 
-  }
-
-  if( pcVPSVUI->getVideoSignalInfoIdxPresentFlag() && pcVPSVUI->getVpsNumVideoSignalInfoMinus1() > 0 )
+    vpsVui->setVpsNumVideoSignalInfoMinus1( pcVPS->getMaxLayersMinus1() - pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1 ); 
+  }
+
+  std::vector<TComVideoSignalInfo> videoSignalInfos; 
+  videoSignalInfos.resize(vpsVui->getVpsNumVideoSignalInfoMinus1() + 1 );
+
+  for( Int i = 0; i <= vpsVui->getVpsNumVideoSignalInfoMinus1(); i++ )
+  { 
+    parseVideoSignalInfo( &videoSignalInfos[i] );     
+  }
+  vpsVui->setVideoSignalInfo( videoSignalInfos ); 
+
+  if( vpsVui->getVideoSignalInfoIdxPresentFlag() && vpsVui->getVpsNumVideoSignalInfoMinus1() > 0 )
   {
     for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i <=  pcVPS->getMaxLayersMinus1(); i++ )
     {
-      READ_CODE( 4, uiCode, "vps_video_signal_info_idx" ); pcVPSVUI->setVpsVideoSignalInfoIdx( i, uiCode );
-    }
-  }
-  else if ( !pcVPSVUI->getVideoSignalInfoIdxPresentFlag() )
+      READ_CODE( 4, uiCode, "vps_video_signal_info_idx" ); vpsVui->setVpsVideoSignalInfoIdx( i, uiCode );
+    }
+  }
+  else if ( !vpsVui->getVideoSignalInfoIdxPresentFlag() )
   {
     for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i <=  pcVPS->getMaxLayersMinus1(); i++ )
     {
-      pcVPSVUI->setVpsVideoSignalInfoIdx( i, i );
+      vpsVui->setVpsVideoSignalInfoIdx( i, i );
     }
   }
@@ -1649,17 +1870,17 @@
     for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i <=  pcVPS->getMaxLayersMinus1(); i++ )
     {
-      pcVPSVUI->setVpsVideoSignalInfoIdx( i, 0 );
-    }
-  }
-
-  READ_FLAG( uiCode, "tiles_not_in_use_flag" ); pcVPSVUI->setTilesNotInUseFlag( uiCode == 1 );
-  if( !pcVPSVUI->getTilesNotInUseFlag() ) 
+      vpsVui->setVpsVideoSignalInfoIdx( i, 0 );
+    }
+  }
+
+  READ_FLAG( uiCode, "tiles_not_in_use_flag" ); vpsVui->setTilesNotInUseFlag( uiCode == 1 );
+  if( !vpsVui->getTilesNotInUseFlag() ) 
   {      
     for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
     {
-      READ_FLAG( uiCode, "tiles_in_use_flag[i]" ); pcVPSVUI->setTilesInUseFlag( i, uiCode == 1 );
-      if( pcVPSVUI->getTilesInUseFlag( i ) )  
-      {
-        READ_FLAG( uiCode, "loop_filter_not_across_tiles_flag[i]" ); pcVPSVUI->setLoopFilterNotAcrossTilesFlag( i, uiCode == 1 );
+      READ_FLAG( uiCode, "tiles_in_use_flag[i]" ); vpsVui->setTilesInUseFlag( i, uiCode == 1 );
+      if( vpsVui->getTilesInUseFlag( i ) )  
+      {
+        READ_FLAG( uiCode, "loop_filter_not_across_tiles_flag[i]" ); vpsVui->setLoopFilterNotAcrossTilesFlag( i, uiCode == 1 );
       }
     }  
@@ -1669,7 +1890,7 @@
       {
         Int layerIdx = pcVPS->getLayerIdInVps(pcVPS->getIdDirectRefLayer(pcVPS->getLayerIdInNuh( i ) , j  ));  
-        if( pcVPSVUI->getTilesInUseFlag( i )  &&  pcVPSVUI->getTilesInUseFlag( layerIdx ) )  
-        {
-          READ_FLAG( uiCode, "tile_boundaries_aligned_flag[i][j]" ); pcVPSVUI->setTileBoundariesAlignedFlag( i, j, uiCode == 1 );
+        if( vpsVui->getTilesInUseFlag( i )  &&  vpsVui->getTilesInUseFlag( layerIdx ) )  
+        {
+          READ_FLAG( uiCode, "tile_boundaries_aligned_flag[i][j]" ); vpsVui->setTileBoundariesAlignedFlag( i, j, uiCode == 1 );
         }
       }  
@@ -1677,18 +1898,18 @@
   }  
   
-  READ_FLAG( uiCode, "wpp_not_in_use_flag" ); pcVPSVUI->setWppNotInUseFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "wpp_not_in_use_flag" ); vpsVui->setWppNotInUseFlag( uiCode == 1 );
   
-  if( !pcVPSVUI->getWppNotInUseFlag( ))
+  if( !vpsVui->getWppNotInUseFlag( ))
   {
     for( Int i = 0; i  <=  pcVPS->getMaxLayersMinus1(); i++ )  
     {
-      READ_FLAG( uiCode, "wpp_in_use_flag[i]" ); pcVPSVUI->setWppInUseFlag( i, uiCode == 1 );
-    }
-  }
-  READ_FLAG( uiCode, "single_layer_for_non_irap_flag" ); pcVPSVUI->setSingleLayerForNonIrapFlag( uiCode == 1 );
-  READ_FLAG( uiCode, "higher_layer_irap_skip_flag" ); pcVPSVUI->setHigherLayerIrapSkipFlag( uiCode == 1 );
-  READ_FLAG( uiCode, "ilp_restricted_ref_layers_flag" ); pcVPSVUI->setIlpRestrictedRefLayersFlag( uiCode == 1 );
-
-  if( pcVPSVUI->getIlpRestrictedRefLayersFlag( ) )
+      READ_FLAG( uiCode, "wpp_in_use_flag[i]" ); vpsVui->setWppInUseFlag( i, uiCode == 1 );
+    }
+  }
+  READ_FLAG( uiCode, "single_layer_for_non_irap_flag" ); vpsVui->setSingleLayerForNonIrapFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "higher_layer_irap_skip_flag" ); vpsVui->setHigherLayerIrapSkipFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "ilp_restricted_ref_layers_flag" ); vpsVui->setIlpRestrictedRefLayersFlag( uiCode == 1 );
+
+  if( vpsVui->getIlpRestrictedRefLayersFlag( ) )
   {
     for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
@@ -1698,11 +1919,11 @@
         if( pcVPS->getVpsBaseLayerInternalFlag() || pcVPS->getIdDirectRefLayer( pcVPS->getLayerIdInNuh( i ), j ) > 0 )
         {        
-          READ_UVLC( uiCode, "min_spatial_segment_offset_plus1" ); pcVPSVUI->setMinSpatialSegmentOffsetPlus1( i, j, uiCode );
-          if( pcVPSVUI->getMinSpatialSegmentOffsetPlus1( i, j ) > 0 )
+          READ_UVLC( uiCode, "min_spatial_segment_offset_plus1" ); vpsVui->setMinSpatialSegmentOffsetPlus1( i, j, uiCode );
+          if( vpsVui->getMinSpatialSegmentOffsetPlus1( i, j ) > 0 )
           {
-            READ_FLAG( uiCode, "ctu_based_offset_enabled_flag" ); pcVPSVUI->setCtuBasedOffsetEnabledFlag( i, j, uiCode == 1 );
-            if( pcVPSVUI->getCtuBasedOffsetEnabledFlag( i, j ) )
+            READ_FLAG( uiCode, "ctu_based_offset_enabled_flag" ); vpsVui->setCtuBasedOffsetEnabledFlag( i, j, uiCode == 1 );
+            if( vpsVui->getCtuBasedOffsetEnabledFlag( i, j ) )
             {
-              READ_UVLC( uiCode, "min_horizontal_ctu_offset_plus1" ); pcVPSVUI->setMinHorizontalCtuOffsetPlus1( i, j, uiCode );
+              READ_UVLC( uiCode, "min_horizontal_ctu_offset_plus1" ); vpsVui->setMinHorizontalCtuOffsetPlus1( i, j, uiCode );
             }
           }
@@ -1712,9 +1933,9 @@
   }
 
-  READ_FLAG( uiCode, "vps_vui_bsp_hrd_present_flag" ); pcVPSVUI->setVpsVuiBspHrdPresentFlag( uiCode == 1 );
-  if ( pcVPSVUI->getVpsVuiBspHrdPresentFlag( ) )
-  {
-    assert(pcVPS->getTimingInfo()->getTimingInfoPresentFlag() == 1);
-    parseVpsVuiBspHrdParameters( pcVPS ); 
+  READ_FLAG( uiCode, "vps_vui_bsp_hrd_present_flag" ); vpsVui->setVpsVuiBspHrdPresentFlag( uiCode == 1 );
+  if ( vpsVui->getVpsVuiBspHrdPresentFlag( ) )
+  {
+    assert(pcVPS->getTimingInfo()->getTimingInfoPresentFlag() == 1);    
+    parseVpsVuiBspHrdParameters( pcVPS, vpsVui );     
   }
   for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
@@ -1722,42 +1943,39 @@
     if( pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i )) == 0 ) 
     {
-      READ_FLAG( uiCode, "base_layer_parameter_set_compatibility_flag" ); pcVPSVUI->setBaseLayerParameterSetCompatibilityFlag( i, uiCode == 1 );
-    }
-  }
-}
-
-Void TDecCavlc::parseVpsVuiBspHrdParameters( TComVPS* pcVPS )
-{
-  assert( pcVPS ); 
-
-  TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
-
-  assert( pcVPSVUI ); 
-
-  TComVpsVuiBspHrdParameters*  vpsVuiBspHrdP = pcVPSVUI->getVpsVuiBspHrdParameters(); 
-  assert( vpsVuiBspHrdP == NULL ); 
-  vpsVuiBspHrdP = new TComVpsVuiBspHrdParameters; 
-  pcVPSVUI->setVpsVuiBspHrdParameters( vpsVuiBspHrdP ); 
+      READ_FLAG( uiCode, "base_layer_parameter_set_compatibility_flag" ); vpsVui->setBaseLayerParameterSetCompatibilityFlag( i, uiCode == 1 );
+    }
+  }  
+}
+
+Void TDecCavlc::parseVpsVuiBspHrdParameters( const TComVPS* pcVPS, TComVPSVUI* vpsVui )
+{
+  assert( pcVPS  ); 
+  assert( vpsVui ); 
+
+  TComVpsVuiBspHrdParameters  vpsVuiBspHrdP;    
+  
   UInt uiCode; 
-  READ_UVLC( uiCode, "vps_num_add_hrd_params" ); vpsVuiBspHrdP->setVpsNumAddHrdParams( uiCode );
-  vpsVuiBspHrdP->createAfterVpsNumAddHrdParams( pcVPS ); 
-  for( Int i = pcVPS->getNumHrdParameters(); i < pcVPS->getNumHrdParameters() + vpsVuiBspHrdP->getVpsNumAddHrdParams(); i++ )
+  READ_UVLC( uiCode, "vps_num_add_hrd_params" ); vpsVuiBspHrdP.setVpsNumAddHrdParams( uiCode );
+  vpsVuiBspHrdP.createAfterVpsNumAddHrdParams( pcVPS ); 
+  for( Int i = pcVPS->getNumHrdParameters(); i < pcVPS->getNumHrdParameters() + vpsVuiBspHrdP.getVpsNumAddHrdParams(); i++ )
   {  
     if( i > 0 )  
     {
-      READ_FLAG( uiCode, "cprms_add_present_flag" ); vpsVuiBspHrdP->setCprmsAddPresentFlag( i, uiCode == 1 );
+      READ_FLAG( uiCode, "cprms_add_present_flag" ); vpsVuiBspHrdP.setCprmsAddPresentFlag( i, uiCode == 1 );
     }
     else
     {
-       vpsVuiBspHrdP->setCprmsAddPresentFlag( i, true );
-    }
-
-    READ_UVLC( uiCode, "num_sub_layer_hrd_minus1" ); vpsVuiBspHrdP->setNumSubLayerHrdMinus1( i, uiCode );
-    TComHRD* hrdParameters = vpsVuiBspHrdP->getHrdParametermeters( i ); 
-    parseHrdParameters( hrdParameters, vpsVuiBspHrdP->getCprmsAddPresentFlag( i ), vpsVuiBspHrdP->getNumSubLayerHrdMinus1( i ) );     
-  }
-
-  vpsVuiBspHrdP->setNumPartitionsInSchemeMinus1( 0, 0, 0);
-  vpsVuiBspHrdP->createAfterNumPartitionsInSchemeMinus1( 0, 0 );
+       vpsVuiBspHrdP.setCprmsAddPresentFlag( i, true );
+    }
+
+    READ_UVLC( uiCode, "num_sub_layer_hrd_minus1" ); vpsVuiBspHrdP.setNumSubLayerHrdMinus1( i, uiCode );
+    
+    TComHRD hrdParameters;
+    parseHrdParameters( &hrdParameters, vpsVuiBspHrdP.getCprmsAddPresentFlag( i ), vpsVuiBspHrdP.getNumSubLayerHrdMinus1( i ) );     
+    vpsVuiBspHrdP.setHrdParametermeters( i, hrdParameters ); 
+  }
+
+  vpsVuiBspHrdP.setNumPartitionsInSchemeMinus1( 0, 0, 0);
+  vpsVuiBspHrdP.createAfterNumPartitionsInSchemeMinus1( pcVPS, 0, 0 );
 
   for( Int h = 0; h < pcVPS->getNumOutputLayerSets(); h++ )
@@ -1765,29 +1983,29 @@
     if ( h == 0)
     {
-      vpsVuiBspHrdP->setNumSignalledPartitioningSchemes( h, 0 );
+      vpsVuiBspHrdP.setNumSignalledPartitioningSchemes( h, 0 );
     }
     else
     {
-      READ_UVLC( uiCode, "num_signalled_partitioning_schemes" ); vpsVuiBspHrdP->setNumSignalledPartitioningSchemes( h, uiCode );
+      READ_UVLC( uiCode, "num_signalled_partitioning_schemes" ); vpsVuiBspHrdP.setNumSignalledPartitioningSchemes( h, uiCode );
     }    
-    vpsVuiBspHrdP->createAfterNumSignalledPartitioningSchemes( h );
-
-    for( Int j = 0; j < vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ) + 1; j++ )
+    vpsVuiBspHrdP.createAfterNumSignalledPartitioningSchemes( pcVPS, h );
+
+    for( Int j = 0; j < vpsVuiBspHrdP.getNumSignalledPartitioningSchemes( h ) + 1; j++ )
     { 
       if ( j == 0 && h == 0 )
       {
-        vpsVuiBspHrdP->setNumPartitionsInSchemeMinus1( h, j, uiCode );
+        vpsVuiBspHrdP.setNumPartitionsInSchemeMinus1( h, j, uiCode );
       }
       else if( j == 0 )
       {
-        vpsVuiBspHrdP->setNumPartitionsInSchemeMinus1( h, j, pcVPS->getNumLayersInIdList( h ) - 1 );
+        vpsVuiBspHrdP.setNumPartitionsInSchemeMinus1( h, j, pcVPS->getNumLayersInIdList( h ) - 1 );
       }
       else
       {
-        READ_UVLC( uiCode, "num_partitions_in_scheme_minus1" ); vpsVuiBspHrdP->setNumPartitionsInSchemeMinus1( h, j, uiCode );
-      }
-      vpsVuiBspHrdP->createAfterNumPartitionsInSchemeMinus1( h, j );
-
-      for( Int k = 0; k  <=  vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ); k++ )  
+        READ_UVLC( uiCode, "num_partitions_in_scheme_minus1" ); vpsVuiBspHrdP.setNumPartitionsInSchemeMinus1( h, j, uiCode );
+      }
+      vpsVuiBspHrdP.createAfterNumPartitionsInSchemeMinus1(pcVPS, h, j );
+
+      for( Int k = 0; k  <=  vpsVuiBspHrdP.getNumPartitionsInSchemeMinus1( h, j ); k++ )  
       {
         for( Int r = 0; r < pcVPS->getNumLayersInIdList(pcVPS->olsIdxToLsIdx( h ) )   ; r++ )  
@@ -1795,13 +2013,13 @@
           if( h == 0 && j == 0 && k == 0 && r == 0 )
           {
-             vpsVuiBspHrdP->setLayerIncludedInPartitionFlag( h, j, k, r, true );
+             vpsVuiBspHrdP.setLayerIncludedInPartitionFlag( h, j, k, r, true );
           }
           else if ( h > 0 && j == 0 )
           {
-             vpsVuiBspHrdP->setLayerIncludedInPartitionFlag( h, j, k, r, (k == r) );
+             vpsVuiBspHrdP.setLayerIncludedInPartitionFlag( h, j, k, r, (k == r) );
           }
           else
           {
-            READ_FLAG( uiCode, "layer_included_in_partition_flag" ); vpsVuiBspHrdP->setLayerIncludedInPartitionFlag( h, j, k, r, uiCode == 1 );
+            READ_FLAG( uiCode, "layer_included_in_partition_flag" ); vpsVuiBspHrdP.setLayerIncludedInPartitionFlag( h, j, k, r, uiCode == 1 );
           }          
         }
@@ -1810,16 +2028,16 @@
     if ( h > 0 )
     {
-      for( Int i = 0; i < vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ) + 1; i++ )  
+      for( Int i = 0; i < vpsVuiBspHrdP.getNumSignalledPartitioningSchemes( h ) + 1; i++ )  
       {
         for( Int t = 0; t  <=  pcVPS->getMaxSubLayersInLayerSetMinus1( pcVPS->olsIdxToLsIdx( i ) ); t++ )
         {  
-          READ_UVLC( uiCode, "num_bsp_schedules_minus1" ); vpsVuiBspHrdP->setNumBspSchedulesMinus1( h, i, t, uiCode );
-          vpsVuiBspHrdP->createAfterNumBspSchedulesMinus1( h, i, t );
-          for( Int j = 0; j  <=  vpsVuiBspHrdP->getNumBspSchedulesMinus1( h, i, t ); j++ )  
+          READ_UVLC( uiCode, "num_bsp_schedules_minus1" ); vpsVuiBspHrdP.setNumBspSchedulesMinus1( h, i, t, uiCode );
+          vpsVuiBspHrdP.createAfterNumBspSchedulesMinus1(pcVPS, h, i, t );
+          for( Int j = 0; j  <=  vpsVuiBspHrdP.getNumBspSchedulesMinus1( h, i, t ); j++ )  
           {
-            for( Int k = 0; k  <=  vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ); k++ )
+            for( Int k = 0; k  <=  vpsVuiBspHrdP.getNumPartitionsInSchemeMinus1( h, j ); k++ )
             {  
-              READ_CODE( vpsVuiBspHrdP->getBspHrdIdxLen( pcVPS ), uiCode, "bsp_hrd_idx" ); vpsVuiBspHrdP->setBspHrdIdx( h, i, t, j, k, uiCode );
-              READ_UVLC( uiCode, "bsp_sched_idx" ); vpsVuiBspHrdP->setBspSchedIdx( h, i, t, j, k, uiCode );
+              READ_CODE( vpsVuiBspHrdP.getBspHrdIdxLen( pcVPS ), uiCode, "bsp_hrd_idx" ); vpsVuiBspHrdP.setBspHrdIdx( h, i, t, j, k, uiCode );
+              READ_UVLC( uiCode, "bsp_sched_idx" ); vpsVuiBspHrdP.setBspSchedIdx( h, i, t, j, k, uiCode );
             }  
           }
@@ -1828,4 +2046,5 @@
     }
   }  
+  vpsVui->setVpsVuiBspHrdParameters( vpsVuiBspHrdP ); 
 }
 
@@ -1843,18 +2062,19 @@
 {
   UInt uiCode; 
-  TComDpbSize* dpbSize = vps->getDpbSize(); 
-  assert ( dpbSize != 0 ); 
+  TComDpbSize dpbSize; 
+  
+  dpbSize.init( vps->getNumOutputLayerSets(), vps->getVpsMaxLayerId() + 1, vps->getMaxSubLayersMinus1() + 1 ) ;
 
   for( Int i = 1; i < vps->getNumOutputLayerSets(); i++ )
   {  
     Int currLsIdx = vps->olsIdxToLsIdx( i ); 
-    READ_FLAG( uiCode, "sub_layer_flag_info_present_flag" ); dpbSize->setSubLayerFlagInfoPresentFlag( i, uiCode == 1 );
+    READ_FLAG( uiCode, "sub_layer_flag_info_present_flag" ); dpbSize.setSubLayerFlagInfoPresentFlag( i, uiCode == 1 );
     for( Int j = 0; j  <=  vps->getMaxSubLayersInLayerSetMinus1( currLsIdx ); j++ )
     {  
-      if( j > 0  &&  dpbSize->getSubLayerDpbInfoPresentFlag( i, j )  )  
-      {
-        READ_FLAG( uiCode, "sub_layer_dpb_info_present_flag" ); dpbSize->setSubLayerDpbInfoPresentFlag( i, j, uiCode == 1 );
-      }
-      if( dpbSize->getSubLayerDpbInfoPresentFlag( i, j ) )
+      if( j > 0  &&  dpbSize.getSubLayerDpbInfoPresentFlag( i, j )  )  
+      {
+        READ_FLAG( uiCode, "sub_layer_dpb_info_present_flag" ); dpbSize.setSubLayerDpbInfoPresentFlag( i, j, uiCode == 1 );
+      }
+      if( dpbSize.getSubLayerDpbInfoPresentFlag( i, j ) )
       {  
         for( Int k = 0; k < vps->getNumLayersInIdList( currLsIdx ); k++ )   
@@ -1862,5 +2082,5 @@
           if ( vps->getNecessaryLayerFlag( i, k ) && ( vps->getVpsBaseLayerInternalFlag() || ( vps->getLayerSetLayerIdList(vps->olsIdxToLsIdx(i),k) != 0 ) ))
           {
-            READ_UVLC( uiCode, "max_vps_dec_pic_buffering_minus1" ); dpbSize->setMaxVpsDecPicBufferingMinus1( i, k, j, uiCode );
+            READ_UVLC( uiCode, "max_vps_dec_pic_buffering_minus1" ); dpbSize.setMaxVpsDecPicBufferingMinus1( i, k, j, uiCode );
           }
           else
@@ -1868,10 +2088,10 @@
             if ( vps->getNecessaryLayerFlag( i, k ) && ( j == 0 ) && ( k == 0 ))
             {
-              dpbSize->setMaxVpsDecPicBufferingMinus1(i ,k, j, 0 );
+              dpbSize.setMaxVpsDecPicBufferingMinus1(i ,k, j, 0 );
             }
           }
         }
-        READ_UVLC( uiCode, "max_vps_num_reorder_pics" ); dpbSize->setMaxVpsNumReorderPics( i, j, uiCode );
-        READ_UVLC( uiCode, "max_vps_latency_increase_plus1" ); dpbSize->setMaxVpsLatencyIncreasePlus1( i, j, uiCode );
+        READ_UVLC( uiCode, "max_vps_num_reorder_pics" ); dpbSize.setMaxVpsNumReorderPics( i, j, uiCode );
+        READ_UVLC( uiCode, "max_vps_latency_increase_plus1" ); dpbSize.setMaxVpsLatencyIncreasePlus1( i, j, uiCode );
       }
       else
@@ -1883,17 +2103,18 @@
             if ( vps->getNecessaryLayerFlag(i, k ) )
             {            
-              dpbSize->setMaxVpsDecPicBufferingMinus1( i, k, j, dpbSize->getMaxVpsDecPicBufferingMinus1( i,k, j - 1 ) );
+              dpbSize.setMaxVpsDecPicBufferingMinus1( i, k, j, dpbSize.getMaxVpsDecPicBufferingMinus1( i,k, j - 1 ) );
             }
           }
-          dpbSize->setMaxVpsNumReorderPics      ( i, j, dpbSize->getMaxVpsNumReorderPics      ( i, j - 1 ) );
-          dpbSize->setMaxVpsLatencyIncreasePlus1( i, j, dpbSize->getMaxVpsLatencyIncreasePlus1( i, j - 1 ) );
+          dpbSize.setMaxVpsNumReorderPics      ( i, j, dpbSize.getMaxVpsNumReorderPics      ( i, j - 1 ) );
+          dpbSize.setMaxVpsLatencyIncreasePlus1( i, j, dpbSize.getMaxVpsLatencyIncreasePlus1( i, j - 1 ) );
         }
       }
     }  
   }  
-}
-
-#if H_3D
-Void TDecCavlc::parseVPS3dExtension( TComVPS* pcVPS )
+  vps->setDpbSize( dpbSize ); 
+}
+
+#if NH_3D
+Void TDecCavlc::parseVps3dExtension( TComVPS* pcVPS )
 {
   UInt uiCode;   
@@ -1929,9 +2150,6 @@
 #endif
 #endif
-#if H_MV
-Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, Int targetOlsIdx)
-#else
-Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)
-#endif
+
+Void TDecCavlc::parseSliceHeader (TComSlice* pcSlice, ParameterSetManager *parameterSetManager, const Int prevTid0POC)
 {
   UInt  uiCode;
@@ -1939,9 +2157,13 @@
 
 #if ENC_DEC_TRACE
-  xTraceSliceHeader(rpcSlice);
+#if NH_MV
+  tracePSHeader( "Slice", pcSlice->getLayerId() ); 
+#else
+  xTraceSliceHeader();
+#endif
 #endif
   TComPPS* pps = NULL;
   TComSPS* sps = NULL;
-#if H_MV
+#if NH_MV
   TComVPS* vps = NULL;
 #endif
@@ -1949,52 +2171,62 @@
   UInt firstSliceSegmentInPic;
   READ_FLAG( firstSliceSegmentInPic, "first_slice_segment_in_pic_flag" );
-  if( rpcSlice->getRapPicFlag())
-  { 
+  if( pcSlice->getRapPicFlag())
+  {
     READ_FLAG( uiCode, "no_output_of_prior_pics_flag" );  //ignored -- updated already
-#if SETTING_NO_OUT_PIC_PRIOR
-    rpcSlice->setNoOutputPriorPicsFlag(uiCode ? true : false);
-#else
-    rpcSlice->setNoOutputPicPrior( false );
-#endif
-  }
-
-  READ_UVLC (    uiCode, "slice_pic_parameter_set_id" );  rpcSlice->setPPSId(uiCode);
-  pps = parameterSetManager->getPrefetchedPPS(uiCode);
+    pcSlice->setNoOutputPriorPicsFlag(uiCode ? true : false);
+  }
+  READ_UVLC (    uiCode, "slice_pic_parameter_set_id" );  pcSlice->setPPSId(uiCode);
+  pps = parameterSetManager->getPPS(uiCode);
   //!KS: need to add error handling code here, if PPS is not available
   assert(pps!=0);
-  sps = parameterSetManager->getPrefetchedSPS(pps->getSPSId());
+  sps = parameterSetManager->getSPS(pps->getSPSId());
   //!KS: need to add error handling code here, if SPS is not available
   assert(sps!=0);
-#if H_MV
-  vps = parameterSetManager->getPrefetchedVPS(sps->getVPSId());
-  assert( vps != NULL );
-  
-  sps->inferRepFormat  ( vps , rpcSlice->getLayerId() ); 
+#if NH_MV  
+  vps = parameterSetManager->getVPS(sps->getVPSId());
+  assert( vps != NULL );  
+  m_decTop->initFromActiveVps( vps );
+  Int targetOlsIdx = m_decTop->getTargetOlsIdx(); 
+
+  // Do inference 
+  sps->inferRepFormat  ( vps , pcSlice->getLayerId(), false ); 
   sps->inferScalingList( parameterSetManager->getActiveSPS( sps->getSpsScalingListRefLayerId() ) );   
-  sps->inferSpsMaxDecPicBufferingMinus1( vps, targetOlsIdx, rpcSlice->getLayerId(), false ); 
+  sps->inferSpsMaxDecPicBufferingMinus1( vps, targetOlsIdx, pcSlice->getLayerId(), false ); 
+
+  if( sps->getMultiLayerExtSpsFlag() )
+  {
+    sps->setTemporalIdNestingFlag( (sps->getMaxTLayers() > 1) ? vps->getTemporalNestingFlag() : true );
+  }
 
   if ( sps->getVuiParametersPresentFlag() )
   {
-    sps->getVuiParameters()->inferVideoSignalInfo( vps, rpcSlice->getLayerId() ); 
-  }
-  rpcSlice->setVPS(vps);      
-  rpcSlice->setViewId   ( vps->getViewId   ( rpcSlice->getLayerId() )      );
-  rpcSlice->setViewIndex( vps->getViewIndex( rpcSlice->getLayerId() )      );  
-#if H_3D  
-  rpcSlice->setIsDepth  ( vps->getDepthId  ( rpcSlice->getLayerId() ) == 1 );
-#endif
-#endif
-  rpcSlice->setSPS(sps);
-  rpcSlice->setPPS(pps);
+    sps->getVuiParameters()->inferVideoSignalInfo( vps, pcSlice->getLayerId() ); 
+  }
+
+
+  pcSlice->setVPS(vps);      
+  pcSlice->setSPS(sps);
+  pcSlice->setPPS(pps);
+
+  pcSlice->setViewId   ( vps->getViewId   ( pcSlice->getLayerId() )      );
+  pcSlice->setViewIndex( vps->getViewIndex( pcSlice->getLayerId() )      );  
+#if NH_3D
+  pcSlice->setIsDepth  ( vps->getDepthId  ( pcSlice->getLayerId() ) == 1 );
+#endif
+#endif
+
+  const ChromaFormat chFmt = sps->getChromaFormatIdc();
+  const UInt numValidComp=getNumberValidComponents(chFmt);
+  const Bool bChroma=(chFmt!=CHROMA_400);
+
   if( pps->getDependentSliceSegmentsEnabledFlag() && ( !firstSliceSegmentInPic ))
   {
-    READ_FLAG( uiCode, "dependent_slice_segment_flag" );       rpcSlice->setDependentSliceSegmentFlag(uiCode ? true : false);
+    READ_FLAG( uiCode, "dependent_slice_segment_flag" );       pcSlice->setDependentSliceSegmentFlag(uiCode ? true : false);
   }
   else
   {
-    rpcSlice->setDependentSliceSegmentFlag(false);
+    pcSlice->setDependentSliceSegmentFlag(false);
   }
   Int numCTUs = ((sps->getPicWidthInLumaSamples()+sps->getMaxCUWidth()-1)/sps->getMaxCUWidth())*((sps->getPicHeightInLumaSamples()+sps->getMaxCUHeight()-1)/sps->getMaxCUHeight());
-  Int maxParts = (1<<(sps->getMaxCUDepth()<<1));
   UInt sliceSegmentAddress = 0;
   Int bitsSliceSegmentAddress = 0;
@@ -2009,97 +2241,82 @@
   }
   //set uiCode to equal slice start address (or dependent slice start address)
-  Int startCuAddress = maxParts*sliceSegmentAddress;
-  rpcSlice->setSliceSegmentCurStartCUAddr( startCuAddress );
-  rpcSlice->setSliceSegmentCurEndCUAddr(numCTUs*maxParts);
-
-  if (rpcSlice->getDependentSliceSegmentFlag())
-  {
-    rpcSlice->setNextSlice          ( false );
-    rpcSlice->setNextSliceSegment ( true  );
-  }
-  else
-  {
-    rpcSlice->setNextSlice          ( true  );
-    rpcSlice->setNextSliceSegment ( false );
-
-    rpcSlice->setSliceCurStartCUAddr(startCuAddress);
-    rpcSlice->setSliceCurEndCUAddr(numCTUs*maxParts);
-  }
-  
-#if H_MV
+  pcSlice->setSliceSegmentCurStartCtuTsAddr( sliceSegmentAddress );// this is actually a Raster-Scan (RS) address, but we do not have the RS->TS conversion table defined yet.
+  pcSlice->setSliceSegmentCurEndCtuTsAddr(numCTUs);                // Set end as the last CTU of the picture.
+
+#if NH_MV
     UInt slicePicOrderCntLsb = 0;
 #endif
 
-  if(!rpcSlice->getDependentSliceSegmentFlag())
-  {
-#if H_MV    
+
+  if (!pcSlice->getDependentSliceSegmentFlag())
+  {
+    pcSlice->setSliceCurStartCtuTsAddr(sliceSegmentAddress); // this is actually a Raster-Scan (RS) address, but we do not have the RS->TS conversion table defined yet.
+    pcSlice->setSliceCurEndCtuTsAddr(numCTUs);
+  }
+
+  if(!pcSlice->getDependentSliceSegmentFlag())
+  {
+#if NH_MV    
     Int esb = 0; //Don't use i, otherwise will shadow something below
 
-    if ( rpcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
+    if ( pps->getNumExtraSliceHeaderBits() > esb )
     {
       esb++; 
-      READ_FLAG( uiCode, "discardable_flag" ); rpcSlice->setDiscardableFlag( uiCode == 1 );
+      READ_FLAG( uiCode, "discardable_flag" ); pcSlice->setDiscardableFlag( uiCode == 1 );
       if ( uiCode == 1 )
       {
-        assert(rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
-          rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
-          rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
-          rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
-          rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
-      }
-    }
-
-    if ( rpcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
+        assert(pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
+      }
+    }
+
+    if ( pps->getNumExtraSliceHeaderBits() > esb )
     {
       esb++; 
-      READ_FLAG( uiCode, "cross_layer_bla_flag" ); rpcSlice->setCrossLayerBlaFlag( uiCode == 1 );
-    }
-    rpcSlice->checkCrossLayerBlaFlag( ); 
-
-
-    for (; esb < rpcSlice->getPPS()->getNumExtraSliceHeaderBits(); esb++)    
+      READ_FLAG( uiCode, "cross_layer_bla_flag" ); pcSlice->setCrossLayerBlaFlag( uiCode == 1 );
+    }
+    pcSlice->checkCrossLayerBlaFlag( ); 
+
+
+    for (; esb < pps->getNumExtraSliceHeaderBits(); esb++)    
 #else
-    for (Int i = 0; i < rpcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
-#endif     
-    {
-      READ_FLAG(uiCode, "slice_reserved_undetermined_flag[]"); // ignored
-    }
-
-    READ_UVLC (    uiCode, "slice_type" );            rpcSlice->setSliceType((SliceType)uiCode);
+    for (Int i = 0; i < pps->getNumExtraSliceHeaderBits(); i++)
+#endif
+    {
+      READ_FLAG(uiCode, "slice_reserved_flag[]"); // ignored
+    }
+
+    READ_UVLC (    uiCode, "slice_type" );            pcSlice->setSliceType((SliceType)uiCode);
     if( pps->getOutputFlagPresentFlag() )
     {
-      READ_FLAG( uiCode, "pic_output_flag" );    rpcSlice->setPicOutputFlag( uiCode ? true : false );
+      READ_FLAG( uiCode, "pic_output_flag" );    pcSlice->setPicOutputFlag( uiCode ? true : false );
     }
     else
     {
-      rpcSlice->setPicOutputFlag( true );
-    }
-    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
-
-#if H_3D_DISABLE_CHROMA
-    assert (sps->getChromaFormatIdc() == 1 || rpcSlice->getIsDepth() );
-    assert (sps->getChromaFormatIdc() == 0 || !rpcSlice->getIsDepth() );
-#else
-    assert (sps->getChromaFormatIdc() == 1 );
-#endif
-    // if( separate_colour_plane_flag  ==  1 )
-    //   colour_plane_id                                      u(2)
-
-
-#if H_MV
+      pcSlice->setPicOutputFlag( true );
+    }
+
+    // if (separate_colour_plane_flag == 1)
+    //   read colour_plane_id
+    //   (separate_colour_plane_flag == 1) is not supported in this version of the standard.
+
+#if NH_MV
     Int iPOClsb = slicePicOrderCntLsb;  // Needed later
-    if ( (rpcSlice->getLayerId() > 0 && !vps->getPocLsbNotPresentFlag( rpcSlice->getLayerIdInVps())) || !rpcSlice->getIdrPicFlag() )
+    if ( (pcSlice->getLayerId() > 0 && !vps->getPocLsbNotPresentFlag( pcSlice->getLayerIdInVps())) || !pcSlice->getIdrPicFlag() )
     {
       READ_CODE(sps->getBitsForPOC(), slicePicOrderCntLsb, "slice_pic_order_cnt_lsb");        
     }    
-    rpcSlice->setSlicePicOrderCntLsb( slicePicOrderCntLsb ); 
+    pcSlice->setSlicePicOrderCntLsb( slicePicOrderCntLsb ); 
 
     Bool picOrderCntMSBZeroFlag = false;     
 
     // as in HM code. However are all cases for IRAP picture with NoRaslOutputFlag equal to 1 covered??
-    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ); 
-    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ); 
-    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ); 
-    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag ||   rpcSlice->getIdrPicFlag(); 
+    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ); 
+    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ); 
+    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ); 
+    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag ||   pcSlice->getIdrPicFlag(); 
 
     // TBD picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( rpcSlice->getLayerId() > 0 &&   !rpcSlice->getFirstPicInLayerDecodedFlag() ); 
@@ -2109,5 +2326,5 @@
     if ( !picOrderCntMSBZeroFlag )
     {
-      Int prevPicOrderCnt    = rpcSlice->getPrevTid0POC();
+      Int prevPicOrderCnt    = prevTid0POC;
       Int maxPicOrderCntLsb  = 1 << sps->getBitsForPOC();
       Int prevPicOrderCntLsb = prevPicOrderCnt & (maxPicOrderCntLsb - 1);
@@ -2128,33 +2345,33 @@
     }
       
-    rpcSlice->setPOC( picOrderCntMSB + slicePicOrderCntLsb );
-    if ( rpcSlice->getPocResetFlag() )  
-    {
-      rpcSlice->setPocBeforeReset   ( rpcSlice->getPOC() ); 
-      rpcSlice->setPOC              ( 0 );
+    pcSlice->setPOC( picOrderCntMSB + slicePicOrderCntLsb );
+    if ( pcSlice->getPocResetFlag() )  
+    {
+      pcSlice->setPocBeforeReset   ( pcSlice->getPOC() ); 
+      pcSlice->setPOC              ( 0 );
     }      
 #endif
 
-    if( rpcSlice->getIdrPicFlag() )
-    {
-#if !H_MV
-      rpcSlice->setPOC(0);
-#endif
-      TComReferencePictureSet* rps = rpcSlice->getLocalRPS();
+    if( pcSlice->getIdrPicFlag() )
+    {
+#if !NH_MV
+      pcSlice->setPOC(0);
+#endif
+      TComReferencePictureSet* rps = pcSlice->getLocalRPS();
       rps->setNumberOfNegativePictures(0);
       rps->setNumberOfPositivePictures(0);
       rps->setNumberOfLongtermPictures(0);
       rps->setNumberOfPictures(0);
-      rpcSlice->setRPS(rps);
-#if H_MV
-      rpcSlice->setEnableTMVPFlag(false);
+      pcSlice->setRPS(rps);
+#if NH_MV
+      pcSlice->setEnableTMVPFlag(false);
 #endif
     }
     else
     {
-#if !H_MV
-      READ_CODE(sps->getBitsForPOC(), uiCode, "pic_order_cnt_lsb");  
+#if !NH_MV
+      READ_CODE(sps->getBitsForPOC(), uiCode, "slice_pic_order_cnt_lsb");
       Int iPOClsb = uiCode;
-      Int iPrevPOC = rpcSlice->getPrevTid0POC();
+      Int iPrevPOC = prevTid0POC;
       Int iMaxPOClsb = 1<< sps->getBitsForPOC();
       Int iPrevPOClsb = iPrevPOC & (iMaxPOClsb - 1);
@@ -2165,5 +2382,5 @@
         iPOCmsb = iPrevPOCmsb + iMaxPOClsb;
       }
-      else if( (iPOClsb  >  iPrevPOClsb )  && ( (iPOClsb - iPrevPOClsb )  >  ( iMaxPOClsb / 2 ) ) ) 
+      else if( (iPOClsb  >  iPrevPOClsb )  && ( (iPOClsb - iPrevPOClsb )  >  ( iMaxPOClsb / 2 ) ) )
       {
         iPOCmsb = iPrevPOCmsb - iMaxPOClsb;
@@ -2173,21 +2390,21 @@
         iPOCmsb = iPrevPOCmsb;
       }
-      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
-        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
-        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+      if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+        || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
       {
         // For BLA picture types, POCmsb is set to 0.
         iPOCmsb = 0;
       }
-      rpcSlice->setPOC              (iPOCmsb+iPOClsb);
+      pcSlice->setPOC              (iPOCmsb+iPOClsb);
 #endif
       TComReferencePictureSet* rps;
-      rps = rpcSlice->getLocalRPS();
-      rpcSlice->setRPS(rps);
+      rps = pcSlice->getLocalRPS();
+      pcSlice->setRPS(rps);
       READ_FLAG( uiCode, "short_term_ref_pic_set_sps_flag" );
       if(uiCode == 0) // use short-term reference picture set explicitly signalled in slice header
-      {        
+      {
         parseShortTermRefPicSet(sps,rps, sps->getRPSList()->getNumberOfReferencePictureSets());
-#if H_MV
+#if NH_MV
         if ( !rps->getInterRPSPrediction( ) )
         { // check sum of num_positive_pics and num_negative_pics
@@ -2195,13 +2412,14 @@
             vps->getVpsExtensionFlag(), 
             MAX_INT,  // To be replaced by MaxDbpSize
-            rpcSlice->getLayerId(), 
+            pcSlice->getLayerId(), 
             sps->getMaxDecPicBuffering( sps->getSpsMaxSubLayersMinus1() ) - 1 );
         }
 #endif
+
       }
       else // use reference to short-term reference picture set in PPS
       {
         Int numBits = 0;
-        while ((1 << numBits) < rpcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
+        while ((1 << numBits) < sps->getRPSList()->getNumberOfReferencePictureSets())
         {
           numBits++;
@@ -2214,4 +2432,5 @@
         {
           uiCode = 0;
+       
         }
         *rps = *(sps->getRPSList()->getReferencePictureSet(uiCode));
@@ -2222,5 +2441,5 @@
         UInt numOfLtrp = 0;
         UInt numLtrpInSPS = 0;
-        if (rpcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
+        if (sps->getNumLongTermRefPicSPS() > 0)
         {
           READ_UVLC( uiCode, "num_long_term_sps");
@@ -2230,5 +2449,5 @@
         }
         Int bitsForLtrpInSPS = 0;
-        while (rpcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
+        while (sps->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
         {
           bitsForLtrpInSPS++;
@@ -2237,6 +2456,6 @@
         numOfLtrp += uiCode;
         rps->setNumberOfLongtermPictures(numOfLtrp);
-        Int maxPicOrderCntLSB = 1 << rpcSlice->getSPS()->getBitsForPOC();
-        Int prevDeltaMSB = 0, deltaPocMSBCycleLT = 0;;
+        Int maxPicOrderCntLSB = 1 << sps->getBitsForPOC();
+        Int prevDeltaMSB = 0, deltaPocMSBCycleLT = 0;
         for(Int j=offset+rps->getNumberOfLongtermPictures()-1, k = 0; k < numOfLtrp; j--, k++)
         {
@@ -2249,17 +2468,17 @@
               READ_CODE(bitsForLtrpInSPS, uiCode, "lt_idx_sps[i]");
             }
-            Int usedByCurrFromSPS=rpcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(uiCode);
-
-            pocLsbLt = rpcSlice->getSPS()->getLtRefPicPocLsbSps(uiCode);
+            Bool usedByCurrFromSPS=sps->getUsedByCurrPicLtSPSFlag(uiCode);
+
+            pocLsbLt = sps->getLtRefPicPocLsbSps(uiCode);
             rps->setUsed(j,usedByCurrFromSPS);
           }
           else
           {
-            READ_CODE(rpcSlice->getSPS()->getBitsForPOC(), uiCode, "poc_lsb_lt"); pocLsbLt= uiCode;
+            READ_CODE(sps->getBitsForPOC(), uiCode, "poc_lsb_lt"); pocLsbLt= uiCode;
             READ_FLAG( uiCode, "used_by_curr_pic_lt_flag");     rps->setUsed(j,uiCode);
           }
           READ_FLAG(uiCode,"delta_poc_msb_present_flag");
           Bool mSBPresentFlag = uiCode ? true : false;
-          if(mSBPresentFlag)                  
+          if(mSBPresentFlag)
           {
             READ_UVLC( uiCode, "delta_poc_msb_cycle_lt[i]" );
@@ -2276,19 +2495,19 @@
             else
             {
-              deltaPocMSBCycleLT = uiCode + prevDeltaMSB;              
+              deltaPocMSBCycleLT = uiCode + prevDeltaMSB;
             }
 
-            Int pocLTCurr = rpcSlice->getPOC() - deltaPocMSBCycleLT * maxPicOrderCntLSB 
+            Int pocLTCurr = pcSlice->getPOC() - deltaPocMSBCycleLT * maxPicOrderCntLSB
                                         - iPOClsb + pocLsbLt;
-            rps->setPOC     (j, pocLTCurr); 
-            rps->setDeltaPOC(j, - rpcSlice->getPOC() + pocLTCurr);
-            rps->setCheckLTMSBPresent(j,true);  
+            rps->setPOC     (j, pocLTCurr);
+            rps->setDeltaPOC(j, - pcSlice->getPOC() + pocLTCurr);
+            rps->setCheckLTMSBPresent(j,true);
           }
           else
           {
             rps->setPOC     (j, pocLsbLt);
-            rps->setDeltaPOC(j, - rpcSlice->getPOC() + pocLsbLt);
-            rps->setCheckLTMSBPresent(j,false);  
-            
+            rps->setDeltaPOC(j, - pcSlice->getPOC() + pocLsbLt);
+            rps->setCheckLTMSBPresent(j,false);
+
             // reset deltaPocMSBCycleLT for first LTRP from slice header if MSB not present
             if( j == offset+(numOfLtrp-numLtrpInSPS)-1 )
@@ -2300,7 +2519,7 @@
         }
         offset += rps->getNumberOfLongtermPictures();
-        rps->setNumberOfPictures(offset);        
-      }  
-#if H_MV
+        rps->setNumberOfPictures(offset);
+      }
+#if NH_MV
       if ( !rps->getInterRPSPrediction( ) )
       { // check sum of NumPositivePics, NumNegativePics, num_long_term_sps and num_long_term_pics 
@@ -2308,64 +2527,65 @@
           vps->getVpsExtensionFlag(), 
             MAX_INT,  // To be replaced by MaxDbpsize
-          rpcSlice->getLayerId(), 
+          pcSlice->getLayerId(), 
           sps->getMaxDecPicBuffering( sps->getSpsMaxSubLayersMinus1() ) - 1 );
       }
 #endif
-      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
-        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
-        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+
+      if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+        || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
       {
         // In the case of BLA picture types, rps data is read from slice header but ignored
-        rps = rpcSlice->getLocalRPS();
+        rps = pcSlice->getLocalRPS();
         rps->setNumberOfNegativePictures(0);
         rps->setNumberOfPositivePictures(0);
         rps->setNumberOfLongtermPictures(0);
         rps->setNumberOfPictures(0);
-        rpcSlice->setRPS(rps);
-      }
-      if (rpcSlice->getSPS()->getTMVPFlagsPresent())
-      {
-#if H_MV
+        pcSlice->setRPS(rps);
+      }
+      if (sps->getTMVPFlagsPresent())
+      {
+#if NH_MV
         READ_FLAG( uiCode, "slice_temporal_mvp_enabled_flag" );
 #else
-        READ_FLAG( uiCode, "slice_temporal_mvp_enable_flag" );
-#endif
-        rpcSlice->setEnableTMVPFlag( uiCode == 1 ? true : false ); 
+        READ_FLAG( uiCode, "slice_temporal_mvp_enabled_flag" );
+#endif
+        pcSlice->setEnableTMVPFlag( uiCode == 1 ? true : false );
       }
       else
       {
-        rpcSlice->setEnableTMVPFlag(false);
-      }
-    }
-#if H_MV
+        pcSlice->setEnableTMVPFlag(false);
+      }
+    }
+#if NH_MV
     Bool interLayerPredLayerIdcPresentFlag = false; 
-    Int layerId       = rpcSlice->getLayerId(); 
-#if H_3D
-    if( rpcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumRefListLayers( layerId ) > 0 )
+    Int layerId       = pcSlice->getLayerId(); 
+#if NH_3D
+    if( pcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumRefListLayers( layerId ) > 0 )
 #else
-    if( rpcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumDirectRefLayers( layerId ) > 0 )
+    if( pcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumDirectRefLayers( layerId ) > 0 )
 #endif
     {   
-      READ_FLAG( uiCode, "inter_layer_pred_enabled_flag" ); rpcSlice->setInterLayerPredEnabledFlag( uiCode == 1 );
-#if H_3D
-      if( rpcSlice->getInterLayerPredEnabledFlag() && vps->getNumRefListLayers( layerId ) > 1 )
+      READ_FLAG( uiCode, "inter_layer_pred_enabled_flag" ); pcSlice->setInterLayerPredEnabledFlag( uiCode == 1 );
+#if NH_3D
+      if( pcSlice->getInterLayerPredEnabledFlag() && vps->getNumRefListLayers( layerId ) > 1 )
 #else
-      if( rpcSlice->getInterLayerPredEnabledFlag() && vps->getNumDirectRefLayers( layerId ) > 1 )
+      if( pcSlice->getInterLayerPredEnabledFlag() && vps->getNumDirectRefLayers( layerId ) > 1 )
 #endif
       {            
         if( !vps->getMaxOneActiveRefLayerFlag())  
         {
-          READ_CODE( rpcSlice->getNumInterLayerRefPicsMinus1Len( ), uiCode, "num_inter_layer_ref_pics_minus1" ); rpcSlice->setNumInterLayerRefPicsMinus1( uiCode );
-        }
-#if H_3D
-        if ( rpcSlice->getNumActiveRefLayerPics() != vps->getNumRefListLayers( layerId ) )
+          READ_CODE( pcSlice->getNumInterLayerRefPicsMinus1Len( ), uiCode, "num_inter_layer_ref_pics_minus1" ); pcSlice->setNumInterLayerRefPicsMinus1( uiCode );
+        }
+#if NH_3D
+        if ( pcSlice->getNumActiveRefLayerPics() != vps->getNumRefListLayers( layerId ) )
 #else
-        if ( rpcSlice->getNumActiveRefLayerPics() != vps->getNumDirectRefLayers( layerId ) )
+        if ( pcSlice->getNumActiveRefLayerPics() != vps->getNumDirectRefLayers( layerId ) )
 #endif
         {
           interLayerPredLayerIdcPresentFlag = true; 
-          for( Int idx = 0; idx < rpcSlice->getNumActiveRefLayerPics(); idx++ )   
+          for( Int idx = 0; idx < pcSlice->getNumActiveRefLayerPics(); idx++ )   
           {
-            READ_CODE( rpcSlice->getInterLayerPredLayerIdcLen( ), uiCode, "inter_layer_pred_layer_idc" ); rpcSlice->setInterLayerPredLayerIdc( idx, uiCode );
+            READ_CODE( pcSlice->getInterLayerPredLayerIdcLen( ), uiCode, "inter_layer_pred_layer_idc" ); pcSlice->setInterLayerPredLayerIdc( idx, uiCode );
           }
         }
@@ -2374,18 +2594,18 @@
     if ( !interLayerPredLayerIdcPresentFlag )
     {
-      for( Int i = 0; i < rpcSlice->getNumActiveRefLayerPics(); i++ )   
-      {
-        rpcSlice->setInterLayerPredLayerIdc( i, rpcSlice->getRefLayerPicIdc( i ) );
-      }
-    }
-#if H_3D
+      for( Int i = 0; i < pcSlice->getNumActiveRefLayerPics(); i++ )   
+      {
+        pcSlice->setInterLayerPredLayerIdc( i, pcSlice->getRefLayerPicIdc( i ) );
+      }
+    }
+#if NH_3D
     if ( getDecTop()->decProcAnnexI() )
     {    
-      rpcSlice->deriveInCmpPredAndCpAvailFlag();
-      if ( rpcSlice->getInCmpPredAvailFlag() )
-      {
-        READ_FLAG(uiCode, "in_comp_pred_flag");  rpcSlice->setInCompPredFlag((Bool)uiCode);      
-      }
-      rpcSlice->init3dToolParameters(); 
+      pcSlice->deriveInCmpPredAndCpAvailFlag( );
+      if ( pcSlice->getInCmpPredAvailFlag() )
+      {
+        READ_FLAG(uiCode, "in_comp_pred_flag");  pcSlice->setInCompPredFlag((Bool)uiCode);      
+      }
+      pcSlice->init3dToolParameters(); 
     }
 #endif
@@ -2393,24 +2613,17 @@
     if(sps->getUseSAO())
     {
-      READ_FLAG(uiCode, "slice_sao_luma_flag");  rpcSlice->setSaoEnabledFlag((Bool)uiCode);
-#if H_3D_DISABLE_CHROMA
-      if( rpcSlice->getSPS()->getChromaFormatIdc() != 0 )
-      {
-        READ_FLAG(uiCode, "slice_sao_chroma_flag");  rpcSlice->setSaoEnabledFlagChroma((Bool)uiCode);
-      }
-      else
-      {
-        rpcSlice->setSaoEnabledFlagChroma( false );
-      }
-#else
-      READ_FLAG(uiCode, "slice_sao_chroma_flag");  rpcSlice->setSaoEnabledFlagChroma((Bool)uiCode);
-#endif
-    }
-
-    if (rpcSlice->getIdrPicFlag())
-    {
-      rpcSlice->setEnableTMVPFlag(false);
-    }
-    if (!rpcSlice->isIntra())
+      READ_FLAG(uiCode, "slice_sao_luma_flag");  pcSlice->setSaoEnabledFlag(CHANNEL_TYPE_LUMA, (Bool)uiCode);
+
+      if (bChroma)
+      {
+        READ_FLAG(uiCode, "slice_sao_chroma_flag");  pcSlice->setSaoEnabledFlag(CHANNEL_TYPE_CHROMA, (Bool)uiCode);
+      }
+    }
+
+    if (pcSlice->getIdrPicFlag())
+    {
+      pcSlice->setEnableTMVPFlag(false);
+    }
+    if (!pcSlice->isIntra())
     {
 
@@ -2418,32 +2631,32 @@
       if (uiCode)
       {
-        READ_UVLC (uiCode, "num_ref_idx_l0_active_minus1" );  rpcSlice->setNumRefIdx( REF_PIC_LIST_0, uiCode + 1 );
-        if (rpcSlice->isInterB())
-        {
-          READ_UVLC (uiCode, "num_ref_idx_l1_active_minus1" );  rpcSlice->setNumRefIdx( REF_PIC_LIST_1, uiCode + 1 );
+        READ_UVLC (uiCode, "num_ref_idx_l0_active_minus1" );  pcSlice->setNumRefIdx( REF_PIC_LIST_0, uiCode + 1 );
+        if (pcSlice->isInterB())
+        {
+          READ_UVLC (uiCode, "num_ref_idx_l1_active_minus1" );  pcSlice->setNumRefIdx( REF_PIC_LIST_1, uiCode + 1 );
         }
         else
         {
-          rpcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
         }
       }
       else
       {
-        rpcSlice->setNumRefIdx(REF_PIC_LIST_0, rpcSlice->getPPS()->getNumRefIdxL0DefaultActive());
-        if (rpcSlice->isInterB())
-        {
-          rpcSlice->setNumRefIdx(REF_PIC_LIST_1, rpcSlice->getPPS()->getNumRefIdxL1DefaultActive());
+        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pps->getNumRefIdxL0DefaultActive());
+        if (pcSlice->isInterB())
+        {
+          pcSlice->setNumRefIdx(REF_PIC_LIST_1, pps->getNumRefIdxL1DefaultActive());
         }
         else
         {
-          rpcSlice->setNumRefIdx(REF_PIC_LIST_1,0);
+          pcSlice->setNumRefIdx(REF_PIC_LIST_1,0);
         }
       }
     }
     // }
-    TComRefPicListModification* refPicListModification = rpcSlice->getRefPicListModification();
-    if(!rpcSlice->isIntra())
-    {
-      if( !rpcSlice->getPPS()->getListsModificationPresentFlag() || rpcSlice->getNumRpsCurrTempList() <= 1 )
+    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+    if(!pcSlice->isIntra())
+    {
+      if( !pps->getListsModificationPresentFlag() || pcSlice->getNumRpsCurrTempList() <= 1 )
       {
         refPicListModification->setRefPicListModificationFlagL0( 0 );
@@ -2455,17 +2668,17 @@
 
       if(refPicListModification->getRefPicListModificationFlagL0())
-      { 
+      {
         uiCode = 0;
         Int i = 0;
-        Int numRpsCurrTempList0 = rpcSlice->getNumRpsCurrTempList();
+        Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
         if ( numRpsCurrTempList0 > 1 )
         {
           Int length = 1;
           numRpsCurrTempList0 --;
-          while ( numRpsCurrTempList0 >>= 1) 
+          while ( numRpsCurrTempList0 >>= 1)
           {
             length ++;
           }
-          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          for (i = 0; i < pcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
           {
             READ_CODE( length, uiCode, "list_entry_l0" );
@@ -2475,5 +2688,5 @@
         else
         {
-          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          for (i = 0; i < pcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
           {
             refPicListModification->setRefPicSetIdxL0(i, 0 );
@@ -2486,7 +2699,7 @@
       refPicListModification->setRefPicListModificationFlagL0(0);
     }
-    if(rpcSlice->isInterB())
-    {
-      if( !rpcSlice->getPPS()->getListsModificationPresentFlag() || rpcSlice->getNumRpsCurrTempList() <= 1 )
+    if(pcSlice->isInterB())
+    {
+      if( !pps->getListsModificationPresentFlag() || pcSlice->getNumRpsCurrTempList() <= 1 )
       {
         refPicListModification->setRefPicListModificationFlagL1( 0 );
@@ -2500,14 +2713,14 @@
         uiCode = 0;
         Int i = 0;
-        Int numRpsCurrTempList1 = rpcSlice->getNumRpsCurrTempList();
+        Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
         if ( numRpsCurrTempList1 > 1 )
         {
           Int length = 1;
           numRpsCurrTempList1 --;
-          while ( numRpsCurrTempList1 >>= 1) 
+          while ( numRpsCurrTempList1 >>= 1)
           {
             length ++;
           }
-          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          for (i = 0; i < pcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
           {
             READ_CODE( length, uiCode, "list_entry_l1" );
@@ -2517,5 +2730,5 @@
         else
         {
-          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          for (i = 0; i < pcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
           {
             refPicListModification->setRefPicSetIdxL1(i, 0 );
@@ -2523,53 +2736,54 @@
         }
       }
-    }  
+    }
     else
     {
       refPicListModification->setRefPicListModificationFlagL1(0);
     }
-    if (rpcSlice->isInterB())
-    {
-      READ_FLAG( uiCode, "mvd_l1_zero_flag" );       rpcSlice->setMvdL1ZeroFlag( (uiCode ? true : false) );
-    }
-
-    rpcSlice->setCabacInitFlag( false ); // default
-    if(pps->getCabacInitPresentFlag() && !rpcSlice->isIntra())
+    if (pcSlice->isInterB())
+    {
+      READ_FLAG( uiCode, "mvd_l1_zero_flag" );       pcSlice->setMvdL1ZeroFlag( (uiCode ? true : false) );
+    }
+
+    pcSlice->setCabacInitFlag( false ); // default
+    if(pps->getCabacInitPresentFlag() && !pcSlice->isIntra())
     {
       READ_FLAG(uiCode, "cabac_init_flag");
-      rpcSlice->setCabacInitFlag( uiCode ? true : false );
-    }
-
-    if ( rpcSlice->getEnableTMVPFlag() )
-    {
-      if ( rpcSlice->getSliceType() == B_SLICE )
+      pcSlice->setCabacInitFlag( uiCode ? true : false );
+    }
+
+    if ( pcSlice->getEnableTMVPFlag() )
+    {
+      if ( pcSlice->getSliceType() == B_SLICE )
       {
         READ_FLAG( uiCode, "collocated_from_l0_flag" );
-        rpcSlice->setColFromL0Flag(uiCode);
+        pcSlice->setColFromL0Flag(uiCode);
       }
       else
       {
-        rpcSlice->setColFromL0Flag( 1 );
-      }
-
-      if ( rpcSlice->getSliceType() != I_SLICE &&
-          ((rpcSlice->getColFromL0Flag() == 1 && rpcSlice->getNumRefIdx(REF_PIC_LIST_0) > 1)||
-           (rpcSlice->getColFromL0Flag() == 0 && rpcSlice->getNumRefIdx(REF_PIC_LIST_1) > 1)))
+        pcSlice->setColFromL0Flag( 1 );
+      }
+
+      if ( pcSlice->getSliceType() != I_SLICE &&
+          ((pcSlice->getColFromL0Flag() == 1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0) > 1)||
+           (pcSlice->getColFromL0Flag() == 0 && pcSlice->getNumRefIdx(REF_PIC_LIST_1) > 1)))
       {
         READ_UVLC( uiCode, "collocated_ref_idx" );
-        rpcSlice->setColRefIdx(uiCode);
+        pcSlice->setColRefIdx(uiCode);
       }
       else
       {
-        rpcSlice->setColRefIdx(0);
-      }
-    }
-    if ( (pps->getUseWP() && rpcSlice->getSliceType()==P_SLICE) || (pps->getWPBiPred() && rpcSlice->getSliceType()==B_SLICE) )
-    {
-      xParsePredWeightTable(rpcSlice);
-      rpcSlice->initWpScaling();
-    }
+        pcSlice->setColRefIdx(0);
+      }
+    }
+    if ( (pps->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pps->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
+    {
+      xParsePredWeightTable(pcSlice, sps);
+      pcSlice->initWpScaling(sps);
+    }
+
 #if H_3D_IC
-    else if(    rpcSlice->getViewIndex() && ( rpcSlice->getSliceType() == P_SLICE || rpcSlice->getSliceType() == B_SLICE ) 
-             && !rpcSlice->getIsDepth() && vps->getNumRefListLayers( layerId ) > 0 
+    else if(    pcSlice->getViewIndex() && ( pcSlice->getSliceType() == P_SLICE || pcSlice->getSliceType() == B_SLICE ) 
+             && !pcSlice->getIsDepth() && vps->getNumRefListLayers( layerId ) > 0 
              && getDecTop()->decProcAnnexI()
            )
@@ -2578,87 +2792,103 @@
 
       READ_FLAG ( uiCodeTmp, "slice_ic_enable_flag" );
-      rpcSlice->setApplyIC( uiCodeTmp );
+      pcSlice->setApplyIC( uiCodeTmp );
 
       if ( uiCodeTmp )
       {
         READ_FLAG ( uiCodeTmp, "ic_skip_mergeidx0" );
-        rpcSlice->setIcSkipParseFlag( uiCodeTmp );
-      }
-    }
-#endif
-    if (!rpcSlice->isIntra())
+        pcSlice->setIcSkipParseFlag( uiCodeTmp );
+      }
+    }
+#endif
+
+    if (!pcSlice->isIntra())
     {
       READ_UVLC( uiCode, "five_minus_max_num_merge_cand");
 #if H_3D_IV_MERGE
-      rpcSlice->setMaxNumMergeCand(( ( rpcSlice->getMpiFlag() || rpcSlice->getIvMvPredFlag() || rpcSlice->getViewSynthesisPredFlag() ) ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS) - uiCode);
+      pcSlice->setMaxNumMergeCand(( ( pcSlice->getMpiFlag() || pcSlice->getIvMvPredFlag() || pcSlice->getViewSynthesisPredFlag() ) ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS) - uiCode);
 #else
-      rpcSlice->setMaxNumMergeCand(MRG_MAX_NUM_CANDS - uiCode);
+      pcSlice->setMaxNumMergeCand(MRG_MAX_NUM_CANDS - uiCode);
 #endif
     }
 
     READ_SVLC( iCode, "slice_qp_delta" );
-    rpcSlice->setSliceQp (26 + pps->getPicInitQPMinus26() + iCode);
-
-    assert( rpcSlice->getSliceQp() >= -sps->getQpBDOffsetY() );
-    assert( rpcSlice->getSliceQp() <=  51 );
-
-    if (rpcSlice->getPPS()->getSliceChromaQpFlag())
-    {
-      READ_SVLC( iCode, "slice_qp_delta_cb" );
-      rpcSlice->setSliceQpDeltaCb( iCode );
-      assert( rpcSlice->getSliceQpDeltaCb() >= -12 );
-      assert( rpcSlice->getSliceQpDeltaCb() <=  12 );
-      assert( (rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb()) >= -12 );
-      assert( (rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb()) <=  12 );
-
-      READ_SVLC( iCode, "slice_qp_delta_cr" );
-      rpcSlice->setSliceQpDeltaCr( iCode );
-      assert( rpcSlice->getSliceQpDeltaCr() >= -12 );
-      assert( rpcSlice->getSliceQpDeltaCr() <=  12 );
-      assert( (rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr()) >= -12 );
-      assert( (rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr()) <=  12 );
-    }
-
-    if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
-    {
-      if(rpcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag())
-      {
-        READ_FLAG ( uiCode, "deblocking_filter_override_flag" );        rpcSlice->setDeblockingFilterOverrideFlag(uiCode ? true : false);
+    pcSlice->setSliceQp (26 + pps->getPicInitQPMinus26() + iCode);
+
+    assert( pcSlice->getSliceQp() >= -sps->getQpBDOffset(CHANNEL_TYPE_LUMA) );
+    assert( pcSlice->getSliceQp() <=  51 );
+
+    if (pps->getSliceChromaQpFlag())
+    {
+      if (numValidComp>COMPONENT_Cb)
+      {
+        READ_SVLC( iCode, "slice_cb_qp_offset" );
+        pcSlice->setSliceChromaQpDelta(COMPONENT_Cb, iCode );
+        assert( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb) >= -12 );
+        assert( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb) <=  12 );
+        assert( (pps->getQpOffset(COMPONENT_Cb) + pcSlice->getSliceChromaQpDelta(COMPONENT_Cb)) >= -12 );
+        assert( (pps->getQpOffset(COMPONENT_Cb) + pcSlice->getSliceChromaQpDelta(COMPONENT_Cb)) <=  12 );
+      }
+
+      if (numValidComp>COMPONENT_Cr)
+      {
+        READ_SVLC( iCode, "slice_cr_qp_offset" );
+        pcSlice->setSliceChromaQpDelta(COMPONENT_Cr, iCode );
+        assert( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr) >= -12 );
+        assert( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr) <=  12 );
+        assert( (pps->getQpOffset(COMPONENT_Cr) + pcSlice->getSliceChromaQpDelta(COMPONENT_Cr)) >= -12 );
+        assert( (pps->getQpOffset(COMPONENT_Cr) + pcSlice->getSliceChromaQpDelta(COMPONENT_Cr)) <=  12 );
+      }
+    }
+
+    if (pps->getPpsRangeExtension().getChromaQpOffsetListEnabledFlag())
+    {
+      READ_FLAG(uiCode, "cu_chroma_qp_offset_enabled_flag"); pcSlice->setUseChromaQpAdj(uiCode != 0);
+    }
+    else
+    {
+      pcSlice->setUseChromaQpAdj(false);
+    }
+
+    if (pps->getDeblockingFilterControlPresentFlag())
+    {
+      if(pps->getDeblockingFilterOverrideEnabledFlag())
+      {
+        READ_FLAG ( uiCode, "deblocking_filter_override_flag" );        pcSlice->setDeblockingFilterOverrideFlag(uiCode ? true : false);
       }
       else
-      {  
-        rpcSlice->setDeblockingFilterOverrideFlag(0);
-      }
-      if(rpcSlice->getDeblockingFilterOverrideFlag())
-      {
-        READ_FLAG ( uiCode, "slice_disable_deblocking_filter_flag" );   rpcSlice->setDeblockingFilterDisable(uiCode ? 1 : 0);
-        if(!rpcSlice->getDeblockingFilterDisable())
-        {
-          READ_SVLC( iCode, "slice_beta_offset_div2" );                       rpcSlice->setDeblockingFilterBetaOffsetDiv2(iCode);
-          assert(rpcSlice->getDeblockingFilterBetaOffsetDiv2() >= -6 &&
-                 rpcSlice->getDeblockingFilterBetaOffsetDiv2() <=  6);
-          READ_SVLC( iCode, "slice_tc_offset_div2" );                         rpcSlice->setDeblockingFilterTcOffsetDiv2(iCode);
-          assert(rpcSlice->getDeblockingFilterTcOffsetDiv2() >= -6 &&
-                 rpcSlice->getDeblockingFilterTcOffsetDiv2() <=  6);
+      {
+        pcSlice->setDeblockingFilterOverrideFlag(0);
+      }
+      if(pcSlice->getDeblockingFilterOverrideFlag())
+      {
+        READ_FLAG ( uiCode, "slice_disable_deblocking_filter_flag" );   pcSlice->setDeblockingFilterDisable(uiCode ? 1 : 0);
+        if(!pcSlice->getDeblockingFilterDisable())
+        {
+          READ_SVLC( iCode, "slice_beta_offset_div2" );                       pcSlice->setDeblockingFilterBetaOffsetDiv2(iCode);
+          assert(pcSlice->getDeblockingFilterBetaOffsetDiv2() >= -6 &&
+                 pcSlice->getDeblockingFilterBetaOffsetDiv2() <=  6);
+          READ_SVLC( iCode, "slice_tc_offset_div2" );                         pcSlice->setDeblockingFilterTcOffsetDiv2(iCode);
+          assert(pcSlice->getDeblockingFilterTcOffsetDiv2() >= -6 &&
+                 pcSlice->getDeblockingFilterTcOffsetDiv2() <=  6);
         }
       }
       else
       {
-        rpcSlice->setDeblockingFilterDisable   ( rpcSlice->getPPS()->getPicDisableDeblockingFilterFlag() );
-        rpcSlice->setDeblockingFilterBetaOffsetDiv2( rpcSlice->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
-        rpcSlice->setDeblockingFilterTcOffsetDiv2  ( rpcSlice->getPPS()->getDeblockingFilterTcOffsetDiv2() );
+        pcSlice->setDeblockingFilterDisable   ( pps->getPicDisableDeblockingFilterFlag() );
+        pcSlice->setDeblockingFilterBetaOffsetDiv2( pps->getDeblockingFilterBetaOffsetDiv2() );
+        pcSlice->setDeblockingFilterTcOffsetDiv2  ( pps->getDeblockingFilterTcOffsetDiv2() );
       }
     }
     else
-    {  
-      rpcSlice->setDeblockingFilterDisable       ( false );
-      rpcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
-      rpcSlice->setDeblockingFilterTcOffsetDiv2  ( 0 );
-    }
-
-    Bool isSAOEnabled = (!rpcSlice->getSPS()->getUseSAO())?(false):(rpcSlice->getSaoEnabledFlag()||rpcSlice->getSaoEnabledFlagChroma());
-    Bool isDBFEnabled = (!rpcSlice->getDeblockingFilterDisable());
-
-    if(rpcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
+    {
+      pcSlice->setDeblockingFilterDisable       ( false );
+      pcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
+      pcSlice->setDeblockingFilterTcOffsetDiv2  ( 0 );
+    }
+
+    Bool isSAOEnabled = sps->getUseSAO() && (pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA) || (bChroma && pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA)));
+    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
+
+    if(pps->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
     {
       READ_FLAG( uiCode, "slice_loop_filter_across_slices_enabled_flag");
@@ -2666,125 +2896,129 @@
     else
     {
-      uiCode = rpcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()?1:0;
-    }
-    rpcSlice->setLFCrossSliceBoundaryFlag( (uiCode==1)?true:false);
-
-#if H_3D
+      uiCode = pps->getLoopFilterAcrossSlicesEnabledFlag()?1:0;
+    }
+    pcSlice->setLFCrossSliceBoundaryFlag( (uiCode==1)?true:false);
+
+#if NH_3D
     if ( getDecTop()->decProcAnnexI() )
     {
-      Int voiInVps = vps->getVoiInVps( rpcSlice->getViewIndex() ); 
-      if( vps->getCpInSliceSegmentHeaderFlag( voiInVps ) && !rpcSlice->getIsDepth() )
+      Int voiInVps = vps->getVoiInVps( pcSlice->getViewIndex() ); 
+      if( vps->getCpInSliceSegmentHeaderFlag( voiInVps ) && !pcSlice->getIsDepth() )
       {
         for( Int m = 0; m < vps->getNumCp( voiInVps ); m++ )
         {
           Int jInVps = vps->getVoiInVps( vps->getCpRefVoi( voiInVps, m ));
-          READ_SVLC( iCode, "cp_scale" );                rpcSlice->setCpScale   ( jInVps, iCode );
-          READ_SVLC( iCode, "cp_off" );                  rpcSlice->setCpOff     ( jInVps, iCode );
-          READ_SVLC( iCode, "cp_inv_scale_plus_scale" ); rpcSlice->setCpInvScale( jInVps, iCode - rpcSlice->getCpScale   ( jInVps ));
-          READ_SVLC( iCode, "cp_inv_off_plus_off" );     rpcSlice->setCpInvOff  ( jInVps, iCode - rpcSlice->getCpOff     ( jInVps ));
-        }
-      }
-    }
-#endif
-  }
-  
-    UInt *entryPointOffset          = NULL;
-    UInt numEntryPointOffsets, offsetLenMinus1;
+          READ_SVLC( iCode, "cp_scale" );                pcSlice->setCpScale   ( jInVps, iCode );
+          READ_SVLC( iCode, "cp_off" );                  pcSlice->setCpOff     ( jInVps, iCode );
+          READ_SVLC( iCode, "cp_inv_scale_plus_scale" ); pcSlice->setCpInvScale( jInVps, iCode - pcSlice->getCpScale   ( jInVps ));
+          READ_SVLC( iCode, "cp_inv_off_plus_off" );     pcSlice->setCpInvOff  ( jInVps, iCode - pcSlice->getCpOff     ( jInVps ));
+        }
+      }
+    }
+#endif
+
+  }
+
+  std::vector<UInt> entryPointOffset;
   if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
   {
-    READ_UVLC(numEntryPointOffsets, "num_entry_point_offsets"); rpcSlice->setNumEntryPointOffsets ( numEntryPointOffsets );
+    UInt numEntryPointOffsets;
+    UInt offsetLenMinus1;
+    READ_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
     if (numEntryPointOffsets>0)
     {
       READ_UVLC(offsetLenMinus1, "offset_len_minus1");
-    }
-    entryPointOffset = new UInt[numEntryPointOffsets];
-    for (UInt idx=0; idx<numEntryPointOffsets; idx++)
-    {
-      READ_CODE(offsetLenMinus1+1, uiCode, "entry_point_offset_minus1");
-      entryPointOffset[ idx ] = uiCode + 1;
-    }
-  }
-  else
-  {
-    rpcSlice->setNumEntryPointOffsets ( 0 );
-  }
-
+      entryPointOffset.resize(numEntryPointOffsets);
+      for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+      {
+        READ_CODE(offsetLenMinus1+1, uiCode, "entry_point_offset_minus1");
+        entryPointOffset[ idx ] = uiCode + 1;
+      }
+    }
+  }
 
   if(pps->getSliceHeaderExtensionPresentFlag())
   {
-#if H_MV
-    READ_UVLC( uiCode, "slice_segment_header_extension_length" ); rpcSlice->setSliceSegmentHeaderExtensionLength( uiCode );
+#if NH_MV
+    READ_UVLC( uiCode, "slice_segment_header_extension_length" ); pcSlice->setSliceSegmentHeaderExtensionLength( uiCode );
     UInt posFollSliceSegHeaderExtLen = m_pcBitstream->getNumBitsRead();
 
-    if( rpcSlice->getPPS()->getPocResetInfoPresentFlag() )
-    {
-      READ_CODE( 2, uiCode, "poc_reset_idc" ); rpcSlice->setPocResetIdc( uiCode );
+    if( pps->getPocResetInfoPresentFlag() )
+    {
+      READ_CODE( 2, uiCode, "poc_reset_idc" ); pcSlice->setPocResetIdc( uiCode );
     }
     else
     {
-      rpcSlice->setPocResetIdc( 0 );
-    }
-    rpcSlice->checkPocResetIdc(); 
-
-    if ( rpcSlice->getVPS()->getPocLsbNotPresentFlag(rpcSlice->getLayerId()) && slicePicOrderCntLsb > 0 )
-    {
-      assert( rpcSlice->getPocResetIdc() != 2 );
-    }
-
-    if( rpcSlice->getPocResetIdc() !=  0 )
-    {
-      READ_CODE( 6, uiCode, "poc_reset_period_id" ); rpcSlice->setPocResetPeriodId( uiCode );
+      pcSlice->setPocResetIdc( 0 );
+    }
+    pcSlice->checkPocResetIdc(); 
+
+    if ( pcSlice->getVPS()->getPocLsbNotPresentFlag(pcSlice->getLayerId()) && slicePicOrderCntLsb > 0 )
+    {
+      assert( pcSlice->getPocResetIdc() != 2 );
+    }
+
+    if( pcSlice->getPocResetIdc() !=  0 )
+    {
+      READ_CODE( 6, uiCode, "poc_reset_period_id" ); pcSlice->setPocResetPeriodId( uiCode );
     }
     else
     {
       // TODO Copy poc_reset_period from earlier picture
-      rpcSlice->setPocResetPeriodId( 0 );
+      pcSlice->setPocResetPeriodId( 0 );
     }
     
-    if( rpcSlice->getPocResetIdc() ==  3 ) 
-    {
-      READ_FLAG( uiCode, "full_poc_reset_flag" ); rpcSlice->setFullPocResetFlag( uiCode == 1 );
-      READ_CODE( rpcSlice->getPocLsbValLen() , uiCode, "poc_lsb_val" ); rpcSlice->setPocLsbVal( uiCode );
+    if( pcSlice->getPocResetIdc() ==  3 ) 
+    {
+      READ_FLAG( uiCode, "full_poc_reset_flag" ); pcSlice->setFullPocResetFlag( uiCode == 1 );
+      READ_CODE( pcSlice->getPocLsbValLen() , uiCode, "poc_lsb_val" ); pcSlice->setPocLsbVal( uiCode );
     }          
-    rpcSlice->checkPocLsbVal(); 
+    pcSlice->checkPocLsbVal(); 
 
     // Derive the value of PocMs8bValRequiredFlag
 
-    if( !rpcSlice->getPocMsbValRequiredFlag() && rpcSlice->getVPS()->getVpsPocLsbAlignedFlag() )
-    {
-      READ_FLAG( uiCode, "poc_msb_val_present_flag" ); rpcSlice->setPocMsbValPresentFlag( uiCode == 1 );
+    if( !pcSlice->getPocMsbValRequiredFlag() && pcSlice->getVPS()->getVpsPocLsbAlignedFlag() )
+    {
+      READ_FLAG( uiCode, "poc_msb_val_present_flag" ); pcSlice->setPocMsbValPresentFlag( uiCode == 1 );
     }
     else
     {
-      rpcSlice->setPocMsbValPresentFlag( rpcSlice->inferPocMsbValPresentFlag( ) ); 
+      pcSlice->setPocMsbValPresentFlag( pcSlice->inferPocMsbValPresentFlag( ) ); 
     }
 
     
-    if( rpcSlice->getPocMsbValPresentFlag() )
-    {
-      READ_UVLC( uiCode, "poc_msb_val" ); rpcSlice->setPocMsbVal( uiCode );
-    }
-
-    while( ( m_pcBitstream->getNumBitsRead() - posFollSliceSegHeaderExtLen ) < rpcSlice->getSliceSegmentHeaderExtensionLength() * 8 )
+    if( pcSlice->getPocMsbValPresentFlag() )
+    {
+      READ_UVLC( uiCode, "poc_msb_val" ); pcSlice->setPocMsbVal( uiCode );
+    }
+
+    while( ( m_pcBitstream->getNumBitsRead() - posFollSliceSegHeaderExtLen ) < pcSlice->getSliceSegmentHeaderExtensionLength() * 8 )
     {
      READ_FLAG( uiCode, "slice_segment_header_extension_data_bit" );
     }
-    assert( ( m_pcBitstream->getNumBitsRead() - posFollSliceSegHeaderExtLen ) == rpcSlice->getSliceSegmentHeaderExtensionLength() * 8  ); 
+    assert( ( m_pcBitstream->getNumBitsRead() - posFollSliceSegHeaderExtLen ) == pcSlice->getSliceSegmentHeaderExtensionLength() * 8  ); 
   }
 #else
-    READ_UVLC( uiCode, "slice_header_extension_length" );
+
+    READ_UVLC(uiCode,"slice_segment_header_extension_length");
     for(Int i=0; i<uiCode; i++)
     {
       UInt ignore;
-      READ_CODE(8,ignore,"slice_header_extension_data_byte");
-    }  
-  }
-#endif
+      READ_CODE(8,ignore,"slice_segment_header_extension_data_byte");
+    }
+  }
+#endif
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS,m_pcBitstream->readByteAlignment(),0);
+#else
   m_pcBitstream->readByteAlignment();
+#endif
+
+  pcSlice->clearSubstreamSizes();
 
   if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
   {
     Int endOfSliceHeaderLocation = m_pcBitstream->getByteLocation();
-    
+
     // Adjust endOfSliceHeaderLocation to account for emulation prevention bytes in the slice segment header
     for ( UInt curByteIdx  = 0; curByteIdx<m_pcBitstream->numEmulationPreventionBytesRead(); curByteIdx++ )
@@ -2798,5 +3032,5 @@
     Int  curEntryPointOffset     = 0;
     Int  prevEntryPointOffset    = 0;
-    for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+    for (UInt idx=0; idx<entryPointOffset.size(); idx++)
     {
       curEntryPointOffset += entryPointOffset[ idx ];
@@ -2805,5 +3039,5 @@
       for ( UInt curByteIdx  = 0; curByteIdx<m_pcBitstream->numEmulationPreventionBytesRead(); curByteIdx++ )
       {
-        if ( m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) >= ( prevEntryPointOffset + endOfSliceHeaderLocation ) && 
+        if ( m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) >= ( prevEntryPointOffset + endOfSliceHeaderLocation ) &&
              m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) <  ( curEntryPointOffset  + endOfSliceHeaderLocation ) )
         {
@@ -2814,38 +3048,5 @@
       entryPointOffset[ idx ] -= emulationPreventionByteCount;
       prevEntryPointOffset = curEntryPointOffset;
-    }
-
-    if ( pps->getTilesEnabledFlag() )
-    {
-      rpcSlice->setTileLocationCount( numEntryPointOffsets );
-
-      UInt prevPos = 0;
-      for (Int idx=0; idx<rpcSlice->getTileLocationCount(); idx++)
-      {
-        rpcSlice->setTileLocation( idx, prevPos + entryPointOffset [ idx ] );
-        prevPos += entryPointOffset[ idx ];
-      }
-    }
-    else if ( pps->getEntropyCodingSyncEnabledFlag() )
-    {
-    Int numSubstreams = rpcSlice->getNumEntryPointOffsets()+1;
-      rpcSlice->allocSubstreamSizes(numSubstreams);
-      UInt *pSubstreamSizes       = rpcSlice->getSubstreamSizes();
-      for (Int idx=0; idx<numSubstreams-1; idx++)
-      {
-        if ( idx < numEntryPointOffsets )
-        {
-          pSubstreamSizes[ idx ] = ( entryPointOffset[ idx ] << 3 ) ;
-        }
-        else
-        {
-          pSubstreamSizes[ idx ] = 0;
-        }
-      }
-    }
-
-    if (entryPointOffset)
-    {
-      delete [] entryPointOffset;
+      pcSlice->addSubstreamSize(entryPointOffset [ idx ] );
     }
   }
@@ -2853,5 +3054,5 @@
   return;
 }
-  
+
 Void TDecCavlc::parsePTL( TComPTL *rpcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1 )
 {
@@ -2859,24 +3060,18 @@
   if(profilePresentFlag)
   {
-    parseProfileTier(rpcPTL->getGeneralPTL());
-  }
-  READ_CODE( 8, uiCode, "general_level_idc" );    rpcPTL->getGeneralPTL()->setLevelIdc(uiCode);
+    parseProfileTier(rpcPTL->getGeneralPTL(), false);
+  }
+  READ_CODE( 8, uiCode, "general_level_idc" );    rpcPTL->getGeneralPTL()->setLevelIdc(Level::Name(uiCode));
 
   for (Int i = 0; i < maxNumSubLayersMinus1; i++)
   {
-#if !H_MV
-    if(profilePresentFlag)
-    {
-#endif
-      READ_FLAG( uiCode, "sub_layer_profile_present_flag[i]" ); rpcPTL->setSubLayerProfilePresentFlag(i, uiCode);
-#if H_MV
-      // When profilePresentFlag is equal to 0, sub_layer_profile_present_flag[ i ] shall be equal to 0.
-      assert( profilePresentFlag || !rpcPTL->getSubLayerProfilePresentFlag(i) );
-#else
-    }
-#endif
+    READ_FLAG( uiCode, "sub_layer_profile_present_flag[i]" ); rpcPTL->setSubLayerProfilePresentFlag(i, uiCode);
     READ_FLAG( uiCode, "sub_layer_level_present_flag[i]"   ); rpcPTL->setSubLayerLevelPresentFlag  (i, uiCode);
-  }
-  
+#if NH_MV
+    // When profilePresentFlag is equal to 0, sub_layer_profile_present_flag[ i ] shall be equal to 0.
+    assert( profilePresentFlag || !rpcPTL->getSubLayerProfilePresentFlag(i) );
+#endif
+  }
+
   if (maxNumSubLayersMinus1 > 0)
   {
@@ -2887,45 +3082,42 @@
     }
   }
-  
+
   for(Int i = 0; i < maxNumSubLayersMinus1; i++)
   {
-#if H_MV
     if( rpcPTL->getSubLayerProfilePresentFlag(i) )         
+    {
+      parseProfileTier(rpcPTL->getSubLayerPTL(i), true);
+    }
+    if(rpcPTL->getSubLayerLevelPresentFlag(i))
+    {
+      READ_CODE( 8, uiCode, "sub_layer_level_idc[i]" );   rpcPTL->getSubLayerPTL(i)->setLevelIdc(Level::Name(uiCode));
+    }
+  }
+}
+
+#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecCavlc::parseProfileTier(ProfileTierLevel *ptl, const Bool bIsSubLayer)
+#define PTL_TRACE_TEXT(txt) bIsSubLayer?("sub_layer_" txt) : ("general_" txt)
 #else
-    if( profilePresentFlag && rpcPTL->getSubLayerProfilePresentFlag(i) )          
-#endif
-    {
-      parseProfileTier(rpcPTL->getSubLayerPTL(i));
-    }
-    if(rpcPTL->getSubLayerLevelPresentFlag(i))
-    {
-      READ_CODE( 8, uiCode, "sub_layer_level_idc[i]" );   rpcPTL->getSubLayerPTL(i)->setLevelIdc(uiCode);
-    }
-  }
-}
-
-Void TDecCavlc::parseProfileTier(ProfileTierLevel *ptl)
+Void TDecCavlc::parseProfileTier(ProfileTierLevel *ptl, const Bool /*bIsSubLayer*/)
+#define PTL_TRACE_TEXT(txt) txt
+#endif
 {
   UInt uiCode;
-  READ_CODE(2 , uiCode, "XXX_profile_space[]");   ptl->setProfileSpace(uiCode);
-  READ_FLAG(    uiCode, "XXX_tier_flag[]"    );   ptl->setTierFlag    (uiCode ? 1 : 0);
-  READ_CODE(5 , uiCode, "XXX_profile_idc[]"  );   ptl->setProfileIdc  (uiCode);
+  READ_CODE(2 , uiCode,   PTL_TRACE_TEXT("profile_space"                   )); ptl->setProfileSpace(uiCode);
+  READ_FLAG(    uiCode,   PTL_TRACE_TEXT("tier_flag"                       )); ptl->setTierFlag    (uiCode ? Level::HIGH : Level::MAIN);
+  READ_CODE(5 , uiCode,   PTL_TRACE_TEXT("profile_idc"                     )); ptl->setProfileIdc  (Profile::Name(uiCode));
   for(Int j = 0; j < 32; j++)
   {
-    READ_FLAG(  uiCode, "XXX_profile_compatibility_flag[][j]");   ptl->setProfileCompatibilityFlag(j, uiCode ? 1 : 0);
-  }
-  READ_FLAG(uiCode, "general_progressive_source_flag");
-  ptl->setProgressiveSourceFlag(uiCode ? true : false);
-
-  READ_FLAG(uiCode, "general_interlaced_source_flag");
-  ptl->setInterlacedSourceFlag(uiCode ? true : false);
-  
-  READ_FLAG(uiCode, "general_non_packed_constraint_flag");
-  ptl->setNonPackedConstraintFlag(uiCode ? true : false);
-  
-  READ_FLAG(uiCode, "general_frame_only_constraint_flag");
-  ptl->setFrameOnlyConstraintFlag(uiCode ? true : false);
-  
-#if H_MV
+    READ_FLAG(  uiCode,   PTL_TRACE_TEXT("profile_compatibility_flag[][j]" )); ptl->setProfileCompatibilityFlag(j, uiCode ? 1 : 0);
+  }
+  READ_FLAG(uiCode,       PTL_TRACE_TEXT("progressive_source_flag"         )); ptl->setProgressiveSourceFlag(uiCode ? true : false);
+
+  READ_FLAG(uiCode,       PTL_TRACE_TEXT("interlaced_source_flag"          )); ptl->setInterlacedSourceFlag(uiCode ? true : false);
+
+  READ_FLAG(uiCode,       PTL_TRACE_TEXT("non_packed_constraint_flag"      )); ptl->setNonPackedConstraintFlag(uiCode ? true : false);
+
+  READ_FLAG(uiCode,       PTL_TRACE_TEXT("frame_only_constraint_flag"      )); ptl->setFrameOnlyConstraintFlag(uiCode ? true : false);
+#if NH_MV
   if( ptl->getV2ConstraintsPresentFlag() )
   {
@@ -2958,7 +3150,50 @@
   }
 #else
-  READ_CODE(16, uiCode, "XXX_reserved_zero_44bits[0..15]");
-  READ_CODE(16, uiCode, "XXX_reserved_zero_44bits[16..31]");
-  READ_CODE(12, uiCode, "XXX_reserved_zero_44bits[32..43]");
+
+  if (ptl->getProfileIdc() == Profile::MAINREXT           || ptl->getProfileCompatibilityFlag(Profile::MAINREXT) ||
+      ptl->getProfileIdc() == Profile::HIGHTHROUGHPUTREXT || ptl->getProfileCompatibilityFlag(Profile::HIGHTHROUGHPUTREXT))
+  {
+    UInt maxBitDepth=16;
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("max_12bit_constraint_flag"       )); if (uiCode) maxBitDepth=12;
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("max_10bit_constraint_flag"       )); if (uiCode) maxBitDepth=10;
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("max_8bit_constraint_flag"        )); if (uiCode) maxBitDepth=8;
+    ptl->setBitDepthConstraint(maxBitDepth);
+    ChromaFormat chromaFmtConstraint=CHROMA_444;
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("max_422chroma_constraint_flag"   )); if (uiCode) chromaFmtConstraint=CHROMA_422;
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("max_420chroma_constraint_flag"   )); if (uiCode) chromaFmtConstraint=CHROMA_420;
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("max_monochrome_constraint_flag"  )); if (uiCode) chromaFmtConstraint=CHROMA_400;
+    ptl->setChromaFormatConstraint(chromaFmtConstraint);
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("intra_constraint_flag"           )); ptl->setIntraConstraintFlag(uiCode != 0);
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("one_picture_only_constraint_flag")); ptl->setOnePictureOnlyConstraintFlag(uiCode != 0);
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("lower_bit_rate_constraint_flag"  )); ptl->setLowerBitRateConstraintFlag(uiCode != 0);
+    READ_CODE(16, uiCode, PTL_TRACE_TEXT("reserved_zero_34bits[0..15]"     ));
+    READ_CODE(16, uiCode, PTL_TRACE_TEXT("reserved_zero_34bits[16..31]"    ));
+    READ_CODE(2,  uiCode, PTL_TRACE_TEXT("reserved_zero_34bits[32..33]"    ));
+  }
+  else
+  {
+    ptl->setBitDepthConstraint((ptl->getProfileIdc() == Profile::MAIN10)?10:8);
+    ptl->setChromaFormatConstraint(CHROMA_420);
+    ptl->setIntraConstraintFlag(false);
+    ptl->setLowerBitRateConstraintFlag(true);
+    READ_CODE(16, uiCode, PTL_TRACE_TEXT("reserved_zero_43bits[0..15]"     ));
+    READ_CODE(16, uiCode, PTL_TRACE_TEXT("reserved_zero_43bits[16..31]"    ));
+    READ_CODE(11, uiCode, PTL_TRACE_TEXT("reserved_zero_43bits[32..42]"    ));
+  }
+
+  if ((ptl->getProfileIdc() >= Profile::MAIN && ptl->getProfileIdc() <= Profile::HIGHTHROUGHPUTREXT) ||
+       ptl->getProfileCompatibilityFlag(Profile::MAIN) ||
+       ptl->getProfileCompatibilityFlag(Profile::MAIN10) ||
+       ptl->getProfileCompatibilityFlag(Profile::MAINSTILLPICTURE) ||
+       ptl->getProfileCompatibilityFlag(Profile::MAINREXT) ||
+       ptl->getProfileCompatibilityFlag(Profile::HIGHTHROUGHPUTREXT) )
+  {
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("inbld_flag"                      )); assert(uiCode == 0);
+  }
+  else
+  {
+    READ_FLAG(    uiCode, PTL_TRACE_TEXT("reserved_zero_bit"               ));
+  }
+#undef PTL_TRACE_TEXT
 #endif
 }
@@ -2978,8 +3213,25 @@
 }
 
-Void TDecCavlc::parseSkipFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
-{
-  assert(0);
-}
+Void TDecCavlc::parseRemainingBytes( Bool noTrailingBytesExpected )
+{
+  if (noTrailingBytesExpected)
+  {
+    const UInt numberOfRemainingSubstreamBytes=m_pcBitstream->getNumBitsLeft();
+    assert (numberOfRemainingSubstreamBytes == 0);
+  }
+  else
+  {
+    while (m_pcBitstream->getNumBitsLeft())
+    {
+      UInt trailingNullByte=m_pcBitstream->readByte();
+      if (trailingNullByte!=0)
+      {
+        printf("Trailing byte should be 0, but has value %02x\n", trailingNullByte);
+        assert(trailingNullByte==0);
+      }
+    }
+  }
+}
+
 #if H_3D
 Void TDecCavlc::parseDIS( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
@@ -2989,4 +3241,9 @@
 #endif
 
+Void TDecCavlc::parseSkipFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
 Void TDecCavlc::parseCUTransquantBypassFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
 {
@@ -3014,5 +3271,5 @@
 }
 
-/** Parse I_PCM information. 
+/** Parse I_PCM information.
 * \param pcCU pointer to CU
 * \param uiAbsPartIdx CU index
@@ -3020,5 +3277,5 @@
 * \returns Void
 *
-* If I_PCM flag indicates that the CU is I_PCM, parse its PCM alignment bits and codes.  
+* If I_PCM flag indicates that the CU is I_PCM, parse its PCM alignment bits and codes.
 */
 Void TDecCavlc::parseIPCMInfo( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
@@ -3028,5 +3285,5 @@
 
 Void TDecCavlc::parseIntraDirLumaAng  ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
-{ 
+{
   assert(0);
 }
@@ -3052,25 +3309,41 @@
 }
 
+Void TDecCavlc::parseCrossComponentPrediction( class TComTU& /*rTu*/, ComponentID /*compID*/ )
+{
+  assert(0);
+}
+
 Void TDecCavlc::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
-  Int qp;
   Int  iDQp;
 
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  READ_SVLC(iDQp, "delta_qp");
+#else
   xReadSvlc( iDQp );
-
-  Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
-  qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+ qpBdOffsetY)) -  qpBdOffsetY;
-
-  UInt uiAbsQpCUPartIdx = (uiAbsPartIdx>>((g_uiMaxCUDepth - pcCU->getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth - pcCU->getSlice()->getPPS()->getMaxCuDQPDepth())<<1) ;
-  UInt uiQpCUDepth =   min(uiDepth,pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()) ;
+#endif
+
+  Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
+  const Int qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+ qpBdOffsetY)) -  qpBdOffsetY;
+
+  const UInt maxCUDepth        = pcCU->getSlice()->getSPS()->getMaxTotalCUDepth();
+  const UInt maxCuDQPDepth     = pcCU->getSlice()->getPPS()->getMaxCuDQPDepth();
+  const UInt doubleDepthDifference = ((maxCUDepth - maxCuDQPDepth)<<1);
+  const UInt uiAbsQpCUPartIdx = (uiAbsPartIdx>>doubleDepthDifference)<<doubleDepthDifference ;
+  const UInt uiQpCUDepth =   min(uiDepth,pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()) ;
 
   pcCU->setQPSubParts( qp, uiAbsQpCUPartIdx, uiQpCUDepth );
 }
 
-Void TDecCavlc::parseCoeffNxN( TComDataCU* /*pcCU*/, TCoeff* /*pcCoef*/, UInt /*uiAbsPartIdx*/, UInt /*uiWidth*/, UInt /*uiHeight*/, UInt /*uiDepth*/, TextType /*eTType*/ )
+Void TDecCavlc::parseChromaQpAdjustment( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
 {
   assert(0);
 }
 
+Void TDecCavlc::parseCoeffNxN( TComTU &/*rTu*/, ComponentID /*compID*/ )
+{
+  assert(0);
+}
+
 Void TDecCavlc::parseTransformSubdivFlag( UInt& /*ruiSubdivFlag*/, UInt /*uiLog2TransformBlockSize*/ )
 {
@@ -3078,5 +3351,5 @@
 }
 
-Void TDecCavlc::parseQtCbf( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, TextType /*eType*/, UInt /*uiTrDepth*/, UInt /*uiDepth*/ )
+Void TDecCavlc::parseQtCbf( TComTU &/*rTu*/, const ComponentID /*compID*/, const Bool /*lowestLevel*/ )
 {
   assert(0);
@@ -3088,5 +3361,5 @@
 }
 
-Void TDecCavlc::parseTransformSkipFlags (TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*width*/, UInt /*height*/, UInt /*uiDepth*/, TextType /*eTType*/)
+Void TDecCavlc::parseTransformSkipFlags (TComTU &/*rTu*/, ComponentID /*component*/)
 {
   assert(0);
@@ -3137,109 +3410,106 @@
 // ====================================================================================================================
 
-/** parse explicit wp tables
-* \param TComSlice* pcSlice
-* \returns Void
-*/
-Void TDecCavlc::xParsePredWeightTable( TComSlice* pcSlice )
-{
-  wpScalingParam  *wp;
-#if H_3D_DISABLE_CHROMA
-  Bool            bChroma     = ( pcSlice->getSPS()->getChromaFormatIdc() != 0 ); 
-#else
-  Bool            bChroma     = true; // color always present in HEVC ?
-#endif
-  SliceType       eSliceType  = pcSlice->getSliceType();
-  Int             iNbRef       = (eSliceType == B_SLICE ) ? (2) : (1);
-  UInt            uiLog2WeightDenomLuma, uiLog2WeightDenomChroma;
-  UInt            uiTotalSignalledWeightFlags = 0;
+//! parse explicit wp tables
+Void TDecCavlc::xParsePredWeightTable( TComSlice* pcSlice, const TComSPS *sps )
+{
+        WPScalingParam *wp;
+  const ChromaFormat    chFmt        = sps->getChromaFormatIdc();
+  const Int             numValidComp = Int(getNumberValidComponents(chFmt));
+  const Bool            bChroma      = (chFmt!=CHROMA_400);
+  const SliceType       eSliceType   = pcSlice->getSliceType();
+  const Int             iNbRef       = (eSliceType == B_SLICE ) ? (2) : (1);
+        UInt            uiLog2WeightDenomLuma=0, uiLog2WeightDenomChroma=0;
+        UInt            uiTotalSignalledWeightFlags = 0;
 
   Int iDeltaDenom;
   // decode delta_luma_log2_weight_denom :
-  READ_UVLC( uiLog2WeightDenomLuma, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+  READ_UVLC( uiLog2WeightDenomLuma, "luma_log2_weight_denom" );
   assert( uiLog2WeightDenomLuma <= 7 );
-  if( bChroma ) 
-  {
-    READ_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );     // se(v): delta_chroma_log2_weight_denom
+  if( bChroma )
+  {
+    READ_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );
     assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)>=0);
     assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)<=7);
     uiLog2WeightDenomChroma = (UInt)(iDeltaDenom + uiLog2WeightDenomLuma);
   }
-  else
-  { 
-    // For some reasons this is also needed to fix a compiler warning when H_3D_DISABLE_CHROMA is equal to 0.
-    uiLog2WeightDenomChroma = 0; 
-  }
-
-
-  for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
+
+
+
+  for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) // loop over l0 and l1 syntax elements
   {
     RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
-    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
     {
       pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
 
-      wp[0].uiLog2WeightDenom = uiLog2WeightDenomLuma;
-      wp[1].uiLog2WeightDenom = uiLog2WeightDenomChroma;
-      wp[2].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+      wp[COMPONENT_Y].uiLog2WeightDenom = uiLog2WeightDenomLuma;
+      for(Int j=1; j<numValidComp; j++)
+      {
+        wp[j].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+      }
 
       UInt  uiCode;
-      READ_FLAG( uiCode, "luma_weight_lX_flag" );           // u(1): luma_weight_l0_flag
-      wp[0].bPresentFlag = ( uiCode == 1 );
-      uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
-    }
-    if ( bChroma ) 
+      READ_FLAG( uiCode, iNumRef==0?"luma_weight_l0_flag[i]":"luma_weight_l1_flag[i]" );
+      wp[COMPONENT_Y].bPresentFlag = ( uiCode == 1 );
+      uiTotalSignalledWeightFlags += wp[COMPONENT_Y].bPresentFlag;
+    }
+    if ( bChroma )
     {
       UInt  uiCode;
-      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
       {
         pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
-        READ_FLAG( uiCode, "chroma_weight_lX_flag" );      // u(1): chroma_weight_l0_flag
-        wp[1].bPresentFlag = ( uiCode == 1 );
-        wp[2].bPresentFlag = ( uiCode == 1 );
-        uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
-      }
-    }
-    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+        READ_FLAG( uiCode, iNumRef==0?"chroma_weight_l0_flag[i]":"chroma_weight_l1_flag[i]" );
+        for(Int j=1; j<numValidComp; j++)
+        {
+          wp[j].bPresentFlag = ( uiCode == 1 );
+        }
+        uiTotalSignalledWeightFlags += 2*wp[COMPONENT_Cb].bPresentFlag;
+      }
+    }
+    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
     {
       pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
-      if ( wp[0].bPresentFlag ) 
+      if ( wp[COMPONENT_Y].bPresentFlag )
       {
         Int iDeltaWeight;
-        READ_SVLC( iDeltaWeight, "delta_luma_weight_lX" );  // se(v): delta_luma_weight_l0[i]
+        READ_SVLC( iDeltaWeight, iNumRef==0?"delta_luma_weight_l0[i]":"delta_luma_weight_l1[i]" );
         assert( iDeltaWeight >= -128 );
         assert( iDeltaWeight <=  127 );
-        wp[0].iWeight = (iDeltaWeight + (1<<wp[0].uiLog2WeightDenom));
-        READ_SVLC( wp[0].iOffset, "luma_offset_lX" );       // se(v): luma_offset_l0[i]
-        assert( wp[0].iOffset >= -128 );
-        assert( wp[0].iOffset <=  127 );
-      }
-      else 
-      {
-        wp[0].iWeight = (1 << wp[0].uiLog2WeightDenom);
-        wp[0].iOffset = 0;
-      }
-      if ( bChroma ) 
-      {
-        if ( wp[1].bPresentFlag ) 
-        {
-          for ( Int j=1 ; j<3 ; j++ ) 
+        wp[COMPONENT_Y].iWeight = (iDeltaWeight + (1<<wp[COMPONENT_Y].uiLog2WeightDenom));
+        READ_SVLC( wp[COMPONENT_Y].iOffset, iNumRef==0?"luma_offset_l0[i]":"luma_offset_l1[i]" );
+        Int range=sps->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag() ? (1<<sps->getBitDepth(CHANNEL_TYPE_LUMA))/2 : 128;
+        assert( wp[0].iOffset >= -range );
+        assert( wp[0].iOffset <   range );
+      }
+      else
+      {
+        wp[COMPONENT_Y].iWeight = (1 << wp[COMPONENT_Y].uiLog2WeightDenom);
+        wp[COMPONENT_Y].iOffset = 0;
+      }
+      if ( bChroma )
+      {
+        if ( wp[COMPONENT_Cb].bPresentFlag )
+        {
+          Int range=sps->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag() ? (1<<sps->getBitDepth(CHANNEL_TYPE_CHROMA))/2 : 128;
+          for ( Int j=1 ; j<numValidComp ; j++ )
           {
             Int iDeltaWeight;
-            READ_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );  // se(v): chroma_weight_l0[i][j]
+            READ_SVLC( iDeltaWeight, iNumRef==0?"delta_chroma_weight_l0[i]":"delta_chroma_weight_l1[i]" );
             assert( iDeltaWeight >= -128 );
             assert( iDeltaWeight <=  127 );
-            wp[j].iWeight = (iDeltaWeight + (1<<wp[1].uiLog2WeightDenom));
+            wp[j].iWeight = (iDeltaWeight + (1<<wp[j].uiLog2WeightDenom));
 
             Int iDeltaChroma;
-            READ_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );  // se(v): delta_chroma_offset_l0[i][j]
-            assert( iDeltaChroma >= -512 );
-            assert( iDeltaChroma <=  511 );
-            Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
-            wp[j].iOffset = Clip3(-128, 127, (iDeltaChroma + pred) );
+            READ_SVLC( iDeltaChroma, iNumRef==0?"delta_chroma_offset_l0[i]":"delta_chroma_offset_l1[i]" );
+            assert( iDeltaChroma >= -4*range);
+            assert( iDeltaChroma <   4*range);
+            Int pred = ( range - ( ( range*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
+            wp[j].iOffset = Clip3(-range, range-1, (iDeltaChroma + pred) );
           }
         }
-        else 
-        {
-          for ( Int j=1 ; j<3 ; j++ ) 
+        else
+        {
+          for ( Int j=1 ; j<numValidComp ; j++ )
           {
             wp[j].iWeight = (1 << wp[j].uiLog2WeightDenom);
@@ -3250,5 +3520,5 @@
     }
 
-    for ( Int iRefIdx=pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+    for ( Int iRefIdx=pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
     {
       pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
@@ -3272,22 +3542,43 @@
   for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
   {
-    for(listId = 0; listId <  g_scalingListNum[sizeId]; listId++)
-    {
-      READ_FLAG( code, "scaling_list_pred_mode_flag");
-      scalingListPredModeFlag = (code) ? true : false;
-      if(!scalingListPredModeFlag) //Copy Mode
-      {
-        READ_UVLC( code, "scaling_list_pred_matrix_id_delta");
-        scalingList->setRefMatrixId (sizeId,listId,(UInt)((Int)(listId)-(code)));
-        if( sizeId > SCALING_LIST_8x8 )
-        {
-          scalingList->setScalingListDC(sizeId,listId,((listId == scalingList->getRefMatrixId (sizeId,listId))? 16 :scalingList->getScalingListDC(sizeId, scalingList->getRefMatrixId (sizeId,listId))));
-        }
-        scalingList->processRefMatrix( sizeId, listId, scalingList->getRefMatrixId (sizeId,listId));
-
-      }
-      else //DPCM Mode
-      {
-        xDecodeScalingList(scalingList, sizeId, listId);
+    for(listId = 0; listId <  SCALING_LIST_NUM; listId++)
+    {
+      if ((sizeId==SCALING_LIST_32x32) && (listId%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) != 0))
+      {
+        Int *src = scalingList->getScalingListAddress(sizeId, listId);
+        const Int size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+        const Int *srcNextSmallerSize = scalingList->getScalingListAddress(sizeId-1, listId);
+        for(Int i=0; i<size; i++)
+        {
+          src[i] = srcNextSmallerSize[i];
+        }
+        scalingList->setScalingListDC(sizeId,listId,(sizeId > SCALING_LIST_8x8) ? scalingList->getScalingListDC(sizeId-1, listId) : src[0]);
+      }
+      else
+      {
+        READ_FLAG( code, "scaling_list_pred_mode_flag");
+        scalingListPredModeFlag = (code) ? true : false;
+        scalingList->setScalingListPredModeFlag(sizeId, listId, scalingListPredModeFlag);
+        if(!scalingListPredModeFlag) //Copy Mode
+        {
+          READ_UVLC( code, "scaling_list_pred_matrix_id_delta");
+
+          if (sizeId==SCALING_LIST_32x32)
+          {
+            code*=(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES); // Adjust the decoded code for this size, to cope with the missing 32x32 chroma entries.
+          }
+
+          scalingList->setRefMatrixId (sizeId,listId,(UInt)((Int)(listId)-(code)));
+          if( sizeId > SCALING_LIST_8x8 )
+          {
+            scalingList->setScalingListDC(sizeId,listId,((listId == scalingList->getRefMatrixId (sizeId,listId))? 16 :scalingList->getScalingListDC(sizeId, scalingList->getRefMatrixId (sizeId,listId))));
+          }
+          scalingList->processRefMatrix( sizeId, listId, scalingList->getRefMatrixId (sizeId,listId));
+
+        }
+        else //DPCM Mode
+        {
+          xDecodeScalingList(scalingList, sizeId, listId);
+        }
       }
     }
@@ -3307,5 +3598,5 @@
   Int scalingListDcCoefMinus8 = 0;
   Int nextCoef = SCALING_LIST_START_VALUE;
-  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
+  UInt* scan  = g_scanOrder[SCAN_UNGROUPED][SCAN_DIAG][sizeId==0 ? 2 : 3][sizeId==0 ? 2 : 3];
   Int *dst = scalingList->getScalingListAddress(sizeId, listId);
 
@@ -3326,5 +3617,5 @@
 
 Bool TDecCavlc::xMoreRbspData()
-{ 
+{
   Int bitsLeft = m_pcBitstream->getNumBitsLeft();
 
@@ -3354,4 +3645,8 @@
 }
 
+Void TDecCavlc::parseExplicitRdpcmMode( TComTU& /*rTu*/, ComponentID /*compID*/ )
+{
+  assert(0);
+}
 //! \}
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -52,5 +52,5 @@
 // Class definition
 // ====================================================================================================================
-#if H_3D
+#if NH_MV
 class TDecTop;
 #endif
@@ -61,13 +61,12 @@
   TDecCavlc();
   virtual ~TDecCavlc();
-  
+
 protected:
-  void  parseShortTermRefPicSet            (TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Int idx);
-  
-#if H_3D
+
+  Void  parseShortTermRefPicSet            (TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Int idx);
+
+#if NH_MV
   TDecTop*  m_decTop;
 #endif
-
-
 public:
 
@@ -76,60 +75,44 @@
   Void  setBitstream        ( TComInputBitstream* p )   { m_pcBitstream = p; }
   Void  parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
-  Void  parseQtCbf          ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void  parseQtCbf          ( class TComTU &rTu, const ComponentID compID, const Bool lowestLevel );
   Void  parseQtRootCbf      ( UInt uiAbsPartIdx, UInt& uiQtRootCbf );
   Void  parseVPS            ( TComVPS* pcVPS );
-#if H_MV
+#if NH_MV
   Void  parseVPSExtension   ( TComVPS* pcVPS ); 
-  Void  parseRepFormat      ( Int i, TComRepFormat* curRepFormat, TComRepFormat* prevRepFormat );
-  Void  parseVPSVUI         ( TComVPS* pcVPS );
+  Void  parseRepFormat      ( Int i, TComRepFormat* curRepFormat, const TComRepFormat* prevRepFormat );
+  Void  parseVPSVUI         ( const TComVPS* pcVPS, TComVPSVUI* vpsVui );
   Void  parseVideoSignalInfo( TComVideoSignalInfo* pcVideoSignalInfo ); 
   Void  parseDpbSize        ( TComVPS* pcVPS ); 
-  Void  parseVpsVuiBspHrdParameters( TComVPS* pcVPS ); 
+  Void  parseVpsVuiBspHrdParameters( const TComVPS* vps, TComVPSVUI* vpsVui ); 
+
+  Void  parseSpsMultilayerExtension( TComSPS* pcSPS );  
+  Void  parsePpsMultilayerExtension( TComPPS* pcPPS );
+  Void  setDecTop           ( TDecTop* decTop ) { m_decTop = decTop; }; 
+#endif
+#if NH_3D
+  Void  parseVps3dExtension  ( TComVPS* pcVPS ); 
+  Void  parseSps3dExtension  ( TComSPS* pcSPS );  
+  Void  parsePps3dExtension  ( TComPPS* pcPPS );
 #endif
 
-#if H_MV
-  Void  parseSPSExtension   ( TComSPS* pcSPS );  
-#endif
-#if H_3D
-  Void  parseVPS3dExtension  ( TComVPS* pcVPS ); 
-  Void  parseSPS3dExtension ( TComSPS* pcSPS );
   Void  parseSPS            ( TComSPS* pcSPS );
-#else
-  Void  parseSPS            ( TComSPS* pcSPS );
-#endif
+  Void  parsePPS            ( TComPPS* pcPPS );
 
-#if H_MV
-  Void  parsePPSMultilayerExtension( TComPPS* pcPPS );
-#endif
-
-
-#if H_3D
-  Void  parsePPS            ( TComPPS* pcPPS, TComVPS* pcVPS );
-  Void  parsePPSExtension   ( TComPPS* pcPPS, TComVPS* pcVPS );
-#else
-  Void  parsePPS            ( TComPPS* pcPPS);
-#endif
-#if H_3D
-  Void  setDecTop           ( TDecTop* decTop ) { m_decTop = decTop; }; 
-#endif
   Void  parseVUI            ( TComVUI* pcVUI, TComSPS* pcSPS );
   Void  parseSEI            ( SEIMessages& );
   Void  parsePTL            ( TComPTL *rpcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1 );
-  Void  parseProfileTier    (ProfileTierLevel *ptl);
+  Void  parseProfileTier    (ProfileTierLevel *ptl, const Bool bIsSubLayer);
   Void  parseHrdParameters  (TComHRD *hrd, Bool cprms_present_flag, UInt tempLevelHigh);
-#if H_MV
-  Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, Int targetOlsIdx);
-#else
-  Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager);
-#endif
+  Void  parseSliceHeader    ( TComSlice* pcSlice, ParameterSetManager *parameterSetManager, const Int prevTid0POC);
   Void  parseTerminatingBit ( UInt& ruiBit );
-  
-  Void  parseMVPIdx         ( Int& riMVPIdx );
-  
-  Void  parseSkipFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void  parseRemainingBytes ( Bool noTrailingBytesExpected );
+
+  Void  parseMVPIdx          ( Int& riMVPIdx );
+        
+  Void  parseSkipFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #if H_3D
   Void  parseDIS            ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
-  Void  parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void parseMergeFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
   Void parseMergeIndex      ( TComDataCU* pcCU, UInt& ruiMergeIndex );
@@ -150,25 +133,29 @@
   Void parsePartSize        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void parsePredMode        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
   Void parseIntraDirLumaAng ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
   Void parseIntraDirChroma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
   Void parseInterDir        ( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx );
-  Void parseRefFrmIdx       ( TComDataCU* pcCU, Int& riRefFrmIdx,  RefPicList eRefList );
+  Void parseRefFrmIdx       ( TComDataCU* pcCU, Int& riRefFrmIdx, RefPicList eRefList );
   Void parseMvd             ( TComDataCU* pcCU, UInt uiAbsPartAddr,UInt uiPartIdx,    UInt uiDepth, RefPicList eRefList );
-  
+
+  Void parseCrossComponentPrediction( class TComTU &rTu, ComponentID compID );
+
   Void parseDeltaQP         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  Void parseCoeffNxN        ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
-  Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType);
+  Void parseChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx, UInt depth);
+
+  Void parseCoeffNxN        ( class TComTU &rTu, ComponentID compID );
+
+  Void parseTransformSkipFlags ( class TComTU &rTu, ComponentID component );
 
   Void parseIPCMInfo        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
 
-  Void updateContextTables  ( SliceType /*eSliceType*/, Int /*iQp*/ ) { return; }
+  Void xParsePredWeightTable ( TComSlice* pcSlice, const TComSPS *sps );
+  Void  parseScalingList     ( TComScalingList* scalingList );
+  Void xDecodeScalingList    ( TComScalingList *scalingList, UInt sizeId, UInt listId);
 
-  Void xParsePredWeightTable ( TComSlice* pcSlice );
-  Void  parseScalingList               ( TComScalingList* scalingList );
-  Void xDecodeScalingList    ( TComScalingList *scalingList, UInt sizeId, UInt listId);
-#if H_3D
+  Void  parseExplicitRdpcmMode( TComTU &rTu, ComponentID compID );
+#if NH_MV
   TDecTop*  getDecTop()      { return m_decTop; };
 #endif
@@ -181,3 +168,2 @@
 
 #endif // !defined(AFX_TDECCAVLC_H__9732DD64_59B0_4A41_B29E_1A5B18821EAD__INCLUDED_)
-
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,4 +37,6 @@
 
 #include "TDecCu.h"
+#include "TLibCommon/TComTU.h"
+#include "TLibCommon/TComPrediction.h"
 
 //! \ingroup TLibDecoder
@@ -67,12 +69,13 @@
 
 /**
- \param    uiMaxDepth    total number of allowable depth
- \param    uiMaxWidth    largest CU width
- \param    uiMaxHeight   largest CU height
+ \param    uiMaxDepth      total number of allowable depth
+ \param    uiMaxWidth      largest CU width
+ \param    uiMaxHeight     largest CU height
+ \param    chromaFormatIDC chroma format
  */
-Void TDecCu::create( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight )
+Void TDecCu::create( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight, ChromaFormat chromaFormatIDC )
 {
   m_uiMaxDepth = uiMaxDepth+1;
-  
+
   m_ppcYuvResi = new TComYuv*[m_uiMaxDepth-1];
   m_ppcYuvReco = new TComYuv*[m_uiMaxDepth-1];
@@ -81,5 +84,5 @@
   m_ppcYuvRecoDBBP = new TComYuv*[m_uiMaxDepth-1];
 #endif
-  
+
   UInt uiNumPartitions;
   for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
@@ -88,14 +91,15 @@
     UInt uiWidth  = uiMaxWidth  >> ui;
     UInt uiHeight = uiMaxHeight >> ui;
-    
-    m_ppcYuvResi[ui] = new TComYuv;    m_ppcYuvResi[ui]->create( uiWidth, uiHeight );
-    m_ppcYuvReco[ui] = new TComYuv;    m_ppcYuvReco[ui]->create( uiWidth, uiHeight );
-    m_ppcCU     [ui] = new TComDataCU; m_ppcCU     [ui]->create( uiNumPartitions, uiWidth, uiHeight, true, uiMaxWidth >> (m_uiMaxDepth - 1) );
+
+    m_ppcYuvResi[ui] = new TComYuv;    m_ppcYuvResi[ui]->create( uiWidth, uiHeight, chromaFormatIDC );
+    m_ppcYuvReco[ui] = new TComYuv;    m_ppcYuvReco[ui]->create( uiWidth, uiHeight, chromaFormatIDC );
+    m_ppcCU     [ui] = new TComDataCU; m_ppcCU     [ui]->create( chromaFormatIDC, uiNumPartitions, uiWidth, uiHeight, true, uiMaxWidth >> (m_uiMaxDepth - 1) );
 #if H_3D_DBBP
     m_ppcYuvRecoDBBP[ui] = new TComYuv;    m_ppcYuvRecoDBBP[ui]->create( uiWidth, uiHeight );
 #endif
-  }
-  
+}
+
   m_bDecodeDQP = false;
+  m_IsChromaQpAdjCoded = false;
 
   // initialize partition order.
@@ -103,5 +107,5 @@
   initZscanToRaster(m_uiMaxDepth, 1, 0, piTmp);
   initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
-  
+
   // initialize conversion matrix from partition index to pel
   initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
@@ -119,5 +123,5 @@
 #endif
   }
-  
+
   delete [] m_ppcYuvResi; m_ppcYuvResi = NULL;
   delete [] m_ppcYuvReco; m_ppcYuvReco = NULL;
@@ -132,24 +136,33 @@
 // ====================================================================================================================
 
-/** \param    pcCU        pointer of CU data
- \param    ruiIsLast   last data?
+/** 
+ Parse a CTU.
+ \param    pCtu                      [in/out] pointer to CTU data structure
+ \param    isLastCtuOfSliceSegment   [out]    true, if last CTU of the slice segment
  */
-Void TDecCu::decodeCU( TComDataCU* pcCU, UInt& ruiIsLast )
-{
-  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+Void TDecCu::decodeCtu( TComDataCU* pCtu, Bool& isLastCtuOfSliceSegment )
+{
+  if ( pCtu->getSlice()->getPPS()->getUseDQP() )
   {
     setdQPFlag(true);
   }
 
+  if ( pCtu->getSlice()->getUseChromaQpAdj() )
+  {
+    setIsChromaQpAdjCoded(true);
+  }
+
   // start from the top level CU
-  xDecodeCU( pcCU, 0, 0, ruiIsLast);
-}
-
-/** \param    pcCU        pointer of CU data
+  xDecodeCU( pCtu, 0, 0, isLastCtuOfSliceSegment);
+}
+
+/** 
+ Decoding process for a CTU.
+ \param    pCtu                      [in/out] pointer to CTU data structure
  */
-Void TDecCu::decompressCU( TComDataCU* pcCU )
+Void TDecCu::decompressCtu( TComDataCU* pCtu )
 {
 #if !H_3D_IV_MERGE
-  xDecompressCU( pcCU, 0,  0 );
+  xDecompressCU( pCtu, 0,  0 );
 #endif
 }
@@ -159,77 +172,47 @@
 // ====================================================================================================================
 
-/**decode end-of-slice flag
- * \param pcCU
- * \param uiAbsPartIdx 
- * \param uiDepth 
- * \returns Bool
- */
-Bool TDecCu::xDecodeSliceEnd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth)
-{
-  UInt uiIsLast;
-  TComPic* pcPic = pcCU->getPic();
-  TComSlice * pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
-  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
-  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
-  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
-  UInt uiGranularityWidth = g_uiMaxCUWidth;
-  UInt uiPosX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  UInt uiPosY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
-
-  if(((uiPosX+pcCU->getWidth(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosX+pcCU->getWidth(uiAbsPartIdx)==uiWidth))
-    &&((uiPosY+pcCU->getHeight(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosY+pcCU->getHeight(uiAbsPartIdx)==uiHeight)))
-  {
-    m_pcEntropyDecoder->decodeTerminatingBit( uiIsLast );
+//! decode end-of-slice flag
+Bool TDecCu::xDecodeSliceEnd( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiIsLastCtuOfSliceSegment;
+
+  if (pcCU->isLastSubCUOfCtu(uiAbsPartIdx))
+  {
+    m_pcEntropyDecoder->decodeTerminatingBit( uiIsLastCtuOfSliceSegment );
   }
   else
   {
-    uiIsLast=0;
-  }
-  
-  if(uiIsLast) 
-  {
-    if(pcSlice->isNextSliceSegment()&&!pcSlice->isNextSlice()) 
-    {
-      pcSlice->setSliceSegmentCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
-    }
-    else 
-    {
-      pcSlice->setSliceCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
-      pcSlice->setSliceSegmentCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
-    }
-  }
-
-  return uiIsLast>0;
-}
-
-/** decode CU block recursively
- * \param pcCU
- * \param uiAbsPartIdx 
- * \param uiDepth 
- * \returns Void
- */
-
-Void TDecCu::xDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
-{
-  TComPic* pcPic = pcCU->getPic();
-  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
+    uiIsLastCtuOfSliceSegment=0;
+  }
+
+  return uiIsLastCtuOfSliceSegment>0;
+}
+
+//! decode CU block recursively
+Void TDecCu::xDecodeCU( TComDataCU*const pcCU, const UInt uiAbsPartIdx, const UInt uiDepth, Bool &isLastCtuOfSliceSegment)
+{
+  TComPic* pcPic        = pcCU->getPic();
+  const TComSPS &sps    = pcPic->getPicSym()->getSPS();
+  const TComPPS &pps    = pcPic->getPicSym()->getPPS();
+  const UInt maxCuWidth = sps.getMaxCUWidth();
+  const UInt maxCuHeight= sps.getMaxCUHeight();
+  UInt uiCurNumParts    = pcPic->getNumPartitionsInCtu() >> (uiDepth<<1);
   UInt uiQNumParts      = uiCurNumParts>>2;
-  
+
+
   Bool bBoundary = false;
   UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiRPelX   = uiLPelX + (maxCuWidth>>uiDepth)  - 1;
   UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  UInt uiBPelY   = uiTPelY + (maxCuHeight>>uiDepth) - 1;
 #if H_MV_ENC_DEC_TRAC
   DTRACE_CU_S("=========== coding_quadtree ===========\n")
   DTRACE_CU("x0", uiLPelX)
   DTRACE_CU("x1", uiTPelY)
-  DTRACE_CU("log2CbSize", g_uiMaxCUWidth>>uiDepth)
+  DTRACE_CU("log2CbSize", maxCuWidth>>uiDepth)
   DTRACE_CU("cqtDepth"  , uiDepth)
 #endif
 
-  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
-  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getSliceSegmentCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getSliceSegmentCurStartCUAddr();
-  if((!bStartInCU) && ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  if( ( uiRPelX < sps.getPicWidthInLumaSamples() ) && ( uiBPelY < sps.getPicHeightInLumaSamples() ) )
   {
     m_pcEntropyDecoder->decodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
@@ -239,9 +222,8 @@
     bBoundary = true;
   }
-  
-  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() ) ) || bBoundary )
   {
     UInt uiIdx = uiAbsPartIdx;
-    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
     {
       setdQPFlag(true);
@@ -249,37 +231,30 @@
     }
 
+    if( uiDepth == pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth() && pcCU->getSlice()->getUseChromaQpAdj() )
+    {
+      setIsChromaQpAdjCoded(true);
+    }
+
     for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
     {
       uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
       uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
-      
-      Bool bSubInSlice = pcCU->getSCUAddr()+uiIdx+uiQNumParts>pcSlice->getSliceSegmentCurStartCUAddr();
-      if ( bSubInSlice )
-      {
-        if ( !ruiIsLast && ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
-        {
-          xDecodeCU( pcCU, uiIdx, uiDepth+1, ruiIsLast );
-        }
-        else
-        {
-          pcCU->setOutsideCUPart( uiIdx, uiDepth+1 );
-        }
-      }
-      
+
+      if ( !isLastCtuOfSliceSegment && ( uiLPelX < sps.getPicWidthInLumaSamples() ) && ( uiTPelY < sps.getPicHeightInLumaSamples() ) )
+      {
+        xDecodeCU( pcCU, uiIdx, uiDepth+1, isLastCtuOfSliceSegment );
+      }
+      else
+      {
+        pcCU->setOutsideCUPart( uiIdx, uiDepth+1 );
+      }
+
       uiIdx += uiQNumParts;
     }
-    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
     {
       if ( getdQPFlag() )
       {
-        UInt uiQPSrcPartIdx;
-        if ( pcPic->getCU( pcCU->getAddr() )->getSliceSegmentStartCU(uiAbsPartIdx) != pcSlice->getSliceSegmentCurStartCUAddr() )
-        {
-          uiQPSrcPartIdx = pcSlice->getSliceSegmentCurStartCUAddr() % pcPic->getNumPartInCU();
-        }
-        else
-        {
-          uiQPSrcPartIdx = uiAbsPartIdx;
-        }
+        UInt uiQPSrcPartIdx = uiAbsPartIdx;
         pcCU->setQPSubParts( pcCU->getRefQP( uiQPSrcPartIdx ), uiAbsPartIdx, uiDepth ); // set QP to default QP
       }
@@ -287,5 +262,5 @@
     return;
   }
-  
+
 #if H_MV_ENC_DEC_TRAC
   DTRACE_CU_S("=========== coding_unit ===========\n")
@@ -303,5 +278,5 @@
 #endif
 
-  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  if( uiDepth <= pps.getMaxCuDQPDepth() && pps.getUseDQP())
   {
     setdQPFlag(true);
@@ -316,6 +291,5 @@
 #endif
  
- 
-  if(!pcCU->getSlice()->isIntra())
+if(!pcCU->getSlice()->isIntra())
   {
 #if H_3D_ARP && H_3D_IV_MERGE
@@ -380,9 +354,15 @@
   }
 #endif
-  if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+
+  if( uiDepth <= pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth() && pcCU->getSlice()->getUseChromaQpAdj() )
+  {
+    setIsChromaQpAdjCoded(true);
+  }
+
+  if (pps.getTransquantBypassEnableFlag())
   {
     m_pcEntropyDecoder->decodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx, uiDepth );
   }
-  
+
   // decode CU mode and the partition size
   if( !pcCU->getSlice()->isIntra())
@@ -390,5 +370,6 @@
     m_pcEntropyDecoder->decodeSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
   }
- 
+
+
   if( pcCU->isSkipped(uiAbsPartIdx) )
   {
@@ -460,5 +441,5 @@
     TComMv cTmpMv( 0, 0 );
     for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
-    {        
+    {
       if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
       {
@@ -524,8 +505,9 @@
 #endif
 
-    xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+    xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
 #if H_3D_IV_MERGE
     xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
 #endif
+
     return;
   }
@@ -535,4 +517,5 @@
   {
 #endif
+
   m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );
   m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );
@@ -547,5 +530,5 @@
       m_pcEntropyDecoder->decodeSDCFlag( pcCU, uiAbsPartIdx, uiDepth );
 #endif
-      xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+      xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
 #if H_3D_IV_MERGE
       xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
@@ -555,7 +538,4 @@
   }
 
-  UInt uiCurrWidth      = pcCU->getWidth ( uiAbsPartIdx );
-  UInt uiCurrHeight     = pcCU->getHeight( uiAbsPartIdx );
-  
   // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
   m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
@@ -563,10 +543,12 @@
   // Coefficient decoding
   Bool bCodeDQP = getdQPFlag();
-  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, uiCurrWidth, uiCurrHeight, bCodeDQP );
+  Bool isChromaQpAdjCoded = getIsChromaQpAdjCoded();
+  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, isChromaQpAdjCoded );
+  setIsChromaQpAdjCoded( isChromaQpAdjCoded );
   setdQPFlag( bCodeDQP );
 #if H_3D
   }
 #endif
-  xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+  xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
 #if H_3D_IV_MERGE
   xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
@@ -574,5 +556,5 @@
 }
 
-Void TDecCu::xFinishDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
+Void TDecCu::xFinishDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool &isLastCtuOfSliceSegment)
 {
   if(  pcCU->getSlice()->getPPS()->getUseDQP())
@@ -581,39 +563,43 @@
   }
 
-  ruiIsLast = xDecodeSliceEnd( pcCU, uiAbsPartIdx, uiDepth);
-}
-
-Void TDecCu::xDecompressCU( TComDataCU* pcCU, UInt uiAbsPartIdx,  UInt uiDepth )
-{
-  TComPic* pcPic = pcCU->getPic();
+  if (pcCU->getSlice()->getUseChromaQpAdj() && !getIsChromaQpAdjCoded())
+  {
+    pcCU->setChromaQpAdjSubParts( pcCU->getCodedChromaQpAdj(), uiAbsPartIdx, uiDepth ); // set QP
+  }
+
+  isLastCtuOfSliceSegment = xDecodeSliceEnd( pcCU, uiAbsPartIdx );
+}
+
+Void TDecCu::xDecompressCU( TComDataCU* pCtu, UInt uiAbsPartIdx,  UInt uiDepth )
+{
+  TComPic* pcPic = pCtu->getPic();
 #if !H_3D_IV_MERGE
+  TComSlice * pcSlice = pCtu->getSlice();
+  const TComSPS &sps=*(pcSlice->getSPS());
+
   Bool bBoundary = false;
-  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
-  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
-
-  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
-  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
-  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getSliceSegmentCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getSliceSegmentCurStartCUAddr();
-  if(bStartInCU||( uiRPelX >= pcSlice->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  UInt uiLPelX   = pCtu->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiRPelX   = uiLPelX + (sps.getMaxCUWidth()>>uiDepth)  - 1;
+  UInt uiTPelY   = pCtu->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (sps.getMaxCUHeight()>>uiDepth) - 1;
+
+  if( ( uiRPelX >= sps.getPicWidthInLumaSamples() ) || ( uiBPelY >= sps.getPicHeightInLumaSamples() ) )
   {
     bBoundary = true;
   }
 
-  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  if( ( ( uiDepth < pCtu->getDepth( uiAbsPartIdx ) ) && ( uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() ) ) || bBoundary )
   {
     UInt uiNextDepth = uiDepth + 1;
-    UInt uiQNumParts = pcCU->getTotalNumPart() >> (uiNextDepth<<1);
+    UInt uiQNumParts = pCtu->getTotalNumPart() >> (uiNextDepth<<1);
     UInt uiIdx = uiAbsPartIdx;
     for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++ )
     {
-      uiLPelX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
-      uiTPelY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
-
-      Bool binSlice = (pcCU->getSCUAddr()+uiIdx+uiQNumParts>pcSlice->getSliceSegmentCurStartCUAddr())&&(pcCU->getSCUAddr()+uiIdx<pcSlice->getSliceSegmentCurEndCUAddr());
-      if(binSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
-      {
-        xDecompressCU(pcCU, uiIdx, uiNextDepth );
+      uiLPelX = pCtu->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY = pCtu->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+
+      if( ( uiLPelX < sps.getPicWidthInLumaSamples() ) && ( uiTPelY < sps.getPicHeightInLumaSamples() ) )
+      {
+        xDecompressCU(pCtu, uiIdx, uiNextDepth );
       }
 
@@ -622,13 +608,13 @@
     return;
   }
-#endif  
+#endif
   // Residual reconstruction
   m_ppcYuvResi[uiDepth]->clear();
 
-  m_ppcCU[uiDepth]->copySubCU( pcCU, uiAbsPartIdx, uiDepth );
+  m_ppcCU[uiDepth]->copySubCU( pCtu, uiAbsPartIdx );
 
   switch( m_ppcCU[uiDepth]->getPredictionMode(0) )
   {
-  case MODE_INTER:
+    case MODE_INTER:
 #if H_3D_DBBP
     if( m_ppcCU[uiDepth]->getDBBPFlag(0) )
@@ -647,5 +633,5 @@
       {
 #endif
-        xReconInter( m_ppcCU[uiDepth], uiDepth );
+      xReconInter( m_ppcCU[uiDepth], uiDepth );
 #if H_3D_INTER_SDC
       }
@@ -654,6 +640,6 @@
     }
 #endif
-    break;
-  case MODE_INTRA:
+      break;
+    case MODE_INTRA:
 #if H_3D
     if( m_ppcCU[uiDepth]->getDISFlag(0) )
@@ -670,9 +656,21 @@
 #endif
       xReconIntraQT( m_ppcCU[uiDepth], uiDepth );
-    break;
-  default:
-    assert(0);
-    break;
-  }
+      break;
+    default:
+      assert(0);
+      break;
+  }
+
+#if DEBUG_STRING
+  const PredMode predMode=m_ppcCU[uiDepth]->getPredictionMode(0);
+  if (DebugOptionList::DebugString_Structure.getInt()&DebugStringGetPredModeMask(predMode))
+  {
+    PartSize eSize=m_ppcCU[uiDepth]->getPartitionSize(0);
+    std::ostream &ss(std::cout);
+
+    ss <<"###: " << (predMode==MODE_INTRA?"Intra   ":"Inter   ") << partSizeToString[eSize] << " CU at " << m_ppcCU[uiDepth]->getCUPelX() << ", " << m_ppcCU[uiDepth]->getCUPelY() << " width=" << UInt(m_ppcCU[uiDepth]->getWidth(0)) << std::endl;
+  }
+#endif
+
   if ( m_ppcCU[uiDepth]->isLosslessCoded(0) && (m_ppcCU[uiDepth]->getIPCMFlag(0) == false))
   {
@@ -685,15 +683,30 @@
 Void TDecCu::xReconInter( TComDataCU* pcCU, UInt uiDepth )
 {
-  
+
   // inter prediction
   m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth] );
-  
+
+#if DEBUG_STRING
+  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTER);
+  if (DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask)
+  {
+    printBlockToStream(std::cout, "###inter-pred: ", *(m_ppcYuvReco[uiDepth]));
+  }
+#endif
+
   // inter recon
-  xDecodeInterTexture( pcCU, 0, uiDepth );
-  
+  xDecodeInterTexture( pcCU, uiDepth );
+
+#if DEBUG_STRING
+  if (DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask)
+  {
+    printBlockToStream(std::cout, "###inter-resi: ", *(m_ppcYuvResi[uiDepth]));
+  }
+#endif
+
   // clip for only non-zero cbp case
-  if  ( ( pcCU->getCbf( 0, TEXT_LUMA ) ) || ( pcCU->getCbf( 0, TEXT_CHROMA_U ) ) || ( pcCU->getCbf(0, TEXT_CHROMA_V ) ) )
-  {
-    m_ppcYuvReco[uiDepth]->addClip( m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], 0, pcCU->getWidth( 0 ) );
+  if  ( pcCU->getQtRootCbf( 0) )
+  {
+    m_ppcYuvReco[uiDepth]->addClip( m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], 0, pcCU->getWidth( 0 ), pcCU->getSlice()->getSPS()->getBitDepths() );
   }
   else
@@ -701,4 +714,11 @@
     m_ppcYuvReco[uiDepth]->copyPartToPartYuv( m_ppcYuvReco[uiDepth],0, pcCU->getWidth( 0 ),pcCU->getHeight( 0 ));
   }
+#if DEBUG_STRING
+  if (DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask)
+  {
+    printBlockToStream(std::cout, "###inter-reco: ", *(m_ppcYuvReco[uiDepth]));
+  }
+#endif
+
 }
 
@@ -924,38 +944,68 @@
 #endif
 
+
 Void
-TDecCu::xIntraRecLumaBlk( TComDataCU* pcCU,
-                         UInt        uiTrDepth,
-                         UInt        uiAbsPartIdx,
-                         TComYuv*    pcRecoYuv,
-                         TComYuv*    pcPredYuv, 
-                         TComYuv*    pcResiYuv )
-{
-  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
-  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
-  UInt    uiStride          = pcRecoYuv->getStride  ();
-  Pel*    piReco            = pcRecoYuv->getLumaAddr( uiAbsPartIdx );
-  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
-  Pel*    piResi            = pcResiYuv->getLumaAddr( uiAbsPartIdx );
-  
-  UInt    uiNumCoeffInc     = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
-  TCoeff* pcCoeff           = pcCU->getCoeffY() + ( uiNumCoeffInc * uiAbsPartIdx );
-  
-  UInt    uiLumaPredMode    = pcCU->getLumaIntraDir     ( uiAbsPartIdx );
-  
-  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
-  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
-  Bool    useTransformSkip  = pcCU->getTransformSkip(uiAbsPartIdx, TEXT_LUMA);
+TDecCu::xIntraRecBlk(       TComYuv*    pcRecoYuv,
+                            TComYuv*    pcPredYuv,
+                            TComYuv*    pcResiYuv,
+                      const ComponentID compID,
+                            TComTU     &rTu)
+{
+  if (!rTu.ProcessComponentSection(compID))
+  {
+    return;
+  }
+  const Bool       bIsLuma = isLuma(compID);
+
+
+  TComDataCU *pcCU = rTu.getCU();
+  const TComSPS &sps=*(pcCU->getSlice()->getSPS());
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  const TComRectangle &tuRect  =rTu.getRect(compID);
+  const UInt uiWidth           = tuRect.width;
+  const UInt uiHeight          = tuRect.height;
+  const UInt uiStride          = pcRecoYuv->getStride (compID);
+        Pel* piPred            = pcPredYuv->getAddr( compID, uiAbsPartIdx );
+  const ChromaFormat chFmt     = rTu.GetChromaFormat();
+
+  if (uiWidth != uiHeight)
+  {
+    //------------------------------------------------
+
+    //split at current level if dividing into square sub-TUs
+
+    TComTURecurse subTURecurse(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+    //recurse further
+    do
+    {
+      xIntraRecBlk(pcRecoYuv, pcPredYuv, pcResiYuv, compID, subTURecurse);
+    } while (subTURecurse.nextSection(rTu));
+
+    //------------------------------------------------
+
+    return;
+  }
+
+  const UInt uiChPredMode  = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
+  const UInt partsPerMinCU = 1<<(2*(sps.getMaxTotalCUDepth() - sps.getLog2DiffMaxMinCodingBlockSize()));
+  const UInt uiChCodedMode = (uiChPredMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt, partsPerMinCU)) : uiChPredMode;
+  const UInt uiChFinalMode = ((chFmt == CHROMA_422)       && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;
+
   //===== init availability pattern =====
   Bool  bAboveAvail = false;
   Bool  bLeftAvail  = false;
-  pcCU->getPattern()->initPattern   ( pcCU, uiTrDepth, uiAbsPartIdx );
-  pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, 
-                                     m_pcPrediction->getPredicBuf       (),
-                                     m_pcPrediction->getPredicBufWidth  (),
-                                     m_pcPrediction->getPredicBufHeight (),
-                                     bAboveAvail, bLeftAvail );
-  
+
+  const Bool bUseFilteredPredictions=TComPrediction::filteringIntraReferenceSamples(compID, uiChFinalMode, uiWidth, uiHeight, chFmt, pcCU->getSlice()->getSPS()->getSpsRangeExtension().getIntraSmoothingDisabledFlag());
+
+#if DEBUG_STRING
+  std::ostream &ss(std::cout);
+#endif
+
+  DEBUG_STRING_NEW(sTemp)
+  m_pcPrediction->initIntraPatternChType( rTu, bAboveAvail, bLeftAvail, compID, bUseFilteredPredictions  DEBUG_STRING_PASS_INTO(sTemp) );
+
+
   //===== get prediction signal =====
 #if H_3D_DIM
@@ -967,9 +1017,26 @@
   {
 #endif
-  m_pcPrediction->predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+
+  m_pcPrediction->predIntraAng( compID,   uiChFinalMode, 0 /* Decoder does not have an original image */, 0, piPred, uiStride, rTu, bAboveAvail, bLeftAvail, bUseFilteredPredictions );
 #if H_3D_DIM
   }
 #endif
-  
+
+#if DEBUG_STRING
+  ss << sTemp;
+#endif
+
+  //===== inverse transform =====
+  Pel*      piResi            = pcResiYuv->getAddr( compID, uiAbsPartIdx );
+  TCoeff*   pcCoeff           = pcCU->getCoeff(compID) + rTu.getCoefficientOffset(compID);//( uiNumCoeffInc * uiAbsPartIdx );
+
+  const QpParam cQP(*pcCU, compID);
+
+
+  DEBUG_STRING_NEW(sDebug);
+#if DEBUG_STRING
+  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTRA);
+  std::string *psDebug=(DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask) ? &sDebug : 0;
+#endif
 #if H_3D
   Bool useDltFlag = (isDimMode( uiLumaPredMode ) || uiLumaPredMode == HOR_IDX || uiLumaPredMode == VER_IDX || uiLumaPredMode == DC_IDX) && pcCU->getSlice()->getIsDepth() && pcCU->getSlice()->getPPS()->getDLT()->getUseDLTFlag(pcCU->getSlice()->getLayerIdInVps());
@@ -977,27 +1044,112 @@
   if ( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth ) || useDltFlag )
 #else
-  if ( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth ) )
-#endif
-  {
-  //===== inverse transform =====
-  m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
-
-  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)TEXT_LUMA];
-    assert(scalingListType < SCALING_LIST_NUM);
-  m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA, pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
-
-  
+  if (pcCU->getCbf(uiAbsPartIdx, compID, rTu.GetTransformDepthRel()) != 0)
+#endif
+  {
+    m_pcTrQuant->invTransformNxN( rTu, compID, piResi, uiStride, pcCoeff, cQP DEBUG_STRING_PASS_INTO(psDebug) );
+  }
+  else
+  {
+    for (UInt y = 0; y < uiHeight; y++)
+    {
+      for (UInt x = 0; x < uiWidth; x++)
+      {
+        piResi[(y * uiStride) + x] = 0;
+      }
+    }
+  }
+
+#if DEBUG_STRING
+  if (psDebug)
+  {
+    ss << (*psDebug);
+  }
+#endif
+
   //===== reconstruction =====
-  Pel* pPred      = piPred;
-  Pel* pResi      = piResi;
-  Pel* pReco      = piReco;
-  Pel* pRecIPred  = piRecIPred;
+  const UInt uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride(compID);
+
+  const Bool useCrossComponentPrediction = isChroma(compID) && (pcCU->getCrossComponentPredictionAlpha(uiAbsPartIdx, compID) != 0);
+  const Pel* pResiLuma  = pcResiYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
+  const Int  strideLuma = pcResiYuv->getStride( COMPONENT_Y );
+
+        Pel* pPred      = piPred;
+        Pel* pResi      = piResi;
+        Pel* pReco      = pcRecoYuv->getAddr( compID, uiAbsPartIdx );
+        Pel* pRecIPred  = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu() + uiAbsPartIdx );
+
+
+#if DEBUG_STRING
+  const Bool bDebugPred=((DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+  const Bool bDebugResi=((DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+  const Bool bDebugReco=((DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+  if (bDebugPred || bDebugResi || bDebugReco)
+  {
+    ss << "###: " << "CompID: " << compID << " pred mode (ch/fin): " << uiChPredMode << "/" << uiChFinalMode << " absPartIdx: " << rTu.GetAbsPartIdxTU() << std::endl;
+  }
+#endif
+
+  const Int clipbd = sps.getBitDepth(toChannelType(compID));
+#if O0043_BEST_EFFORT_DECODING
+  const Int bitDepthDelta = sps.getStreamBitDepth(toChannelType(compID)) - clipbd;
+#endif
+
+  if( useCrossComponentPrediction )
+  {
+    TComTrQuant::crossComponentPrediction( rTu, compID, pResiLuma, piResi, piResi, uiWidth, uiHeight, strideLuma, uiStride, uiStride, true );
+  }
+
   for( UInt uiY = 0; uiY < uiHeight; uiY++ )
   {
+#if DEBUG_STRING
+    if (bDebugPred || bDebugResi || bDebugReco)
+    {
+      ss << "###: ";
+    }
+
+    if (bDebugPred)
+    {
+      ss << " - pred: ";
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        ss << pPred[ uiX ] << ", ";
+      }
+    }
+    if (bDebugResi)
+    {
+      ss << " - resi: ";
+    }
+#endif
+
     for( UInt uiX = 0; uiX < uiWidth; uiX++ )
     {
-      pReco    [ uiX ] = ClipY( pPred[ uiX ] + pResi[ uiX ] );
+#if DEBUG_STRING
+      if (bDebugResi)
+      {
+        ss << pResi[ uiX ] << ", ";
+      }
+#endif
+#if O0043_BEST_EFFORT_DECODING
+      pReco    [ uiX ] = ClipBD( rightShiftEvenRounding<Pel>(pPred[ uiX ] + pResi[ uiX ], bitDepthDelta), clipbd );
+#else
+      pReco    [ uiX ] = ClipBD( pPred[ uiX ] + pResi[ uiX ], clipbd );
+#endif
       pRecIPred[ uiX ] = pReco[ uiX ];
     }
+#if DEBUG_STRING
+    if (bDebugReco)
+    {
+      ss << " - reco: ";
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        ss << pReco[ uiX ] << ", ";
+      }
+    }
+
+    if (bDebugPred || bDebugResi || bDebugReco)
+    {
+      ss << "\n";
+    }
+#endif
     pPred     += uiStride;
     pResi     += uiStride;
@@ -1006,145 +1158,7 @@
   }
 }
-  else
-  {
-    //===== reconstruction =====
-    Pel* pPred      = piPred;
-    Pel* pReco      = piReco;
-    Pel* pRecIPred  = piRecIPred;
-    for ( Int y = 0; y < uiHeight; y++ )
-    {
-      for ( Int x = 0; x < uiWidth; x++ )
-      {
-        pReco    [ x ] = pPred[ x ];
-        pRecIPred[ x ] = pReco[ x ];
-      }
-      pPred     += uiStride;
-      pReco     += uiStride;
-      pRecIPred += uiRecIPredStride;
-    }
-  }
-}
-
-
-Void
-TDecCu::xIntraRecChromaBlk( TComDataCU* pcCU,
-                           UInt        uiTrDepth,
-                           UInt        uiAbsPartIdx,
-                           TComYuv*    pcRecoYuv,
-                           TComYuv*    pcPredYuv, 
-                           TComYuv*    pcResiYuv,
-                           UInt        uiChromaId )
-{
-  UInt uiFullDepth  = pcCU->getDepth( 0 ) + uiTrDepth;
-  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-
-  if( uiLog2TrSize == 2 )
-  {
-    assert( uiTrDepth > 0 );
-    uiTrDepth--;
-    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
-    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
-    if( !bFirstQ )
-    {
-      return;
-    }
-  }
-
-  TextType  eText             = ( uiChromaId > 0 ? TEXT_CHROMA_V : TEXT_CHROMA_U );
-  UInt      uiWidth           = pcCU     ->getWidth   ( 0 ) >> ( uiTrDepth + 1 );
-  UInt      uiHeight          = pcCU     ->getHeight  ( 0 ) >> ( uiTrDepth + 1 );
-  UInt      uiStride          = pcRecoYuv->getCStride ();
-  Pel*      piReco            = ( uiChromaId > 0 ? pcRecoYuv->getCrAddr( uiAbsPartIdx ) : pcRecoYuv->getCbAddr( uiAbsPartIdx ) );
-  Pel*      piPred            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
-  Pel*      piResi            = ( uiChromaId > 0 ? pcResiYuv->getCrAddr( uiAbsPartIdx ) : pcResiYuv->getCbAddr( uiAbsPartIdx ) );
-
-  UInt      uiNumCoeffInc     = ( ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) ) >> 2;
-  TCoeff*   pcCoeff           = ( uiChromaId > 0 ? pcCU->getCoeffCr() : pcCU->getCoeffCb() ) + ( uiNumCoeffInc * uiAbsPartIdx );
-
-  UInt      uiChromaPredMode  = pcCU->getChromaIntraDir( 0 );
-
-  UInt      uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-  Pel*      piRecIPred        = ( uiChromaId > 0 ? pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder ) : pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder ) );
-  UInt      uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride();
-  Bool      useTransformSkipChroma = pcCU->getTransformSkip(uiAbsPartIdx,eText);
-  //===== init availability pattern =====
-  Bool  bAboveAvail = false;
-  Bool  bLeftAvail  = false;
-  pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
-
-  pcCU->getPattern()->initAdiPatternChroma( pcCU, uiAbsPartIdx, uiTrDepth,
-    m_pcPrediction->getPredicBuf       (),
-    m_pcPrediction->getPredicBufWidth  (),
-    m_pcPrediction->getPredicBufHeight (),
-    bAboveAvail, bLeftAvail );
-  Int* pPatChroma   = ( uiChromaId > 0 ? pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_pcPrediction->getPredicBuf() ) : pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_pcPrediction->getPredicBuf() ) );
-
-  //===== get prediction signal =====
-  {
-    if( uiChromaPredMode == DM_CHROMA_IDX )
-    {
-      uiChromaPredMode = pcCU->getLumaIntraDir( 0 );
 #if H_3D_DIM
       mapDepthModeToIntraDir( uiChromaPredMode );
 #endif
-    }
-    m_pcPrediction->predIntraChromaAng( pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );  
-  }
-
-  if ( pcCU->getCbf( uiAbsPartIdx, eText, uiTrDepth ) )
-  {
-    //===== inverse transform =====
-    Int curChromaQpOffset;
-    if(eText == TEXT_CHROMA_U)
-    {
-      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
-    }
-    else
-    {
-      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
-    }
-    m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), eText, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eText];
-    assert(scalingListType < SCALING_LIST_NUM);
-    m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eText, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
-
-    //===== reconstruction =====
-    Pel* pPred      = piPred;
-    Pel* pResi      = piResi;
-    Pel* pReco      = piReco;
-    Pel* pRecIPred  = piRecIPred;
-    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-    {
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        pReco    [ uiX ] = ClipC( pPred[ uiX ] + pResi[ uiX ] );
-        pRecIPred[ uiX ] = pReco[ uiX ];
-      }
-      pPred     += uiStride;
-      pResi     += uiStride;
-      pReco     += uiStride;
-      pRecIPred += uiRecIPredStride;
-    }
-  }
-  else
-  {
-    //===== reconstruction =====
-    Pel* pPred      = piPred;
-    Pel* pReco      = piReco;
-    Pel* pRecIPred  = piRecIPred;
-    for ( Int y = 0; y < uiHeight; y++ )
-    {
-      for ( Int x = 0; x < uiWidth; x++ )
-      {
-        pReco    [ x ] = pPred[ x ];
-        pRecIPred[ x ] = pReco[ x ];
-      }
-      pPred     += uiStride;
-      pReco     += uiStride;
-      pRecIPred += uiRecIPredStride;
-    }    
-  }
-}
 
 
@@ -1152,8 +1166,4 @@
 TDecCu::xReconIntraQT( TComDataCU* pcCU, UInt uiDepth )
 {
-  UInt  uiInitTrDepth = ( pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1 );
-  UInt  uiNumPart     = pcCU->getNumPartitions();
-  UInt  uiNumQParts   = pcCU->getTotalNumPart() >> 2;
-  
   if (pcCU->getIPCMFlag(0))
   {
@@ -1161,15 +1171,19 @@
     return;
   }
-
-  for( UInt uiPU = 0; uiPU < uiNumPart; uiPU++ )
-  {
-    xIntraLumaRecQT( pcCU, uiInitTrDepth, uiPU * uiNumQParts, m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth] );
-  }  
-
-  for( UInt uiPU = 0; uiPU < uiNumPart; uiPU++ )
-  {
-    xIntraChromaRecQT( pcCU, uiInitTrDepth, uiPU * uiNumQParts, m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth] );
-  }
-
+  const UInt numChType = pcCU->getPic()->getChromaFormat()!=CHROMA_400 ? 2 : 1;
+  for (UInt chType=CHANNEL_TYPE_LUMA; chType<numChType; chType++)
+  {
+    const ChannelType chanType=ChannelType(chType);
+    const Bool NxNPUHas4Parts = ::isChroma(chanType) ? enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()) : true;
+    const UInt uiInitTrDepth = ( pcCU->getPartitionSize(0) != SIZE_2Nx2N && NxNPUHas4Parts ? 1 : 0 );
+
+    TComTURecurse tuRecurseCU(pcCU, 0);
+    TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);
+
+    do
+    {
+      xIntraRecQT( m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], chanType, tuRecurseWithPU );
+    } while (tuRecurseWithPU.nextSection(tuRecurseCU));
+  }
 }
 
@@ -1369,70 +1383,48 @@
 #endif
 
-/** Function for deriving recontructed PU/CU Luma sample with QTree structure
- * \param pcCU pointer of current CU
- * \param uiTrDepth current tranform split depth
- * \param uiAbsPartIdx  part index
+
+/** Function for deriving reconstructed PU/CU chroma samples with QTree structure
  * \param pcRecoYuv pointer to reconstructed sample arrays
  * \param pcPredYuv pointer to prediction sample arrays
  * \param pcResiYuv pointer to residue sample arrays
- * 
- \ This function dervies recontructed PU/CU Luma sample with recursive QTree structure
+ * \param chType    texture channel type (luma/chroma)
+ * \param rTu       reference to transform data
+ *
+ \ This function derives reconstructed PU/CU chroma samples with QTree recursive structure
  */
+
 Void
-TDecCu::xIntraLumaRecQT( TComDataCU* pcCU,
-                     UInt        uiTrDepth,
-                     UInt        uiAbsPartIdx,
-                     TComYuv*    pcRecoYuv,
-                     TComYuv*    pcPredYuv, 
-                     TComYuv*    pcResiYuv )
-{
-  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+TDecCu::xIntraRecQT(TComYuv*    pcRecoYuv,
+                    TComYuv*    pcPredYuv,
+                    TComYuv*    pcResiYuv,
+                    const ChannelType chType,
+                    TComTU     &rTu)
+{
+  UInt uiTrDepth    = rTu.GetTransformDepthRel();
+  TComDataCU *pcCU  = rTu.getCU();
+  UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
   UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
   if( uiTrMode == uiTrDepth )
   {
-    xIntraRecLumaBlk  ( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv );
+    if (isLuma(chType))
+    {
+      xIntraRecBlk( pcRecoYuv, pcPredYuv, pcResiYuv, COMPONENT_Y,  rTu );
+    }
+    else
+    {
+      const UInt numValidComp=getNumberValidComponents(rTu.GetChromaFormat());
+      for(UInt compID=COMPONENT_Cb; compID<numValidComp; compID++)
+      {
+        xIntraRecBlk( pcRecoYuv, pcPredYuv, pcResiYuv, ComponentID(compID), rTu );
+      }
+    }
   }
   else
   {
-    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
-    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
-    {
-      xIntraLumaRecQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv, pcPredYuv, pcResiYuv );
-    }
-  }
-}
-
-/** Function for deriving recontructed PU/CU chroma samples with QTree structure
- * \param pcCU pointer of current CU
- * \param uiTrDepth current tranform split depth
- * \param uiAbsPartIdx  part index
- * \param pcRecoYuv pointer to reconstructed sample arrays
- * \param pcPredYuv pointer to prediction sample arrays
- * \param pcResiYuv pointer to residue sample arrays
- * 
- \ This function dervies recontructed PU/CU chroma samples with QTree recursive structure
- */
-Void
-TDecCu::xIntraChromaRecQT( TComDataCU* pcCU,
-                     UInt        uiTrDepth,
-                     UInt        uiAbsPartIdx,
-                     TComYuv*    pcRecoYuv,
-                     TComYuv*    pcPredYuv, 
-                     TComYuv*    pcResiYuv )
-{
-  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
-  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
-  if( uiTrMode == uiTrDepth )
-  {
-    xIntraRecChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv, 0 );
-    xIntraRecChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv, 1 );
-  }
-  else
-  {
-    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
-    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
-    {
-      xIntraChromaRecQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv, pcPredYuv, pcResiYuv );
-    }
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xIntraRecQT( pcRecoYuv, pcPredYuv, pcResiYuv, chType, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
   }
 }
@@ -1440,42 +1432,25 @@
 Void TDecCu::xCopyToPic( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth )
 {
-  UInt uiCUAddr = pcCU->getAddr();
-  
-  m_ppcYuvReco[uiDepth]->copyToPicYuv  ( pcPic->getPicYuvRec (), uiCUAddr, uiZorderIdx );
-  
+  UInt uiCtuRsAddr = pcCU->getCtuRsAddr();
+
+  m_ppcYuvReco[uiDepth]->copyToPicYuv  ( pcPic->getPicYuvRec (), uiCtuRsAddr, uiZorderIdx );
+
   return;
 }
 
-Void TDecCu::xDecodeInterTexture ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
-{
-  UInt    uiWidth    = pcCU->getWidth ( uiAbsPartIdx );
-  UInt    uiHeight   = pcCU->getHeight( uiAbsPartIdx );
-  TCoeff* piCoeff;
-  
-  Pel*    pResi;
-  UInt    trMode = pcCU->getTransformIdx( uiAbsPartIdx );
-  
-  // Y
-  piCoeff = pcCU->getCoeffY();
-  pResi = m_ppcYuvResi[uiDepth]->getLumaAddr();
-
-  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
-
-  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_LUMA, pResi, 0, m_ppcYuvResi[uiDepth]->getStride(), uiWidth, uiHeight, trMode, 0, piCoeff );
-  
-  // Cb and Cr
-  Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
-  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-  uiWidth  >>= 1;
-  uiHeight >>= 1;
-  piCoeff = pcCU->getCoeffCb(); pResi = m_ppcYuvResi[uiDepth]->getCbAddr();
-  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_U, pResi, 0, m_ppcYuvResi[uiDepth]->getCStride(), uiWidth, uiHeight, trMode, 0, piCoeff );
-
-  curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
-  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-  piCoeff = pcCU->getCoeffCr(); pResi = m_ppcYuvResi[uiDepth]->getCrAddr();
-  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_V, pResi, 0, m_ppcYuvResi[uiDepth]->getCStride(), uiWidth, uiHeight, trMode, 0, piCoeff );
+Void TDecCu::xDecodeInterTexture ( TComDataCU* pcCU, UInt uiDepth )
+{
+
+  TComTURecurse tuRecur(pcCU, 0, uiDepth);
+
+  for(UInt ch=0; ch<pcCU->getPic()->getNumberValidComponents(); ch++)
+  {
+    const ComponentID compID=ComponentID(ch);
+    DEBUG_STRING_OUTPUT(std::cout, debug_reorder_data_inter_token[compID])
+
+    m_pcTrQuant->invRecurTransformNxN ( compID, m_ppcYuvResi[uiDepth], tuRecur );
+  }
+
+  DEBUG_STRING_OUTPUT(std::cout, debug_reorder_data_inter_token[MAX_NUM_COMPONENT])
 }
 
@@ -1488,38 +1463,17 @@
  * \param uiWidth CU width
  * \param uiHeight CU height
- * \param ttText texture component type
+ * \param compID colour component ID
  * \returns Void
  */
-Void TDecCu::xDecodePCMTexture( TComDataCU* pcCU, UInt uiPartIdx, Pel *piPCM, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType ttText)
-{
-  UInt uiX, uiY;
-  Pel* piPicReco;
-  UInt uiPicStride;
-  UInt uiPcmLeftShiftBit; 
-
-  if( ttText == TEXT_LUMA )
-  {
-    uiPicStride   = pcCU->getPic()->getPicYuvRec()->getStride();
-    piPicReco = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
-    uiPcmLeftShiftBit = g_bitDepthY - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
-  }
-  else
-  {
-    uiPicStride = pcCU->getPic()->getPicYuvRec()->getCStride();
-
-    if( ttText == TEXT_CHROMA_U )
-    {
-      piPicReco = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
-    }
-    else
-    {
-      piPicReco = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
-    }
-    uiPcmLeftShiftBit = g_bitDepthC - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
-  }
-
-  for( uiY = 0; uiY < uiHeight; uiY++ )
-  {
-    for( uiX = 0; uiX < uiWidth; uiX++ )
+Void TDecCu::xDecodePCMTexture( TComDataCU* pcCU, const UInt uiPartIdx, const Pel *piPCM, Pel* piReco, const UInt uiStride, const UInt uiWidth, const UInt uiHeight, const ComponentID compID)
+{
+        Pel* piPicReco         = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu()+uiPartIdx);
+  const UInt uiPicStride       = pcCU->getPic()->getPicYuvRec()->getStride(compID);
+  const TComSPS &sps           = *(pcCU->getSlice()->getSPS());
+  const UInt uiPcmLeftShiftBit = sps.getBitDepth(toChannelType(compID)) - sps.getPCMBitDepth(toChannelType(compID));
+
+  for(UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for(UInt uiX = 0; uiX < uiWidth; uiX++ )
     {
       piReco[uiX] = (piPCM[uiX] << uiPcmLeftShiftBit);
@@ -1539,80 +1493,52 @@
 Void TDecCu::xReconPCM( TComDataCU* pcCU, UInt uiDepth )
 {
-  // Luma
-  UInt uiWidth  = (g_uiMaxCUWidth >> uiDepth);
-  UInt uiHeight = (g_uiMaxCUHeight >> uiDepth);
-
-  Pel* piPcmY = pcCU->getPCMSampleY();
-  Pel* piRecoY = m_ppcYuvReco[uiDepth]->getLumaAddr(0, uiWidth);
-
-  UInt uiStride = m_ppcYuvResi[uiDepth]->getStride();
-
-  xDecodePCMTexture( pcCU, 0, piPcmY, piRecoY, uiStride, uiWidth, uiHeight, TEXT_LUMA);
-
-  // Cb and Cr
-  UInt uiCWidth  = (uiWidth>>1);
-  UInt uiCHeight = (uiHeight>>1);
-
-  Pel* piPcmCb = pcCU->getPCMSampleCb();
-  Pel* piPcmCr = pcCU->getPCMSampleCr();
-  Pel* pRecoCb = m_ppcYuvReco[uiDepth]->getCbAddr();
-  Pel* pRecoCr = m_ppcYuvReco[uiDepth]->getCrAddr();
-
-  UInt uiCStride = m_ppcYuvReco[uiDepth]->getCStride();
-
-  xDecodePCMTexture( pcCU, 0, piPcmCb, pRecoCb, uiCStride, uiCWidth, uiCHeight, TEXT_CHROMA_U);
-  xDecodePCMTexture( pcCU, 0, piPcmCr, pRecoCr, uiCStride, uiCWidth, uiCHeight, TEXT_CHROMA_V);
-}
-
-/** Function for filling the PCM buffer of a CU using its reconstructed sample array 
- * \param pcCU pointer to current CU
- * \param uiDepth CU Depth
- * \returns Void
+  const UInt maxCuWidth     = pcCU->getSlice()->getSPS()->getMaxCUWidth();
+  const UInt maxCuHeight    = pcCU->getSlice()->getSPS()->getMaxCUHeight();
+  for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+  {
+    const ComponentID compID = ComponentID(ch);
+    const UInt width  = (maxCuWidth >>(uiDepth+m_ppcYuvResi[uiDepth]->getComponentScaleX(compID)));
+    const UInt height = (maxCuHeight>>(uiDepth+m_ppcYuvResi[uiDepth]->getComponentScaleY(compID)));
+    const UInt stride = m_ppcYuvResi[uiDepth]->getStride(compID);
+    Pel * pPCMChannel = pcCU->getPCMSample(compID);
+    Pel * pRecChannel = m_ppcYuvReco[uiDepth]->getAddr(compID);
+    xDecodePCMTexture( pcCU, 0, pPCMChannel, pRecChannel, stride, width, height, compID );
+  }
+}
+
+/** Function for filling the PCM buffer of a CU using its reconstructed sample array
+ * \param pCU   pointer to current CU
+ * \param depth CU Depth
  */
 Void TDecCu::xFillPCMBuffer(TComDataCU* pCU, UInt depth)
 {
-  // Luma
-  UInt width  = (g_uiMaxCUWidth >> depth);
-  UInt height = (g_uiMaxCUHeight >> depth);
-
-  Pel* pPcmY = pCU->getPCMSampleY();
-  Pel* pRecoY = m_ppcYuvReco[depth]->getLumaAddr(0, width);
-
-  UInt stride = m_ppcYuvReco[depth]->getStride();
-
-  for(Int y = 0; y < height; y++ )
-  {
-    for(Int x = 0; x < width; x++ )
-    {
-      pPcmY[x] = pRecoY[x];
-    }
-    pPcmY += width;
-    pRecoY += stride;
-  }
-
-  // Cb and Cr
-  UInt widthC  = (width>>1);
-  UInt heightC = (height>>1);
-
-  Pel* pPcmCb = pCU->getPCMSampleCb();
-  Pel* pPcmCr = pCU->getPCMSampleCr();
-  Pel* pRecoCb = m_ppcYuvReco[depth]->getCbAddr();
-  Pel* pRecoCr = m_ppcYuvReco[depth]->getCrAddr();
-
-  UInt strideC = m_ppcYuvReco[depth]->getCStride();
-
-  for(Int y = 0; y < heightC; y++ )
-  {
-    for(Int x = 0; x < widthC; x++ )
-    {
-      pPcmCb[x] = pRecoCb[x];
-      pPcmCr[x] = pRecoCr[x];
-    }
-    pPcmCr += widthC;
-    pPcmCb += widthC;
-    pRecoCb += strideC;
-    pRecoCr += strideC;
-  }
-
+  const ChromaFormat format = pCU->getPic()->getChromaFormat();
+  const UInt numValidComp   = getNumberValidComponents(format);
+  const UInt maxCuWidth     = pCU->getSlice()->getSPS()->getMaxCUWidth();
+  const UInt maxCuHeight    = pCU->getSlice()->getSPS()->getMaxCUHeight();
+
+  for (UInt componentIndex = 0; componentIndex < numValidComp; componentIndex++)
+  {
+    const ComponentID component = ComponentID(componentIndex);
+
+    const UInt width  = maxCuWidth  >> (depth + getComponentScaleX(component, format));
+    const UInt height = maxCuHeight >> (depth + getComponentScaleY(component, format));
+
+    Pel *source      = m_ppcYuvReco[depth]->getAddr(component, 0, width);
+    Pel *destination = pCU->getPCMSample(component);
+
+    const UInt sourceStride = m_ppcYuvReco[depth]->getStride(component);
+
+    for (Int line = 0; line < height; line++)
+    {
+      for (Int column = 0; column < width; column++)
+      {
+        destination[column] = source[column];
+      }
+
+      source      += sourceStride;
+      destination += width;
+    }
+  }
 }
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCu.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecCu.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -44,5 +44,4 @@
 
 #include "TLibCommon/TComTrQuant.h"
-#include "TLibCommon/TComPrediction.h"
 #include "TDecEntropy.h"
 
@@ -62,5 +61,5 @@
   TComYuv**           m_ppcYuvReco;       ///< array of prediction & reconstruction buffer
   TComDataCU**        m_ppcCU;            ///< CU data array
-  
+
 #if H_3D_DBBP
   TComYuv**           m_ppcYuvRecoDBBP;
@@ -73,54 +72,56 @@
 
   Bool                m_bDecodeDQP;
-  
+  Bool                m_IsChromaQpAdjCoded;
+
 public:
   TDecCu();
   virtual ~TDecCu();
-  
+
   /// initialize access channels
   Void  init                    ( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction );
-  
+
   /// create internal buffers
-  Void  create                  ( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight );
-  
+  Void  create                  ( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight, ChromaFormat chromaFormatIDC );
+
   /// destroy internal buffers
   Void  destroy                 ();
-  
-  /// decode CU information
-  Void  decodeCU                ( TComDataCU* pcCU, UInt& ruiIsLast );
-  
-  /// reconstruct CU information
-  Void  decompressCU            ( TComDataCU* pcCU );
-  
+
+  /// decode Ctu information
+  Void  decodeCtu               ( TComDataCU* pCtu, Bool &isLastCtuOfSliceSegment );
+
+  /// reconstruct Ctu information
+  Void  decompressCtu           ( TComDataCU* pCtu );
+
 protected:
-  
-  Void xDecodeCU                ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth, UInt &ruiIsLast);
-  Void xFinishDecodeCU          ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth, UInt &ruiIsLast);
-  Bool xDecodeSliceEnd          ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth);
-  Void xDecompressCU            ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
+  Void xDecodeCU                ( TComDataCU* const pcCU, const UInt uiAbsPartIdx, const UInt uiDepth, Bool &isLastCtuOfSliceSegment);
+  Void xFinishDecodeCU          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool &isLastCtuOfSliceSegment);
+  Bool xDecodeSliceEnd          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void xDecompressCU            ( TComDataCU* pCtu, UInt uiAbsPartIdx, UInt uiDepth );
+
   Void xReconInter              ( TComDataCU* pcCU, UInt uiDepth );
-  
+
 #if H_3D_DBBP
   Void xReconInterDBBP          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
   
-  Void  xReconIntraQT           ( TComDataCU* pcCU, UInt uiDepth );
-  Void  xIntraRecLumaBlk        ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
-  Void  xIntraRecChromaBlk      ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, UInt uiChromaId );
-  
-  Void  xReconPCM               ( TComDataCU* pcCU, UInt uiDepth );
+  Void xReconIntraQT            ( TComDataCU* pcCU, UInt uiDepth );
+  Void xIntraRecBlk             ( TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, const ComponentID component, TComTU &rTu );
+  Void xIntraRecQT              ( TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, const ChannelType chType, TComTU &rTu );
 
-  Void xDecodeInterTexture      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  Void xDecodePCMTexture        ( TComDataCU* pcCU, UInt uiPartIdx, Pel *piPCM, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType ttText);
-  
+  Void xReconPCM                ( TComDataCU* pcCU, UInt uiDepth );
+
+  Void xDecodeInterTexture      ( TComDataCU* pcCU, UInt uiDepth );
+  Void xDecodePCMTexture        ( TComDataCU* pcCU, const UInt uiPartIdx, const Pel *piPCM, Pel* piReco, const UInt uiStride, const UInt uiWidth, const UInt uiHeight, const ComponentID compID);
+
   Void xCopyToPic               ( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth );
-
-  Void  xIntraLumaRecQT         ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
-  Void  xIntraChromaRecQT       ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
 
   Bool getdQPFlag               ()                        { return m_bDecodeDQP;        }
   Void setdQPFlag               ( Bool b )                { m_bDecodeDQP = b;           }
+  Bool getIsChromaQpAdjCoded    ()                        { return m_IsChromaQpAdjCoded;        }
+  Void setIsChromaQpAdjCoded    ( Bool b )                { m_IsChromaQpAdjCoded = b;           }
+
   Void xFillPCMBuffer           (TComDataCU* pCU, UInt depth);
+
 #if H_3D
   Void xReconDIS               ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
@@ -132,4 +133,5 @@
   Void xReconInterSDC           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
+
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,4 +37,12 @@
 
 #include "TDecEntropy.h"
+#include "TLibCommon/TComTU.h"
+#include "TLibCommon/TComPrediction.h"
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+#include "../TLibCommon/Debug.h"
+static const Bool bDebugRQT = DebugOptionList::DebugRQT.getInt()!=0;
+static const Bool bDebugPredEnabled = DebugOptionList::DebugPred.getInt()!=0;
+#endif
 
 //! \ingroup TLibDecoder
@@ -69,13 +77,14 @@
 }
 
+
 /** decode merge flag
  * \param pcSubCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
- * \param uiPUIdx 
+ * \param uiPUIdx
  * \returns Void
  */
 Void TDecEntropy::decodeMergeFlag( TComDataCU* pcSubCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
-{ 
+{
   // at least one merge candidate exists
   m_pcEntropyDecoderIf->parseMergeFlag( pcSubCU, uiAbsPartIdx, uiDepth, uiPUIdx );
@@ -84,8 +93,6 @@
 /** decode merge index
  * \param pcCU
- * \param uiPartIdx 
- * \param uiAbsPartIdx 
- * \param puhInterDirNeighbours pointer to list of inter direction from the casual neighbours
- * \param pcMvFieldNeighbours pointer to list of motion vector field from the casual neighbours
+ * \param uiPartIdx
+ * \param uiAbsPartIdx
  * \param uiDepth
  * \returns Void
@@ -156,12 +163,18 @@
     decodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx, uiDepth );
 #if H_3D_DIM_SDC
-    decodeSDCFlag   ( pcCU, uiAbsPartIdx, uiDepth );    
-#if H_3D_DISABLE_CHROMA
-    if(!pcCU->getSDCFlag(uiAbsPartIdx) && pcCU->getSlice()->getSPS()->getChromaFormatIdc() != 0  )
-#else
+    decodeSDCFlag   ( pcCU, uiAbsPartIdx, uiDepth );
     if(!pcCU->getSDCFlag(uiAbsPartIdx))
 #endif
-#endif
-    decodeIntraDirModeChroma( pcCU, uiAbsPartIdx, uiDepth );
+    if (pcCU->getPic()->getChromaFormat()!=CHROMA_400)
+    {
+      decodeIntraDirModeChroma( pcCU, uiAbsPartIdx, uiDepth );
+      if (enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()) && pcCU->getPartitionSize( uiAbsPartIdx )==SIZE_NxN)
+      {
+        UInt uiPartOffset = ( pcCU->getPic()->getNumPartitionsInCtu() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+        decodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset,   uiDepth+1 );
+        decodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset*2, uiDepth+1 );
+        decodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset*3, uiDepth+1 );
+      }
+    }
   }
   else                                                                // if it is Inter mode, encode motion vector and reference index
@@ -171,5 +184,5 @@
 }
 
-/** Parse I_PCM information. 
+/** Parse I_PCM information.
  * \param pcCU  pointer to CUpointer to CU
  * \param uiAbsPartIdx CU index
@@ -185,5 +198,5 @@
     return;
   }
-  
+
   m_pcEntropyDecoderIf->parseIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
 }
@@ -197,9 +210,21 @@
 {
   m_pcEntropyDecoderIf->parseIntraDirChroma( pcCU, uiAbsPartIdx, uiDepth );
-}
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugPredEnabled)
+  {
+    UInt cdir=pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, uiAbsPartIdx);
+    if (cdir==36)
+    {
+      cdir=pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiAbsPartIdx);
+    }
+    printf("coding chroma Intra dir: %d, uiAbsPartIdx: %d, luma dir: %d\n", cdir, uiAbsPartIdx, pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiAbsPartIdx));
+  }
+#endif
+}
+
 
 /** decode motion information for every PU block.
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
  * \param pcSubCU
@@ -210,6 +235,5 @@
   PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
   UInt uiNumPU = ( ePartSize == SIZE_2Nx2N ? 1 : ( ePartSize == SIZE_NxN ? 4 : 2 ) );
-  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
-
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxTotalCUDepth() - uiDepth ) << 1 ) ) >> 4;
 #if H_3D_IV_MERGE
   TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
@@ -224,4 +248,7 @@
   UChar* puhInterDirSP = new UChar[pcCU->getPic()->getPicSym()->getNumPartition()]; 
 #endif
+#if H_3D_IV_MERGE
+  pcSubCU->copyDVInfoFrom( pcCU, uiAbsPartIdx);
+#endif
   for ( UInt ui = 0; ui < pcCU->getSlice()->getMaxNumMergeCand(); ui++ )
   {
@@ -229,11 +256,8 @@
   }
   Int numValidMergeCand = 0;
-  Bool isMerged = false;
+  Bool hasMergedCandList = false;
 
   pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
   pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
-#if H_3D_IV_MERGE
-  pcSubCU->copyDVInfoFrom( pcCU, uiAbsPartIdx);
-#endif
 #if H_3D
   for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
@@ -445,14 +469,22 @@
     {
       decodeMergeIndex( pcCU, uiPartIdx, uiSubPartIdx, uiDepth );
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      if (bDebugPredEnabled)
+      {
+        std::cout << "Coded merge flag, CU absPartIdx: " << uiAbsPartIdx << " PU(" << uiPartIdx << ") absPartIdx: " << uiSubPartIdx;
+        std::cout << " merge index: " << (UInt)pcCU->getMergeIndex(uiSubPartIdx) << std::endl;
+      }
+#endif
+
       UInt uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
-      if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 ) 
-      {
-        pcSubCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
-        if ( !isMerged )
-        {
+      if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 )
+      {
+        if ( !hasMergedCandList )
+        {
+          pcSubCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth ); // temporarily set.
           pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
-          isMerged = true;
-        }
-        pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth );
+          pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth ); // restore.
+          hasMergedCandList = true;
+        }
       }
       else
@@ -461,9 +493,10 @@
         pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
       }
+
       pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
 
       TComMv cTmpMv( 0, 0 );
       for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
-      {        
+      {
         if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
         {
@@ -472,4 +505,5 @@
           pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
           pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
+
         }
       }
@@ -479,5 +513,5 @@
       decodeInterDirPU( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
       for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
-      {        
+      {
         if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
         {
@@ -485,7 +519,18 @@
           decodeMvdPU      ( pcCU,    uiSubPartIdx,              uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
           decodeMVPIdxPU   ( pcSubCU, uiSubPartIdx-uiAbsPartIdx, uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
-        }
-      }
-    }
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+          if (bDebugPredEnabled)
+          {
+            std::cout << "refListIdx: " << uiRefListIdx << std::endl;
+            std::cout << "MVD horizontal: " << pcCU->getCUMvField(RefPicList(uiRefListIdx))->getMvd( uiAbsPartIdx ).getHor() << std::endl;
+            std::cout << "MVD vertical:   " << pcCU->getCUMvField(RefPicList(uiRefListIdx))->getMvd( uiAbsPartIdx ).getVer() << std::endl;
+            std::cout << "MVPIdxPU: " << pcCU->getMVPIdx(RefPicList( uiRefListIdx ), uiSubPartIdx) << std::endl;
+            std::cout << "InterDir: " << (UInt)pcCU->getInterDir(uiSubPartIdx) << std::endl;
+          }
+#endif
+        }
+      }
+    }
+
     if ( (pcCU->getInterDir(uiSubPartIdx) == 3) && pcSubCU->isBipredRestriction(uiPartIdx) )
     {
@@ -505,7 +550,7 @@
 /** decode inter direction for a PU block
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
- * \param uiPartIdx 
+ * \param uiPartIdx
  * \returns Void
  */
@@ -550,8 +595,8 @@
 /** decode motion vector difference for a PU block
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
  * \param uiPartIdx
- * \param eRefList 
+ * \param eRefList
  * \returns Void
  */
@@ -656,6 +701,11 @@
 #endif
 
-Void TDecEntropy::xDecodeTransform( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP, Int quadtreeTULog2MinSizeInCU)
-{
+Void TDecEntropy::xDecodeTransform        ( Bool& bCodeDQP, Bool& isChromaQpAdjCoded, TComTU &rTu, const Int quadtreeTULog2MinSizeInCU )
+{
+
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+  const UInt uiDepth=rTu.GetTransformDepthTotal();
+  const UInt uiTrDepth = rTu.GetTransformDepthRel();
 
 #if H_MV_ENC_DEC_TRAC
@@ -663,9 +713,10 @@
   UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
   UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  
+
   DTRACE_TU_S("=========== transform_tree ===========\n")
   DTRACE_TU("x0", uiLPelX)
   DTRACE_TU("x1", uiTPelY)
-  DTRACE_TU("log2TrafoSize", g_uiMaxCUWidth>>uiDepth)
+  
+  DTRACE_TU("log2TrafoSize", pcCU->getSlice()->getSPS()->getMaxCUWidth()  >> uiDepth )
   DTRACE_TU("trafoDepth"  , uiDepth)
 #endif
@@ -673,26 +724,24 @@
 
   UInt uiSubdiv;
-  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
-
-  if(uiTrIdx==0)
-  {
-    m_bakAbsPartIdxCU = uiAbsPartIdx;
-  }
-  if( uiLog2TrafoSize == 2 )
-  {
-    UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
-    if( ( uiAbsPartIdx % partNum ) == 0 )
-    {
-      m_uiBakAbsPartIdx   = uiAbsPartIdx;
-      m_uiBakChromaOffset = offsetChroma;
-    }
-  }
-  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  const UInt numValidComponent = pcCU->getPic()->getNumberValidComponents();
+  const Bool bChroma = isChromaEnabled(pcCU->getPic()->getChromaFormat());
+
+  const UInt uiLog2TrafoSize = rTu.GetLog2LumaTrSize();
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugRQT)
+  {
+    printf("x..codeTransform: offsetLuma=%d offsetChroma=%d absPartIdx=%d, uiDepth=%d\n width=%d, height=%d, uiTrIdx=%d, uiInnerQuadIdx=%d\n",
+        rTu.getCoefficientOffset(COMPONENT_Y), rTu.getCoefficientOffset(COMPONENT_Cb), uiAbsPartIdx, uiDepth, rTu.getRect(COMPONENT_Y).width, rTu.getRect(COMPONENT_Y).height, rTu.GetTransformDepthRel(), rTu.GetSectionNumber());
+    fflush(stdout);
+  }
+#endif
+
+  if( pcCU->isIntra(uiAbsPartIdx) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
   {
     uiSubdiv = 1;
   }
-  else if( (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && (pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER) && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ) && (uiDepth == pcCU->getDepth(uiAbsPartIdx)) )
-  {
-    uiSubdiv = (uiLog2TrafoSize > quadtreeTULog2MinSizeInCU);
+  else if( (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && (pcCU->isInter(uiAbsPartIdx)) && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ) && (uiDepth == pcCU->getDepth(uiAbsPartIdx)) )
+  {
+    uiSubdiv = (uiLog2TrafoSize >quadtreeTULog2MinSizeInCU);
   }
   else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
@@ -713,85 +762,51 @@
     m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
   }
-  
-  const UInt uiTrDepth = uiDepth - pcCU->getDepth( uiAbsPartIdx );
-  {
+
+  for(Int chan=COMPONENT_Cb; chan<numValidComponent; chan++)
+  {
+    const ComponentID compID=ComponentID(chan);
+    const UInt trDepthTotalAdj=rTu.GetTransformDepthTotalAdj(compID);
+
     const Bool bFirstCbfOfCU = uiTrDepth == 0;
+
     if( bFirstCbfOfCU )
     {
-      pcCU->setCbfSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
-      pcCU->setCbfSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
-    }
-    if( bFirstCbfOfCU || uiLog2TrafoSize > 2 )
-    {
-#if H_3D_DISABLE_CHROMA
-      if (pcCU->getSlice()->getSPS()->getChromaFormatIdc() != 0 )      
-      {
-        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) )
-        {
-          m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth, uiDepth );
-        }
-        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) )
-        {
-          m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth, uiDepth );
-        }
-      }
-      else
-      {
-        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) )
-        {
-          pcCU->setCbfSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiTrDepth - 1 );
-        }
-        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) )
-        {
-          pcCU->setCbfSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiTrDepth - 1 );
-        }
-      }
-#else
-      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) )
-      {
-        m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth, uiDepth );
-      }
-      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) )
-      {
-        m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth, uiDepth );
-      }
-#endif
-    }
-    else
-    {
-      pcCU->setCbfSubParts( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
-      pcCU->setCbfSubParts( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
-    }
-  }
-  
+      pcCU->setCbfSubParts( 0, compID, rTu.GetAbsPartIdxTU(compID), trDepthTotalAdj);
+    }
+    if( bFirstCbfOfCU || rTu.ProcessingAllQuadrants(compID) )
+    {
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepth - 1 ) )
+      {
+        m_pcEntropyDecoderIf->parseQtCbf( rTu, compID, (uiSubdiv == 0) );
+      }
+    }
+  }
+
   if( uiSubdiv )
   {
-    UInt size;
-    width  >>= 1;
-    height >>= 1;
-    size = width*height;
-    uiTrIdx++;
-    ++uiDepth;
-    const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
-    const UInt uiStartAbsPartIdx = uiAbsPartIdx;
-    UInt uiYCbf = 0;
-    UInt uiUCbf = 0;
-    UInt uiVCbf = 0;
-    
-    for( Int i = 0; i < 4; i++ )
-    {
-      xDecodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP, quadtreeTULog2MinSizeInCU );
-      uiYCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth+1 );
-      uiUCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth+1 );
-      uiVCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth+1 );
-      uiAbsPartIdx += uiQPartNum;
-      offsetLuma += size;  offsetChroma += (size>>2);
-    }
-    
-    for( UInt ui = 0; ui < 4 * uiQPartNum; ++ui )
-    {
-      pcCU->getCbf( TEXT_LUMA     )[uiStartAbsPartIdx + ui] |= uiYCbf << uiTrDepth;
-      pcCU->getCbf( TEXT_CHROMA_U )[uiStartAbsPartIdx + ui] |= uiUCbf << uiTrDepth;
-      pcCU->getCbf( TEXT_CHROMA_V )[uiStartAbsPartIdx + ui] |= uiVCbf << uiTrDepth;
+    const UInt uiQPartNum = pcCU->getPic()->getNumPartitionsInCtu() >> ((uiDepth+1) << 1);
+    UInt uiYUVCbf[MAX_NUM_COMPONENT] = {0,0,0};
+
+    TComTURecurse tuRecurseChild(rTu, true);
+
+    do
+    {
+      xDecodeTransform( bCodeDQP, isChromaQpAdjCoded, tuRecurseChild, quadtreeTULog2MinSizeInCU );
+      UInt childTUAbsPartIdx=tuRecurseChild.GetAbsPartIdxTU();
+      for(UInt ch=0; ch<numValidComponent; ch++)
+      {
+        uiYUVCbf[ch] |= pcCU->getCbf(childTUAbsPartIdx , ComponentID(ch),  uiTrDepth+1 );
+      }
+    } while (tuRecurseChild.nextSection(rTu) );
+
+    for(UInt ch=0; ch<numValidComponent; ch++)
+    {
+      UChar *pBase = pcCU->getCbf( ComponentID(ch) ) + uiAbsPartIdx;
+      const UChar flag = uiYUVCbf[ch] << uiTrDepth;
+
+      for( UInt ui = 0; ui < 4 * uiQPartNum; ++ui )
+      {
+        pBase[ui] |= flag;
+      }
     }
   }
@@ -800,5 +815,5 @@
     assert( uiDepth >= pcCU->getDepth( uiAbsPartIdx ) );
     pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiDepth );
-    
+
 #if !H_MV_ENC_DEC_TRAC
     {
@@ -813,74 +828,110 @@
     }
 #endif
-    
-    pcCU->setCbfSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
-    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
-    {
-      pcCU->setCbfSubParts( 1 << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+
+    pcCU->setCbfSubParts ( 0, COMPONENT_Y, uiAbsPartIdx, uiDepth );
+
+    if( (!pcCU->isIntra(uiAbsPartIdx)) && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && ((!bChroma) || (!pcCU->getCbf( uiAbsPartIdx, COMPONENT_Cb, 0 ) && !pcCU->getCbf( uiAbsPartIdx, COMPONENT_Cr, 0 )) ))
+    {
+      pcCU->setCbfSubParts( 1 << uiTrDepth, COMPONENT_Y, uiAbsPartIdx, uiDepth );
     }
     else
     {
-      m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrDepth, uiDepth );
+      m_pcEntropyDecoderIf->parseQtCbf( rTu, COMPONENT_Y, true );
     }
 
 
     // transform_unit begin
-    UInt cbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA    , uiTrIdx );
-    UInt cbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
-    UInt cbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
-    if( uiLog2TrafoSize == 2 )
-    {
-      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
-      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
-      {
-        cbfU = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
-        cbfV = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
-      }
-    }
-    if ( cbfY || cbfU || cbfV )
-    {
-      // dQP: only for LCU
+    UInt cbf[MAX_NUM_COMPONENT]={0,0,0};
+    Bool validCbf       = false;
+    Bool validChromaCbf = false;
+    const UInt uiTrIdx = rTu.GetTransformDepthRel();
+
+    for(UInt ch=0; ch<pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+
+      cbf[compID] = pcCU->getCbf( uiAbsPartIdx, compID, uiTrIdx );
+
+      if (cbf[compID] != 0)
+      {
+        validCbf = true;
+        if (isChroma(compID))
+        {
+          validChromaCbf = true;
+        }
+      }
+    }
+
+    if ( validCbf )
+    {
+
+      // dQP: only for CTU
       if ( pcCU->getSlice()->getPPS()->getUseDQP() )
       {
         if ( bCodeDQP )
         {
-          decodeQP( pcCU, m_bakAbsPartIdxCU);
+          const UInt uiAbsPartIdxCU=rTu.GetAbsPartIdxCU();
+          decodeQP( pcCU, uiAbsPartIdxCU);
           bCodeDQP = false;
         }
       }
-    }
-    if( cbfY )
-    {
-      Int trWidth = width;
-      Int trHeight = height;
-      m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffY()+offsetLuma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
-    }
-    if( uiLog2TrafoSize > 2 )
-    {
-      Int trWidth = width >> 1;
-      Int trHeight = height >> 1;
-      if( cbfU )
-      {
-        m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCb()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
-      }
-      if( cbfV )
-      {
-        m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCr()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
-      }
-    }
-    else
-    {
-      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
-      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
-      {
-        Int trWidth = width;
-        Int trHeight = height;
-        if( cbfU )
-        {
-          m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCb()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
-        }
-        if( cbfV )
-        {
-          m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCr()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+
+      if ( pcCU->getSlice()->getUseChromaQpAdj() )
+      {
+        if ( validChromaCbf && isChromaQpAdjCoded && !pcCU->getCUTransquantBypass(rTu.GetAbsPartIdxCU()) )
+        {
+          decodeChromaQpAdjustment( pcCU, rTu.GetAbsPartIdxCU() );
+          isChromaQpAdjCoded = false;
+        }
+      }
+
+      const UInt numValidComp=pcCU->getPic()->getNumberValidComponents();
+
+      for(UInt ch=COMPONENT_Y; ch<numValidComp; ch++)
+      {
+        const ComponentID compID=ComponentID(ch);
+
+        if( rTu.ProcessComponentSection(compID) )
+        {
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+          if (bDebugRQT)
+          {
+            printf("Call NxN for chan %d width=%d height=%d cbf=%d\n", compID, rTu.getRect(compID).width, rTu.getRect(compID).height, 1);
+          }
+#endif
+
+          if (rTu.getRect(compID).width != rTu.getRect(compID).height)
+          {
+            //code two sub-TUs
+            TComTURecurse subTUIterator(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+            do
+            {
+              const UInt subTUCBF = pcCU->getCbf(subTUIterator.GetAbsPartIdxTU(), compID, (uiTrIdx + 1));
+
+              if (subTUCBF != 0)
+              {
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+                if (bDebugRQT)
+                {
+                  printf("Call NxN for chan %d width=%d height=%d cbf=%d\n", compID, subTUIterator.getRect(compID).width, subTUIterator.getRect(compID).height, 1);
+                }
+#endif
+                m_pcEntropyDecoderIf->parseCoeffNxN( subTUIterator, compID );
+              }
+            } while (subTUIterator.nextSection(rTu));
+          }
+          else
+          {
+            if(isChroma(compID) && (cbf[COMPONENT_Y] != 0))
+            {
+              m_pcEntropyDecoderIf->parseCrossComponentPrediction( rTu, compID );
+            }
+
+            if(cbf[compID] != 0)
+            {
+              m_pcEntropyDecoderIf->parseCoeffNxN( rTu, compID );
+            }
+          }
         }
       }
@@ -898,18 +949,16 @@
 }
 
-
-/** decode coefficients
- * \param pcCU
- * \param uiAbsPartIdx 
- * \param uiDepth
- * \param uiWidth
- * \param uiHeight 
- * \returns Void
- */
-Void TDecEntropy::decodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP )
-{
-  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
-  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
-  UInt uiChromaOffset = uiLumaOffset>>2;
+Void TDecEntropy::decodeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( pcCU->getSlice()->getUseChromaQpAdj() )
+  {
+    m_pcEntropyDecoderIf->parseChromaQpAdjustment( pcCU, uiAbsPartIdx, pcCU->getDepth( uiAbsPartIdx ) );
+  }
+}
+
+
+//! decode coefficients
+Void TDecEntropy::decodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool& bCodeDQP, Bool& isChromaQpAdjCoded )
+{
 #if H_3D_DIM_SDC
   if( pcCU->getSDCFlag( uiAbsPartIdx ) && pcCU->isIntra( uiAbsPartIdx) )
@@ -918,16 +967,7 @@
     assert( pcCU->getTransformIdx(uiAbsPartIdx) == 0 );
     assert( pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA) == 1 );
-#if H_3D_DISABLE_CHROMA
-    if (pcCU->getSlice()->getSPS()->getChromaFormatIdc() != 0 )
-    {
-      assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
-      assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
-    }
-#else
     assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
     assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
-#endif
-  }
-
+}
 #if H_3D_INTER_SDC
   if( pcCU->getSDCFlag( uiAbsPartIdx ) && !pcCU->isIntra( uiAbsPartIdx) )
@@ -973,14 +1013,24 @@
     if ( !uiQtRootCbf )
     {
-      pcCU->setCbfSubParts( 0, 0, 0, uiAbsPartIdx, uiDepth );
+      static const UInt cbfZero[MAX_NUM_COMPONENT]={0,0,0};
+      pcCU->setCbfSubParts( cbfZero, uiAbsPartIdx, uiDepth );
       pcCU->setTrIdxSubParts( 0 , uiAbsPartIdx, uiDepth );
       return;
     }
-    
-  }
-
-  Int getQuadtreeTULog2MinSizeInCU = pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx);
-
-  xDecodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, bCodeDQP, getQuadtreeTULog2MinSizeInCU );
+
+  }
+
+  TComTURecurse tuRecurse(pcCU, uiAbsPartIdx, uiDepth);
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugRQT)
+  {
+    printf("..codeCoeff: uiAbsPartIdx=%d, PU format=%d, 2Nx2N=%d, NxN=%d\n", uiAbsPartIdx, pcCU->getPartitionSize(uiAbsPartIdx), SIZE_2Nx2N, SIZE_NxN);
+  }
+#endif
+
+  Int quadtreeTULog2MinSizeInCU = pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx);
+  
+  xDecodeTransform( bCodeDQP, isChromaQpAdjCoded, tuRecurse, quadtreeTULog2MinSizeInCU );
 }
 
@@ -1020,3 +1070,5 @@
 #endif
 
+
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecEntropy.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecEntropy.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,14 +39,15 @@
 #define __TDECENTROPY__
 
-#include "../TLibCommon/CommonDef.h"
-#include "../TLibCommon/TComBitStream.h"
-#include "../TLibCommon/TComSlice.h"
-#include "../TLibCommon/TComPic.h"
-#include "../TLibCommon/TComPrediction.h"
-#include "../TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComRectangle.h"
 
 class TDecSbac;
 class TDecCavlc;
 class ParameterSetManagerDecoder;
+class TComPrediction;
 
 //! \ingroup TLibDecoder
@@ -65,22 +66,14 @@
   virtual Void  setBitstream          ( TComInputBitstream* p )  = 0;
 
-  virtual Void  parseVPS                  ( TComVPS* pcVPS )                       = 0;
-  virtual Void  parseSPS                  ( TComSPS* pcSPS )                                      = 0;
-#if H_3D
-  virtual Void  parsePPS                  ( TComPPS* pcPPS, TComVPS* pcVPS )                      = 0;
-#else
-  virtual Void  parsePPS                  ( TComPPS* pcPPS )                                      = 0;
-#endif
-
-#if H_MV
-  virtual Void parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, Int targetOlsIdx )       = 0;
-#else
-  virtual Void parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)       = 0;
-#endif
-
-  virtual Void  parseTerminatingBit       ( UInt& ruilsLast )                                     = 0;
-  
+  virtual Void  parseVPS                  ( TComVPS* pcVPS )     = 0;
+  virtual Void  parseSPS                  ( TComSPS* pcSPS )     = 0;
+  virtual Void  parsePPS                  ( TComPPS* pcPPS )     = 0;
+  virtual Void parseSliceHeader          ( TComSlice* pcSlice, ParameterSetManager *parameterSetManager, const Int prevTid0POC)       = 0;
+
+  virtual Void parseTerminatingBit       ( UInt& ruilsLast )                                     = 0;
+  virtual Void parseRemainingBytes( Bool noTrailingBytesExpected ) = 0;
+
   virtual Void parseMVPIdx        ( Int& riMVPIdx ) = 0;
-  
+
 public:
   virtual Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
@@ -107,25 +100,29 @@
   virtual Void parsePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
   virtual Void parsePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-  
+
   virtual Void parseIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-  
   virtual Void parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-  
+
   virtual Void parseInterDir      ( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx ) = 0;
   virtual Void parseRefFrmIdx     ( TComDataCU* pcCU, Int& riRefFrmIdx, RefPicList eRefList ) = 0;
   virtual Void parseMvd           ( TComDataCU* pcCU, UInt uiAbsPartAddr, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList ) = 0;
-  
+
+  virtual Void parseCrossComponentPrediction ( class TComTU &rTu, ComponentID compID ) = 0;
+
   virtual Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize ) = 0;
-  virtual Void parseQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth ) = 0;
+  virtual Void parseQtCbf         ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel ) = 0;
   virtual Void parseQtRootCbf     ( UInt uiAbsPartIdx, UInt& uiQtRootCbf ) = 0;
-  
+
   virtual Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-  
+  virtual Void parseChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+
   virtual Void parseIPCMInfo     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth) = 0;
 
-  virtual Void parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
-  virtual Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType) = 0;
-  virtual Void updateContextTables( SliceType eSliceType, Int iQp ) = 0;
-  
+  virtual Void parseCoeffNxN( class TComTU &rTu, ComponentID compID  ) = 0;
+
+  virtual Void parseTransformSkipFlags ( class TComTU &rTu, ComponentID component ) = 0;
+
+  virtual Void parseExplicitRdpcmMode ( TComTU &rTu, ComponentID compID ) = 0;
+
   virtual ~TDecEntropyIf() {}
 };
@@ -137,8 +134,8 @@
   TDecEntropyIf*  m_pcEntropyDecoderIf;
   TComPrediction* m_pcPrediction;
-  UInt    m_uiBakAbsPartIdx;
-  UInt    m_uiBakChromaOffset;
-  UInt    m_bakAbsPartIdxCU;
-  
+  //UInt    m_uiBakAbsPartIdx;
+  //UInt    m_uiBakChromaOffset;
+  //UInt    m_bakAbsPartIdxCU;
+
 public:
   Void init (TComPrediction* p) {m_pcPrediction = p;}
@@ -149,5 +146,5 @@
   Void decodeMVPIdxPU     ( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
 #if H_3D
-  Void decodeMvsAMVP       ( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, 
+  Void decodeMvsAMVP      ( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, 
 RefPicList eRefList );
 #endif
@@ -155,20 +152,14 @@
   Void    setBitstream                ( TComInputBitstream* p ) { m_pcEntropyDecoderIf->setBitstream(p);                    }
   Void    resetEntropy                ( TComSlice* p)           { m_pcEntropyDecoderIf->resetEntropy(p);                    }
+
   Void    decodeVPS                   ( TComVPS* pcVPS ) { m_pcEntropyDecoderIf->parseVPS(pcVPS); }
-  Void    decodeSPS                   ( TComSPS* pcSPS     )    { m_pcEntropyDecoderIf->parseSPS(pcSPS);                    }
-#if H_3D
-  Void    decodePPS                   ( TComPPS* pcPPS, TComVPS* pcVPS )    { m_pcEntropyDecoderIf->parsePPS(pcPPS, pcVPS);                    }
-#else
-  Void    decodePPS                   ( TComPPS* pcPPS )    { m_pcEntropyDecoderIf->parsePPS(pcPPS);                    }
-#endif
-#if H_MV
-  Void    decodeSliceHeader           ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, Int targetOlsIdx)  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice, parameterSetManager, targetOlsIdx );         }
-#else
-  Void    decodeSliceHeader           ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice, parameterSetManager);         }
-#endif
+  Void    decodeSPS                   ( TComSPS* pcSPS ) { m_pcEntropyDecoderIf->parseSPS(pcSPS); }
+  Void    decodePPS                   ( TComPPS* pcPPS ) { m_pcEntropyDecoderIf->parsePPS(pcPPS); }
+  Void    decodeSliceHeader           ( TComSlice* pcSlice, ParameterSetManager *parameterSetManager, const Int prevTid0POC)  { m_pcEntropyDecoderIf->parseSliceHeader(pcSlice, parameterSetManager, prevTid0POC);         }
   Void    decodeTerminatingBit        ( UInt& ruiIsLast )       { m_pcEntropyDecoderIf->parseTerminatingBit(ruiIsLast);     }
-  
+  Void    decodeRemainingBytes( Bool noTrailingBytesExpected ) { m_pcEntropyDecoderIf->parseRemainingBytes(noTrailingBytesExpected); }
+
   TDecEntropyIf* getEntropyDecoder() { return m_pcEntropyDecoderIf; }
-  
+
 public:
   Void decodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
@@ -182,5 +173,5 @@
   Void decodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void decodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
 #if H_3D_ARP
   Void decodeARPW              ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
@@ -198,19 +189,19 @@
 
   Void decodePredInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU );
-  
+
   Void decodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void decodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
   Void decodeQP                ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-  
-  Void updateContextTables    ( SliceType eSliceType, Int iQp ) { m_pcEntropyDecoderIf->updateContextTables( eSliceType, iQp ); }
-  
-  
+  Void decodeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
 private:
-  Void xDecodeTransform        ( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP, Int getQuadtreeTULog2MinSizeInCU );
-
-public:
-  Void decodeCoeff             ( TComDataCU* pcCU                 , UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
-  
+
+  Void xDecodeTransform        ( Bool& bCodeDQP, Bool& isChromaQpAdjCoded, TComTU &rTu, const Int quadtreeTULog2MinSizeInCU );
+
+public:
+
+  Void decodeCoeff             ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool& bCodeDQP, Bool& isChromaQpAdjCoded );
+
 };// END CLASS DEFINITION TDecEntropy
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,9 +46,7 @@
 #include <time.h>
 
-extern Bool g_md5_mismatch; ///< top level flag to signal when there is a decode problem
-
 //! \ingroup TLibDecoder
 //! \{
-static void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI);
+static Void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI, const BitDepths &bitDepths, UInt &numChecksumErrors);
 // ====================================================================================================================
 // Constructor / destructor / initialization / destroy
@@ -56,18 +54,17 @@
 
 TDecGop::TDecGop()
+ : m_numberOfChecksumErrorsDetected(0)
 {
   m_dDecTime = 0;
-  m_pcSbacDecoders = NULL;
-  m_pcBinCABACs = NULL;
 }
 
 TDecGop::~TDecGop()
 {
-  
+
 }
 
 Void TDecGop::create()
 {
-  
+
 }
 
@@ -77,9 +74,9 @@
 }
 
-Void TDecGop::init( TDecEntropy*            pcEntropyDecoder, 
-                   TDecSbac*               pcSbacDecoder, 
+Void TDecGop::init( TDecEntropy*            pcEntropyDecoder,
+                   TDecSbac*               pcSbacDecoder,
                    TDecBinCABAC*           pcBinCABAC,
-                   TDecCavlc*              pcCavlcDecoder, 
-                   TDecSlice*              pcSliceDecoder, 
+                   TDecCavlc*              pcCavlcDecoder,
+                   TDecSlice*              pcSliceDecoder,
                    TComLoopFilter*         pcLoopFilter,
                    TComSampleAdaptiveOffset* pcSAO
@@ -92,5 +89,6 @@
   m_pcSliceDecoder        = pcSliceDecoder;
   m_pcLoopFilter          = pcLoopFilter;
-  m_pcSAO  = pcSAO;  
+  m_pcSAO                 = pcSAO;
+  m_numberOfChecksumErrorsDetected = 0;
 }
 
@@ -103,7 +101,7 @@
 // ====================================================================================================================
 
-Void TDecGop::decompressSlice(TComInputBitstream* pcBitstream, TComPic*& rpcPic)
-{
-  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+Void TDecGop::decompressSlice(TComInputBitstream* pcBitstream, TComPic* pcPic)
+{
+  TComSlice*  pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
   // Table of extracted substreams.
   // These must be deallocated AND their internal fifos, too.
@@ -111,31 +109,17 @@
 
   //-- For time output for each slice
-  long iBeforeTime = clock();
+  clock_t iBeforeTime = clock();
   m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
   m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
 
-  UInt uiNumSubstreams = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() ? pcSlice->getNumEntryPointOffsets()+1 : pcSlice->getPPS()->getNumSubstreams();
+  const UInt uiNumSubstreams = pcSlice->getNumberOfSubstreamSizes()+1;
 
   // init each couple {EntropyDecoder, Substream}
-  UInt *puiSubstreamSizes = pcSlice->getSubstreamSizes();
   ppcSubstreams    = new TComInputBitstream*[uiNumSubstreams];
-  m_pcSbacDecoders = new TDecSbac[uiNumSubstreams];
-  m_pcBinCABACs    = new TDecBinCABAC[uiNumSubstreams];
   for ( UInt ui = 0 ; ui < uiNumSubstreams ; ui++ )
   {
-    m_pcSbacDecoders[ui].init(&m_pcBinCABACs[ui]);
-    ppcSubstreams[ui] = pcBitstream->extractSubstream(ui+1 < uiNumSubstreams ? puiSubstreamSizes[ui] : pcBitstream->getNumBitsLeft());
-  }
-
-  for ( UInt ui = 0 ; ui+1 < uiNumSubstreams; ui++ )
-  {
-    m_pcEntropyDecoder->setEntropyDecoder ( &m_pcSbacDecoders[uiNumSubstreams - 1 - ui] );
-    m_pcEntropyDecoder->setBitstream      (  ppcSubstreams   [uiNumSubstreams - 1 - ui] );
-    m_pcEntropyDecoder->resetEntropy      (pcSlice);
-  }
-
-  m_pcEntropyDecoder->setEntropyDecoder ( m_pcSbacDecoder  );
-  m_pcEntropyDecoder->setBitstream      ( ppcSubstreams[0] );
-  m_pcEntropyDecoder->resetEntropy      (pcSlice);
+    ppcSubstreams[ui] = pcBitstream->extractSubstream(ui+1 < uiNumSubstreams ? (pcSlice->getSubstreamSize(ui)<<3) : pcBitstream->getNumBitsLeft());
+  }
+
 #if H_3D_NBDV 
   if(pcSlice->getViewIndex() && !pcSlice->getIsDepth()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
@@ -155,52 +139,51 @@
   }
 #endif
-#if H_3D
+#if NH_3D
   pcSlice->setDepthToDisparityLUTs(); 
 #endif
-  m_pcSbacDecoders[0].load(m_pcSbacDecoder);
-  m_pcSliceDecoder->decompressSlice( ppcSubstreams, rpcPic, m_pcSbacDecoder, m_pcSbacDecoders);
-  m_pcEntropyDecoder->setBitstream(  ppcSubstreams[uiNumSubstreams-1] );
+
+  m_pcSliceDecoder->decompressSlice( ppcSubstreams, pcPic, m_pcSbacDecoder);
   // deallocate all created substreams, including internal buffers.
   for (UInt ui = 0; ui < uiNumSubstreams; ui++)
   {
-    ppcSubstreams[ui]->deleteFifo();
     delete ppcSubstreams[ui];
   }
   delete[] ppcSubstreams;
-  delete[] m_pcSbacDecoders; m_pcSbacDecoders = NULL;
-  delete[] m_pcBinCABACs; m_pcBinCABACs = NULL;
 
   m_dDecTime += (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
 }
 
-Void TDecGop::filterPicture(TComPic*& rpcPic)
-{
-  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+Void TDecGop::filterPicture(TComPic* pcPic)
+{
+  TComSlice*  pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
 
   //-- For time output for each slice
-  long iBeforeTime = clock();
+  clock_t iBeforeTime = clock();
 
   // deblocking filter
   Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
   m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
-  m_pcLoopFilter->loopFilterPic( rpcPic );
+  m_pcLoopFilter->loopFilterPic( pcPic );
+
   if( pcSlice->getSPS()->getUseSAO() )
   {
-    m_pcSAO->reconstructBlkSAOParams(rpcPic, rpcPic->getPicSym()->getSAOBlkParam());
-    m_pcSAO->SAOProcess(rpcPic);
-    m_pcSAO->PCMLFDisableProcess(rpcPic);
-  }
-#if H_3D
-  rpcPic->compressMotion(2); 
-#endif
-#if !H_3D
-  rpcPic->compressMotion(); 
+    m_pcSAO->reconstructBlkSAOParams(pcPic, pcPic->getPicSym()->getSAOBlkParam());
+    m_pcSAO->SAOProcess(pcPic);
+    m_pcSAO->PCMLFDisableProcess(pcPic);
+  }
+#if NH_3D
+  pcPic->compressMotion(2); 
+#else
+  pcPic->compressMotion();
 #endif
   Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
-  if (!pcSlice->isReferenced()) c += 32;
+  if (!pcSlice->isReferenced())
+  {
+    c += 32;
+  }
 
   //-- For time output for each slice
-#if H_MV
-  printf("\nLayer %2d   POC %4d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getLayerId(),
+#if NH_MV
+  printf("Layer %2d   POC %4d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getLayerId(),
                                                               pcSlice->getPOC(),
                                                               pcSlice->getTLayer(),
@@ -208,8 +191,8 @@
                                                               pcSlice->getSliceQp() );
 #else
-  printf("\nPOC %4d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getPOC(),
-                                                    pcSlice->getTLayer(),
-                                                    c,
-                                                    pcSlice->getSliceQp() );
+  printf("POC %4d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getPOC(),
+                                                  pcSlice->getTLayer(),
+                                                  c,
+                                                  pcSlice->getSliceQp() );
 #endif
 
@@ -223,5 +206,5 @@
     for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
     {
-#if H_MV
+#if NH_MV
       if( pcSlice->getLayerId() != pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) )
       {
@@ -232,5 +215,5 @@
 #endif
       printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
-#if H_MV
+#if NH_MV
       }
 #endif
@@ -240,5 +223,5 @@
   if (m_decodedPictureHashSEIEnabled)
   {
-    SEIMessages pictureHashes = getSeisByType(rpcPic->getSEIs(), SEI::DECODED_PICTURE_HASH );
+    SEIMessages pictureHashes = getSeisByType(pcPic->getSEIs(), SEI::DECODED_PICTURE_HASH );
     const SEIDecodedPictureHash *hash = ( pictureHashes.size() > 0 ) ? (SEIDecodedPictureHash*) *(pictureHashes.begin()) : NULL;
     if (pictureHashes.size() > 1)
@@ -246,13 +229,11 @@
       printf ("Warning: Got multiple decoded picture hash SEI messages. Using first.");
     }
-    calcAndPrintHashStatus(*rpcPic->getPicYuvRec(), hash);
-  }
-#if !H_MV
-#if SETTING_PIC_OUTPUT_MARK
-  rpcPic->setOutputMark(rpcPic->getSlice(0)->getPicOutputFlag() ? true : false);
-#else
-  rpcPic->setOutputMark(true);
-#endif
-  rpcPic->setReconMark(true);
+    calcAndPrintHashStatus(*(pcPic->getPicYuvRec()), hash, pcSlice->getSPS()->getBitDepths(), m_numberOfChecksumErrorsDetected);
+  }
+
+  printf("\n");
+#if !NH_MV
+  pcPic->setOutputMark(pcPic->getSlice(0)->getPicOutputFlag() ? true : false);
+  pcPic->setReconMark(true);
 #endif
 }
@@ -269,8 +250,8 @@
  *            unk         - no SEI message was available for comparison
  */
-static void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI)
+static Void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI, const BitDepths &bitDepths, UInt &numChecksumErrors)
 {
   /* calculate MD5sum for entire reconstructed picture */
-  UChar recon_digest[3][16];
+  TComPictureHash recon_digest;
   Int numChar=0;
   const Char* hashType = "\0";
@@ -280,29 +261,27 @@
     switch (pictureHashSEI->method)
     {
-    case SEIDecodedPictureHash::MD5:
-      {
-        hashType = "MD5";
-        calcMD5(pic, recon_digest);
-        numChar = 16;
-        break;
-      }
-    case SEIDecodedPictureHash::CRC:
-      {
-        hashType = "CRC";
-        calcCRC(pic, recon_digest);
-        numChar = 2;
-        break;
-      }
-    case SEIDecodedPictureHash::CHECKSUM:
-      {
-        hashType = "Checksum";
-        calcChecksum(pic, recon_digest);
-        numChar = 4;
-        break;
-      }
-    default:
-      {
-        assert (!"unknown hash type");
-      }
+      case SEIDecodedPictureHash::MD5:
+        {
+          hashType = "MD5";
+          numChar = calcMD5(pic, recon_digest, bitDepths);
+          break;
+        }
+      case SEIDecodedPictureHash::CRC:
+        {
+          hashType = "CRC";
+          numChar = calcCRC(pic, recon_digest, bitDepths);
+          break;
+        }
+      case SEIDecodedPictureHash::CHECKSUM:
+        {
+          hashType = "Checksum";
+          numChar = calcChecksum(pic, recon_digest, bitDepths);
+          break;
+        }
+      default:
+        {
+          assert (!"unknown hash type");
+          break;
+        }
     }
   }
@@ -315,23 +294,17 @@
   {
     ok = "(OK)";
-    for(Int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
+    if (recon_digest != pictureHashSEI->m_pictureHash)
     {
-      for (UInt i = 0; i < numChar; i++)
-      {
-        if (recon_digest[yuvIdx][i] != pictureHashSEI->digest[yuvIdx][i])
-        {
-          ok = "(***ERROR***)";
-          mismatch = true;
-        }
-      }
+      ok = "(***ERROR***)";
+      mismatch = true;
     }
   }
 
-  printf("[%s:%s,%s] ", hashType, digestToString(recon_digest, numChar), ok);
+  printf("[%s:%s,%s] ", hashType, hashToString(recon_digest, numChar).c_str(), ok);
 
   if (mismatch)
   {
-    g_md5_mismatch = true;
-    printf("[rx%s:%s] ", hashType, digestToString(pictureHashSEI->digest, numChar));
+    numChecksumErrors++;
+    printf("[rx%s:%s] ", hashType, hashToString(pictureHashSEI->m_pictureHash, numChar).c_str());
   }
 }
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecGop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecGop.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -56,5 +56,4 @@
 #include "TDecBinCoderCABAC.h"
 
-
 //! \ingroup TLibDecoder
 //! \{
@@ -63,5 +62,5 @@
 // Class definition
 // ====================================================================================================================
-#if H_3D
+#if NH_MV
 class TDecTop; 
 #endif
@@ -73,31 +72,30 @@
 private:
   TComList<TComPic*>    m_cListPic;         //  Dynamic buffer
-  
+
   //  Access channel
   TDecEntropy*          m_pcEntropyDecoder;
   TDecSbac*             m_pcSbacDecoder;
   TDecBinCABAC*         m_pcBinCABAC;
-  TDecSbac*             m_pcSbacDecoders; // independant CABAC decoders
-  TDecBinCABAC*         m_pcBinCABACs;
   TDecCavlc*            m_pcCavlcDecoder;
   TDecSlice*            m_pcSliceDecoder;
   TComLoopFilter*       m_pcLoopFilter;
-#if H_3D
+#if NH_MV
   TDecTop*              m_decTop; 
 #endif
-  
+
   TComSampleAdaptiveOffset*     m_pcSAO;
   Double                m_dDecTime;
   Int                   m_decodedPictureHashSEIEnabled;  ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+  UInt                  m_numberOfChecksumErrorsDetected;
 
 public:
   TDecGop();
   virtual ~TDecGop();
-  
-  Void  init    ( TDecEntropy*            pcEntropyDecoder, 
-                 TDecSbac*               pcSbacDecoder, 
+
+  Void  init    ( TDecEntropy*            pcEntropyDecoder,
+                 TDecSbac*               pcSbacDecoder,
                  TDecBinCABAC*           pcBinCABAC,
-                 TDecCavlc*              pcCavlcDecoder, 
-                 TDecSlice*              pcSliceDecoder, 
+                 TDecCavlc*              pcCavlcDecoder,
+                 TDecSlice*              pcSliceDecoder,
                  TComLoopFilter*         pcLoopFilter,
                  TComSampleAdaptiveOffset* pcSAO
@@ -105,8 +103,9 @@
   Void  create  ();
   Void  destroy ();
-  Void  decompressSlice(TComInputBitstream* pcBitstream, TComPic*& rpcPic );
-  Void  filterPicture  (TComPic*& rpcPic );
+  Void  decompressSlice(TComInputBitstream* pcBitstream, TComPic* pcPic );
+  Void  filterPicture  (TComPic* pcPic );
 
-  void setDecodedPictureHashSEIEnabled(Int enabled) { m_decodedPictureHashSEIEnabled = enabled; }
+  Void setDecodedPictureHashSEIEnabled(Int enabled) { m_decodedPictureHashSEIEnabled = enabled; }
+  UInt getNumberOfChecksumErrorsDetected() const { return m_numberOfChecksumErrorsDetected; }
 
 };
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,7 +37,22 @@
 
 #include "TDecSbac.h"
+#include "TLibCommon/TComTU.h"
+#include "TLibCommon/TComTrQuant.h"
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+//
+#define RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(a) , a
+#else
+#define RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(a)
+#endif
 
 //! \ingroup TLibDecoder
 //! \{
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+#include "../TLibCommon/Debug.h"
+#endif
+
 
 //////////////////////////////////////////////////////////////////////
@@ -45,17 +60,17 @@
 //////////////////////////////////////////////////////////////////////
 
-TDecSbac::TDecSbac() 
+TDecSbac::TDecSbac()
 // new structure here
-: m_pcBitstream               ( 0 )
-, m_pcTDecBinIf               ( NULL )
-, m_numContextModels          ( 0 )
-, m_cCUSplitFlagSCModel       ( 1,             1,               NUM_SPLIT_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels )
-, m_cCUSkipFlagSCModel        ( 1,             1,               NUM_SKIP_FLAG_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+: m_pcBitstream                              ( 0 )
+, m_pcTDecBinIf                              ( NULL )
+, m_numContextModels                         ( 0 )
+, m_cCUSplitFlagSCModel                      ( 1,             1,                      NUM_SPLIT_FLAG_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSkipFlagSCModel                       ( 1,             1,                      NUM_SKIP_FLAG_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
 #if H_3D
 , m_cCUDISFlagSCModel         ( 1,             1,               NUM_DIS_FLAG_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cCUDISTypeSCModel         ( 1,             1,               NUM_DIS_TYPE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
-, m_cCUMergeFlagExtSCModel    ( 1,             1,               NUM_MERGE_FLAG_EXT_CTX        , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUMergeIdxExtSCModel     ( 1,             1,               NUM_MERGE_IDX_EXT_CTX         , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMergeFlagExtSCModel                   ( 1,             1,                      NUM_MERGE_FLAG_EXT_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMergeIdxExtSCModel                    ( 1,             1,                      NUM_MERGE_IDX_EXT_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
 #if H_3D_ARP
 , m_cCUPUARPWSCModel          ( 1,             1,               NUM_ARPW_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
@@ -64,26 +79,31 @@
 , m_cCUICFlagSCModel          ( 1,             1,               NUM_IC_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
-, m_cCUPartSizeSCModel        ( 1,             1,               NUM_PART_SIZE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUPredModeSCModel        ( 1,             1,               NUM_PRED_MODE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUIntraPredSCModel       ( 1,             1,               NUM_ADI_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUChromaPredSCModel      ( 1,             1,               NUM_CHROMA_PRED_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUDeltaQpSCModel         ( 1,             1,               NUM_DELTA_QP_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUInterDirSCModel        ( 1,             1,               NUM_INTER_DIR_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCURefPicSCModel          ( 1,             1,               NUM_REF_NO_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUMvdSCModel             ( 1,             1,               NUM_MV_RES_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUQtCbfSCModel           ( 1,             2,               NUM_QT_CBF_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUTransSubdivFlagSCModel ( 1,             1,               NUM_TRANS_SUBDIV_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUQtRootCbfSCModel       ( 1,             1,               NUM_QT_ROOT_CBF_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUSigCoeffGroupSCModel   ( 1,             2,               NUM_SIG_CG_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUSigSCModel             ( 1,             1,               NUM_SIG_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCuCtxLastX               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCuCtxLastY               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUOneSCModel             ( 1,             1,               NUM_ONE_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cSaoMergeSCModel      ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cTransformSkipSCModel     ( 1,             2,               NUM_TRANSFORMSKIP_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
-, m_CUTransquantBypassFlagSCModel( 1,          1,               NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX, m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPartSizeSCModel                       ( 1,             1,                      NUM_PART_SIZE_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPredModeSCModel                       ( 1,             1,                      NUM_PRED_MODE_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUIntraPredSCModel                      ( 1,             1,                      NUM_INTRA_PREDICT_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUChromaPredSCModel                     ( 1,             1,                      NUM_CHROMA_PRED_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUDeltaQpSCModel                        ( 1,             1,                      NUM_DELTA_QP_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUInterDirSCModel                       ( 1,             1,                      NUM_INTER_DIR_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCURefPicSCModel                         ( 1,             1,                      NUM_REF_NO_CTX                       , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMvdSCModel                            ( 1,             1,                      NUM_MV_RES_CTX                       , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtCbfSCModel                          ( 1,             NUM_QT_CBF_CTX_SETS,    NUM_QT_CBF_CTX_PER_SET               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUTransSubdivFlagSCModel                ( 1,             1,                      NUM_TRANS_SUBDIV_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtRootCbfSCModel                      ( 1,             1,                      NUM_QT_ROOT_CBF_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigCoeffGroupSCModel                  ( 1,             2,                      NUM_SIG_CG_FLAG_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigSCModel                            ( 1,             1,                      NUM_SIG_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastX                              ( 1,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastY                              ( 1,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUOneSCModel                            ( 1,             1,                      NUM_ONE_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAbsSCModel                            ( 1,             1,                      NUM_ABS_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cMVPIdxSCModel                           ( 1,             1,                      NUM_MVP_IDX_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeSCModel                         ( 1,             1,                      NUM_SAO_MERGE_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel                       ( 1,             1,                      NUM_SAO_TYPE_IDX_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cTransformSkipSCModel                    ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_TRANSFORMSKIP_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_CUTransquantBypassFlagSCModel            ( 1,             1,                      NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_explicitRdpcmFlagSCModel                 ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_FLAG_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_explicitRdpcmDirSCModel                  ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_DIR_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCrossComponentPredictionSCModel         ( 1,             1,                      NUM_CROSS_COMPONENT_PREDICTION_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_ChromaQpAdjFlagSCModel                   ( 1,             1,                      NUM_CHROMA_QP_ADJ_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_ChromaQpAdjIdcSCModel                    ( 1,             1,                      NUM_CHROMA_QP_ADJ_IDC_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
 #if H_3D_DIM
 , m_cDepthIntraModeSCModel    ( 1,             1,               NUM_DEPTH_INTRA_MODE_CTX      , m_contextModels + m_numContextModels, m_numContextModels)
@@ -102,4 +122,5 @@
 , m_cDBBPFlagSCModel             ( 1,             1,                 DBBP_NUM_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
+
 {
   assert( m_numContextModels <= MAX_NUM_CTX_MOD );
@@ -124,22 +145,23 @@
     {
     case P_SLICE:           // change initialization table to B_SLICE initialization
-      sliceType = B_SLICE; 
+      sliceType = B_SLICE;
       break;
     case B_SLICE:           // change initialization table to P_SLICE initialization
-      sliceType = P_SLICE; 
+      sliceType = P_SLICE;
       break;
     default     :           // should not occur
       assert(0);
-    }
-  }
-
-  m_cCUSplitFlagSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_SPLIT_FLAG );
-  m_cCUSkipFlagSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SKIP_FLAG );
+      break;
+    }
+  }
+
+  m_cCUSplitFlagSCModel.initBuffer                ( sliceType, qp, (UChar*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_SKIP_FLAG );
 #if H_3D
   m_cCUDISFlagSCModel.initBuffer         ( sliceType, qp, (UChar*)INIT_DIS_FLAG );
   m_cCUDISTypeSCModel.initBuffer         ( sliceType, qp, (UChar*)INIT_DIS_TYPE );
 #endif
-  m_cCUMergeFlagExtSCModel.initBuffer    ( sliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT );
-  m_cCUMergeIdxExtSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_MERGE_IDX_EXT );
+  m_cCUMergeFlagExtSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT );
+  m_cCUMergeIdxExtSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_MERGE_IDX_EXT );
 #if H_3D_ARP
   m_cCUPUARPWSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_ARPW );
@@ -148,27 +170,31 @@
   m_cCUICFlagSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_IC_FLAG );
 #endif
-  m_cCUPartSizeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PART_SIZE );
-  m_cCUPredModeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PRED_MODE );
-  m_cCUIntraPredSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
-  m_cCUChromaPredSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
-  m_cCUInterDirSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_INTER_DIR );
-  m_cCUMvdSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_MVD );
-  m_cCURefPicSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_REF_PIC );
-  m_cCUDeltaQpSCModel.initBuffer         ( sliceType, qp, (UChar*)INIT_DQP );
-  m_cCUQtCbfSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_QT_CBF );
-  m_cCUQtRootCbfSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
-  m_cCUSigCoeffGroupSCModel.initBuffer   ( sliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
-  m_cCUSigSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_SIG_FLAG );
-  m_cCuCtxLastX.initBuffer               ( sliceType, qp, (UChar*)INIT_LAST );
-  m_cCuCtxLastY.initBuffer               ( sliceType, qp, (UChar*)INIT_LAST );
-  m_cCUOneSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_ONE_FLAG );
-  m_cCUAbsSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_ABS_FLAG );
-  m_cMVPIdxSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_MVP_IDX );
-  m_cSaoMergeSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
-  m_cSaoTypeIdxSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
-
-  m_cCUTransSubdivFlagSCModel.initBuffer ( sliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
-  m_cTransformSkipSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
-  m_CUTransquantBypassFlagSCModel.initBuffer( sliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  m_cCUPartSizeSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer                ( sliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer               ( sliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer                      ( sliceType, qp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer                   ( sliceType, qp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer                  ( sliceType, qp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer                    ( sliceType, qp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer                ( sliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer                      ( sliceType, qp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer                        ( sliceType, qp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer                        ( sliceType, qp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer                      ( sliceType, qp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer                      ( sliceType, qp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer                     ( sliceType, qp, (UChar*)INIT_MVP_IDX );
+  m_cSaoMergeSCModel.initBuffer                   ( sliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cTransformSkipSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  m_explicitRdpcmFlagSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_FLAG);
+  m_explicitRdpcmDirSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_DIR);
+  m_cCrossComponentPredictionSCModel.initBuffer   ( sliceType, qp, (UChar*)INIT_CROSS_COMPONENT_PREDICTION );
+  m_ChromaQpAdjFlagSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
+  m_ChromaQpAdjIdcSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
 #if H_3D_DIM
   m_cDepthIntraModeSCModel.initBuffer    ( sliceType, qp, (UChar*)INIT_DEPTH_INTRA_MODE );
@@ -187,30 +213,32 @@
   m_cDBBPFlagSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_DBBP_FLAG );
 #endif
-  m_uiLastDQpNonZero  = 0;
-  
-  // new structure
-  m_uiLastQp          = qp;
-  
+
+  for (UInt statisticIndex = 0; statisticIndex < RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS ; statisticIndex++)
+  {
+    m_golombRiceAdaptationStatistics[statisticIndex] = 0;
+  }
+
   m_pcTDecBinIf->start();
 }
 
-/** The function does the following: Read out terminate bit. Flush CABAC. Byte-align for next tile.
- *  Intialize CABAC states. Start CABAC.
- */
-Void TDecSbac::updateContextTables( SliceType eSliceType, Int iQp )
-{
-  UInt uiBit;
-  m_pcTDecBinIf->decodeBinTrm(uiBit);
-  assert(uiBit); // end_of_sub_stream_one_bit must be equal to 1
-  m_pcTDecBinIf->finish();  
-  m_pcBitstream->readOutTrailingBits();
-  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
-  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+Void TDecSbac::parseTerminatingBit( UInt& ruiBit )
+{
+  m_pcTDecBinIf->decodeBinTrm( ruiBit );
+  if ( ruiBit == 1 )
+  {
+    m_pcTDecBinIf->finish();
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::IncrementStatisticEP(STATS__TRAILING_BITS, m_pcBitstream->readOutTrailingBits(),0);
+#else
+    m_pcBitstream->readOutTrailingBits();
+#endif
+  }
+}
+
 #if H_3D
   m_cCUDISFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DIS_FLAG );
   m_cCUDISTypeSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DIS_TYPE );
 #endif
-  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT );
-  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT );
 #if H_3D_ARP
   m_cCUPUARPWSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_ARPW );
@@ -219,27 +247,4 @@
   m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
 #endif
-  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
-  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
-  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
-  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
-  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
-  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
-  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
-  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
-  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
-  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
-  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
-  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
-  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
-  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
-  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
-  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
-  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
-  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
-  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
-  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
-  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
-  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
-
 #if H_3D_DIM
   m_cDepthIntraModeSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_DEPTH_INTRA_MODE );
@@ -258,18 +263,32 @@
   m_cDBBPFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_DBBP_FLAG );
 #endif
-  m_pcTDecBinIf->start();
-}
-
-Void TDecSbac::parseTerminatingBit( UInt& ruiBit )
-{
-  m_pcTDecBinIf->decodeBinTrm( ruiBit );
-  if ( ruiBit )
-  {
-    m_pcTDecBinIf->finish();
-  }
-}
-
-
+
+
+Void TDecSbac::parseRemainingBytes( Bool noTrailingBytesExpected )
+{
+  if (noTrailingBytesExpected)
+  {
+    const UInt numberOfRemainingSubstreamBytes=m_pcBitstream->getNumBitsLeft();
+    assert (numberOfRemainingSubstreamBytes == 0);
+  }
+  else
+  {
+    while (m_pcBitstream->getNumBitsLeft())
+    {
+      UInt trailingNullByte=m_pcBitstream->readByte();
+      if (trailingNullByte!=0)
+      {
+        printf("Trailing byte should be 0, but has value %02x\n", trailingNullByte);
+        assert(trailingNullByte==0);
+      }
+    }
+  }
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecSbac::xReadUnaryMaxSymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol, const class TComCodingStatisticsClassType &whichStat )
+#else
 Void TDecSbac::xReadUnaryMaxSymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
+#endif
 {
   if (uiMaxSymbol == 0)
@@ -278,70 +297,76 @@
     return;
   }
-  
-  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
-  
+
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+
   if( ruiSymbol == 0 || uiMaxSymbol == 1 )
   {
     return;
   }
-  
+
   UInt uiSymbol = 0;
   UInt uiCont;
-  
+
   do
   {
-    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] );
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
     uiSymbol++;
-  }
-  while( uiCont && ( uiSymbol < uiMaxSymbol - 1 ) );
-  
+  } while( uiCont && ( uiSymbol < uiMaxSymbol - 1 ) );
+
   if( uiCont && ( uiSymbol == uiMaxSymbol - 1 ) )
   {
     uiSymbol++;
   }
-  
+
   ruiSymbol = uiSymbol;
 }
 
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecSbac::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount, const class TComCodingStatisticsClassType &whichStat )
+#else
 Void TDecSbac::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
+#endif
 {
   UInt uiSymbol = 0;
   UInt uiBit = 1;
-  
+
   while( uiBit )
   {
-    m_pcTDecBinIf->decodeBinEP( uiBit );
+    m_pcTDecBinIf->decodeBinEP( uiBit RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
     uiSymbol += uiBit << uiCount++;
   }
-  
+
   if ( --uiCount )
   {
     UInt bins;
-    m_pcTDecBinIf->decodeBinsEP( bins, uiCount );
+    m_pcTDecBinIf->decodeBinsEP( bins, uiCount RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
     uiSymbol += bins;
   }
-  
+
   ruiSymbol = uiSymbol;
 }
 
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecSbac::xReadUnarySymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, const class TComCodingStatisticsClassType &whichStat )
+#else
 Void TDecSbac::xReadUnarySymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset )
-{
-  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
-  
+#endif
+{
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
+
   if( !ruiSymbol )
   {
     return;
   }
-  
+
   UInt uiSymbol = 0;
   UInt uiCont;
-  
+
   do
   {
-    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] );
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
     uiSymbol++;
-  }
-  while( uiCont );
-  
+  } while( uiCont );
+
   ruiSymbol = uiSymbol;
 }
@@ -349,30 +374,60 @@
 
 /** Parsing of coeff_abs_level_remaing
- * \param ruiSymbol reference to coeff_abs_level_remaing
- * \param ruiParam reference to parameter
- * \returns Void
+ * \param rSymbol                 reference to coeff_abs_level_remaing
+ * \param rParam                  reference to parameter
+ * \param useLimitedPrefixLength
+ * \param maxLog2TrDynamicRange
  */
-Void TDecSbac::xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam )
-{
-
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecSbac::xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange, const class TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecSbac::xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange )
+#endif
+{
   UInt prefix   = 0;
   UInt codeWord = 0;
-  do
-  {
-    prefix++;
-    m_pcTDecBinIf->decodeBinEP( codeWord );
-  }
-  while( codeWord);
+
+  if (useLimitedPrefixLength)
+  {
+    const UInt longestPossiblePrefix = (32 - (COEF_REMAIN_BIN_REDUCTION + maxLog2TrDynamicRange)) + COEF_REMAIN_BIN_REDUCTION;
+
+    do
+    {
+      prefix++;
+      m_pcTDecBinIf->decodeBinEP( codeWord RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+    } while((codeWord != 0) && (prefix < longestPossiblePrefix));
+  }
+  else
+  {
+    do
+    {
+      prefix++;
+      m_pcTDecBinIf->decodeBinEP( codeWord RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+    } while( codeWord);
+  }
+
   codeWord  = 1 - codeWord;
   prefix -= codeWord;
   codeWord=0;
+
   if (prefix < COEF_REMAIN_BIN_REDUCTION )
   {
-    m_pcTDecBinIf->decodeBinsEP(codeWord,rParam);
+    m_pcTDecBinIf->decodeBinsEP(codeWord,rParam RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
     rSymbol = (prefix<<rParam) + codeWord;
   }
+  else if (useLimitedPrefixLength)
+  {
+    const UInt maximumPrefixLength = (32 - (COEF_REMAIN_BIN_REDUCTION + maxLog2TrDynamicRange));
+
+    const UInt prefixLength = prefix - COEF_REMAIN_BIN_REDUCTION;
+    const UInt suffixLength = (prefixLength == maximumPrefixLength) ? (maxLog2TrDynamicRange - rParam) : prefixLength;
+
+    m_pcTDecBinIf->decodeBinsEP(codeWord, (suffixLength + rParam) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
+
+    rSymbol = codeWord + ((((1 << prefixLength) - 1) + COEF_REMAIN_BIN_REDUCTION) << rParam);
+  }
   else
   {
-    m_pcTDecBinIf->decodeBinsEP(codeWord,prefix-COEF_REMAIN_BIN_REDUCTION+rParam);
+    m_pcTDecBinIf->decodeBinsEP(codeWord,prefix-COEF_REMAIN_BIN_REDUCTION+rParam RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
     rSymbol = (((1<<(prefix-COEF_REMAIN_BIN_REDUCTION))+COEF_REMAIN_BIN_REDUCTION-1)<<rParam)+codeWord;
   }
@@ -434,11 +489,13 @@
 
 #endif
-/** Parse I_PCM information. 
+
+
+/** Parse I_PCM information.
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
  * \returns Void
  *
- * If I_PCM flag indicates that the CU is I_PCM, parse its PCM alignment bits and codes. 
+ * If I_PCM flag indicates that the CU is I_PCM, parse its PCM alignment bits and codes.
  */
 Void TDecSbac::parseIPCMInfo ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
@@ -451,76 +508,37 @@
   DTRACE_CU("pcm_flag", uiSymbol)
 #endif
-  if (uiSymbol)
+
+
+  if (uiSymbol == 1)
   {
     Bool bIpcmFlag = true;
+    const TComSPS &sps=*(pcCU->getSlice()->getSPS());
 
     pcCU->setPartSizeSubParts  ( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
-    pcCU->setSizeSubParts      ( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts      ( sps.getMaxCUWidth()>>uiDepth, sps.getMaxCUHeight()>>uiDepth, uiAbsPartIdx, uiDepth );
     pcCU->setTrIdxSubParts     ( 0, uiAbsPartIdx, uiDepth );
     pcCU->setIPCMFlagSubParts  ( bIpcmFlag, uiAbsPartIdx, uiDepth );
 
-    UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
-    UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
-    UInt uiChromaOffset = uiLumaOffset>>2;
-
-    Pel* piPCMSample;
-    UInt uiWidth;
-    UInt uiHeight;
-    UInt uiSampleBits;
-    UInt uiX, uiY;
-
-    piPCMSample = pcCU->getPCMSampleY() + uiLumaOffset;
-    uiWidth = pcCU->getWidth(uiAbsPartIdx);
-    uiHeight = pcCU->getHeight(uiAbsPartIdx);
-    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
-
-    for(uiY = 0; uiY < uiHeight; uiY++)
-    {
-      for(uiX = 0; uiX < uiWidth; uiX++)
-      {
-        UInt uiSample;
-        m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
-        piPCMSample[uiX] = uiSample;
-      }
-      piPCMSample += uiWidth;
-    }
-#if H_3D_DISABLE_CHROMA
-    if( pcCU->getSlice()->getSPS()->getChromaFormatIdc() != 0 )
-    {    
-#endif
-      piPCMSample = pcCU->getPCMSampleCb() + uiChromaOffset;
-      uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
-      uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
-      uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
-
-      for(uiY = 0; uiY < uiHeight; uiY++)
-      {
-        for(uiX = 0; uiX < uiWidth; uiX++)
-        {
-          UInt uiSample;
-          m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
-          piPCMSample[uiX] = uiSample;
-        }
-        piPCMSample += uiWidth;
-      }
-
-      piPCMSample = pcCU->getPCMSampleCr() + uiChromaOffset;
-      uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
-      uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
-      uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
-
-      for(uiY = 0; uiY < uiHeight; uiY++)
-      {
-        for(uiX = 0; uiX < uiWidth; uiX++)
-        {
-          UInt uiSample;
-          m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
-          piPCMSample[uiX] = uiSample;
-        }
-        piPCMSample += uiWidth;
-      }
-#if H_3D_DISABLE_CHROMA
-    }
-#endif
+    const UInt minCoeffSizeY = pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight();
+    const UInt offsetY       = minCoeffSizeY * uiAbsPartIdx;
+    for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      const UInt offset = offsetY >> (pcCU->getPic()->getComponentScaleX(compID) + pcCU->getPic()->getComponentScaleY(compID));
+      Pel * pPCMSample  = pcCU->getPCMSample(compID) + offset;
+      const UInt width  = pcCU->getWidth (uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleX(compID);
+      const UInt height = pcCU->getHeight(uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleY(compID);
+      const UInt sampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
+      for (UInt y=0; y<height; y++)
+      {
+        for (UInt x=0; x<width; x++)
+        {
+          UInt sample;
+          m_pcTDecBinIf->xReadPCMCode(sampleBits, sample);
+          pPCMSample[x] = sample;
+        }
+        pPCMSample += width;
+      }
+    }
     m_pcTDecBinIf->start();
   }
@@ -530,8 +548,9 @@
 {
   UInt uiSymbol;
-  m_pcTDecBinIf->decodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__TQ_BYPASS_FLAG) );
 #if H_MV_ENC_DEC_TRAC
   DTRACE_CU("cu_transquant_bypass_flag", uiSymbol); 
 #endif
+
   pcCU->setCUTransquantBypassSubParts(uiSymbol ? true : false, uiAbsPartIdx, uiDepth);
 }
@@ -539,5 +558,5 @@
 /** parse skip flag
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
  * \returns Void
@@ -549,8 +568,8 @@
     return;
   }
-  
+
   UInt uiSymbol = 0;
   UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx );
-  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SKIP_FLAG) );
 #if !H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
@@ -562,5 +581,4 @@
   DTRACE_CABAC_T( "\n");
 #endif
-  
   if( uiSymbol )
   {
@@ -568,5 +586,5 @@
     pcCU->setPredModeSubParts( MODE_INTER,  uiAbsPartIdx, uiDepth );
     pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
-    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( pcCU->getSlice()->getSPS()->getMaxCUWidth()>>uiDepth, pcCU->getSlice()->getSPS()->getMaxCUHeight()>>uiDepth, uiAbsPartIdx, uiDepth );
     pcCU->setMergeFlagSubParts( true , uiAbsPartIdx, 0, uiDepth );
   }
@@ -574,4 +592,5 @@
   DTRACE_CU("cu_skip_flag", uiSymbol); 
 #endif
+
 }
 #if H_3D
@@ -620,7 +639,9 @@
 }
 #endif
+
+
 /** parse merge flag
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
  * \param uiPUIdx
@@ -630,10 +651,9 @@
 {
   UInt uiSymbol;
-  m_pcTDecBinIf->decodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
+  m_pcTDecBinIf->decodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MERGE_FLAG) );
 #if H_MV_ENC_DEC_TRAC
   DTRACE_PU("merge_flag", uiSymbol)
 #endif
   pcCU->setMergeFlagSubParts( uiSymbol ? true : false, uiAbsPartIdx, uiPUIdx, uiDepth );
-
 #if !H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
@@ -641,5 +661,5 @@
   DTRACE_CABAC_V( uiSymbol );
   DTRACE_CABAC_T( "\tAddress: " );
-  DTRACE_CABAC_V( pcCU->getAddr() );
+  DTRACE_CABAC_V( pcCU->getCtuRsAddr() );
   DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
   DTRACE_CABAC_V( uiAbsPartIdx );
@@ -659,9 +679,9 @@
       if ( uiUnaryIdx==0 )
       {
-        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) );
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MERGE_INDEX) );
       }
       else
       {
-        m_pcTDecBinIf->decodeBinEP( uiSymbol );
+        m_pcTDecBinIf->decodeBinEP( uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MERGE_INDEX) );
       }
       if( uiSymbol == 0 )
@@ -688,5 +708,5 @@
 {
   UInt uiSymbol;
-  xReadUnaryMaxSymbol(uiSymbol, m_cMVPIdxSCModel.get(0), 1, AMVP_MAX_NUM_CANDS-1);
+  xReadUnaryMaxSymbol(uiSymbol, m_cMVPIdxSCModel.get(0), 1, AMVP_MAX_NUM_CANDS-1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVP_IDX) );
   riMVPIdx = uiSymbol;
 }
@@ -694,9 +714,12 @@
 Void TDecSbac::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
-  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+  if( uiDepth == pcCU->getSlice()->getSPS()->getLog2DiffMaxMinCodingBlockSize() )
   {
     pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
     return;
   }
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__SPLIT_FLAG, g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()>>uiDepth]+2);
+#endif
 
   UInt uiSymbol;
@@ -724,10 +747,10 @@
   {
 #endif
-    m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSplitFlagSCModel.get( 0, 0, pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ) ) );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSplitFlagSCModel.get( 0, 0, pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ) ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
 #if H_MV_ENC_DEC_TRAC
     DTRACE_CU("split_cu_flag", uiSymbol); 
 #else
-    DTRACE_CABAC_VL( g_nSymbolCounter++ )
-    DTRACE_CABAC_T( "\tSplitFlag\n" )
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tSplitFlag\n" )
 #endif
 #if H_3D_QTLPC
@@ -745,5 +768,5 @@
 /** parse partition size
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
  * \returns Void
@@ -753,4 +776,13 @@
   UInt uiSymbol, uiMode = 0;
   PartSize eMode;
+  const UChar cuWidth =UChar(pcCU->getSlice()->getSPS()->getMaxCUWidth()>>uiDepth);
+  const UChar cuHeight=UChar(pcCU->getSlice()->getSPS()->getMaxCUHeight()>>uiDepth);
+  const Int log2DiffMaxMinCodingBlockSize = pcCU->getSlice()->getSPS()->getLog2DiffMaxMinCodingBlockSize();
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__PART_SIZE, g_aucConvertToBit[cuWidth]+2);
+#endif
+
+  assert ( pcCU->getSlice()->getSPS()->getLog2DiffMaxMinCodingBlockSize() == log2DiffMaxMinCodingBlockSize);
 
 #if H_3D_QTLPC
@@ -788,5 +820,4 @@
 #endif
 
-
   if ( pcCU->isIntra( uiAbsPartIdx ) )
   {
@@ -795,17 +826,17 @@
     {
 #endif
-      uiSymbol = 1;
-      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
-      {
-        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+    uiSymbol = 1;
+    if( uiDepth == log2DiffMaxMinCodingBlockSize )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
 #if H_MV_ENC_DEC_TRAC          
         DTRACE_CU("part_mode", uiSymbol)
 #endif        
-      }
-      eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
+    }
+    eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
 #if H_3D_QTLPC
     }
 #endif
-    UInt uiTrLevel = 0;    
+    UInt uiTrLevel = 0;
     UInt uiWidthInBit  = g_aucConvertToBit[pcCU->getWidth(uiAbsPartIdx)]+2;
     UInt uiTrSizeInBit = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxTrSize()]+2;
@@ -828,6 +859,48 @@
       {
 #endif
-        UInt uiMaxNumBits = 2;
-        if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( (g_uiMaxCUWidth>>uiDepth) == 8 && (g_uiMaxCUHeight>>uiDepth) == 8 ) )
+    UInt uiMaxNumBits = 2;
+
+    if( uiDepth == log2DiffMaxMinCodingBlockSize && !( cuWidth == 8 && cuHeight == 8 ) )
+    {
+      uiMaxNumBits ++;
+    }
+
+    for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, ui) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      if ( uiSymbol )
+      {
+        break;
+      }
+      uiMode++;
+    }
+    eMode = (PartSize) uiMode;
+    if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
+    {
+      if (eMode == SIZE_2NxN)
+      {
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype));
+        if (uiSymbol == 0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+          eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+        }
+      }
+      else if (eMode == SIZE_Nx2N)
+      {
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+        if (uiSymbol == 0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+          eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
+        }
+      }
+    }
+#if H_3D_QTLPC
+      }
+      else if(uiTexturePart == SIZE_2NxN || uiTexturePart == SIZE_2NxnU || uiTexturePart == SIZE_2NxnD)
+      {
+        UInt uiMaxNumBits = 1;
+        if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
         {
           uiMaxNumBits ++;
@@ -843,28 +916,19 @@
         }
         eMode = (PartSize) uiMode;
-        if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
-        {
-          if (eMode == SIZE_2NxN)
-          {
-            m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-            if (uiSymbol == 0)
-            {
-              m_pcTDecBinIf->decodeBinEP(uiSymbol);
-              eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
-            }
-          }
-          else if (eMode == SIZE_Nx2N)
-          {
-            m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-            if (uiSymbol == 0)
-            {
-              m_pcTDecBinIf->decodeBinEP(uiSymbol);
-              eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
-            }
-          }
-        }
-#if H_3D_QTLPC
-      }
-      else if(uiTexturePart == SIZE_2NxN || uiTexturePart == SIZE_2NxnU || uiTexturePart == SIZE_2NxnD)
+        if(uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==1 )
+        {
+          eMode = SIZE_2NxN;
+        }
+        else if (uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth )==0  && uiSymbol==0)
+        {
+          eMode = SIZE_2NxN;
+        }
+        else if (uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol);
+          eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+        }
+      }
+      else if(uiTexturePart == SIZE_Nx2N|| uiTexturePart==SIZE_nLx2N || uiTexturePart==SIZE_nRx2N)
       {
         UInt uiMaxNumBits = 1;
@@ -885,35 +949,4 @@
         if(uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==1 )
         {
-          eMode = SIZE_2NxN;
-        }
-        else if (uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth )==0  && uiSymbol==0)
-        {
-          eMode = SIZE_2NxN;
-        }
-        else if (uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==0)
-        {
-          m_pcTDecBinIf->decodeBinEP(uiSymbol);
-          eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
-        }
-      }
-      else if(uiTexturePart == SIZE_Nx2N|| uiTexturePart==SIZE_nLx2N || uiTexturePart==SIZE_nRx2N)
-      {
-        UInt uiMaxNumBits = 1;
-        if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
-        {
-          uiMaxNumBits ++;
-        }
-        for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
-        {
-          m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, ui) );
-          if ( uiSymbol )
-          {
-            break;
-          }
-          uiMode++;
-        }
-        eMode = (PartSize) uiMode;
-        if(uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==1 )
-        {
           eMode = SIZE_Nx2N;
         }
@@ -941,10 +974,11 @@
   }
   pcCU->setPartSizeSubParts( eMode, uiAbsPartIdx, uiDepth );
-  pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
-}
+  pcCU->setSizeSubParts( cuWidth, cuHeight, uiAbsPartIdx, uiDepth );
+}
+
 
 /** parse prediction mode
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \param uiDepth
  * \returns Void
@@ -957,8 +991,8 @@
     return;
   }
-  
+
   UInt uiSymbol;
   Int  iPredMode = MODE_INTER;
-  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPredModeSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__PRED_MODE) );
   iPredMode += uiSymbol;
 #if H_MV_ENC_DEC_TRAC          
@@ -968,15 +1002,19 @@
 }
 
+
 Void TDecSbac::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
 {
   PartSize mode = pcCU->getPartitionSize( absPartIdx );
   UInt partNum = mode==SIZE_NxN?4:1;
-  UInt partOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
+  UInt partOffset = ( pcCU->getPic()->getNumPartitionsInCtu() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
   UInt mpmPred[4],symbol;
-  Int j,intraPredMode;    
+  Int j,intraPredMode;
   if (mode==SIZE_NxN)
   {
     depth++;
   }
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__INTRA_DIR_ANG, g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()>>depth]+2, CHANNEL_TYPE_LUMA);
+#endif
   for (j=0;j<partNum;j++)
   {
@@ -989,6 +1027,6 @@
     {
 #endif
-      m_pcTDecBinIf->decodeBin( symbol, m_cCUIntraPredSCModel.get( 0, 0, 0) );
-      mpmPred[j] = symbol;
+    m_pcTDecBinIf->decodeBin( symbol, m_cCUIntraPredSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+    mpmPred[j] = symbol;
 #if H_MV_ENC_DEC_TRAC          
       DTRACE_CU("prev_intra_luma_pred_flag", symbol)
@@ -1004,45 +1042,46 @@
     {
 #endif
-      Int preds[3] = {-1, -1, -1};
-      Int predNum = pcCU->getIntraDirLumaPredictor(absPartIdx+partOffset*j, preds);  
-      if (mpmPred[j])
-      {
-        m_pcTDecBinIf->decodeBinEP( symbol );
-        if (symbol)
-        {
-          m_pcTDecBinIf->decodeBinEP( symbol );
-          symbol++;
-        }
+    Int preds[NUM_MOST_PROBABLE_MODES] = {-1, -1, -1};
+    pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds, COMPONENT_Y);
+    if (mpmPred[j])
+    {
+      m_pcTDecBinIf->decodeBinEP( symbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      if (symbol)
+      {
+        m_pcTDecBinIf->decodeBinEP( symbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+        symbol++;
+      }
 #if H_MV_ENC_DEC_TRAC          
         DTRACE_CU("mpm_idx", symbol)
 #endif
-          intraPredMode = preds[symbol];
-      }
-      else
-      {
-        m_pcTDecBinIf->decodeBinsEP( symbol, 5 );
-        intraPredMode = symbol;
+      intraPredMode = preds[symbol];
+    }
+    else
+    {
+      m_pcTDecBinIf->decodeBinsEP( symbol, 5 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      intraPredMode = symbol;
 #if H_MV_ENC_DEC_TRAC          
         DTRACE_CU("rem_intra_luma_pred_mode", symbol)
 #endif        
-          //postponed sorting of MPMs (only in remaining branch)
-          if (preds[0] > preds[1])
-          { 
-            std::swap(preds[0], preds[1]); 
-          }
-          if (preds[0] > preds[2])
-          {
-            std::swap(preds[0], preds[2]);
-          }
-          if (preds[1] > preds[2])
-          {
-            std::swap(preds[1], preds[2]);
-          }
-          for ( Int i = 0; i < predNum; i++ )
-          {
-            intraPredMode += ( intraPredMode >= preds[i] );
-          }
-      }
-      pcCU->setLumaIntraDirSubParts( (UChar)intraPredMode, absPartIdx+partOffset*j, depth );
+
+      //postponed sorting of MPMs (only in remaining branch)
+      if (preds[0] > preds[1])
+      {
+        std::swap(preds[0], preds[1]);
+      }
+      if (preds[0] > preds[2])
+      {
+        std::swap(preds[0], preds[2]);
+      }
+      if (preds[1] > preds[2])
+      {
+        std::swap(preds[1], preds[2]);
+      }
+      for ( UInt i = 0; i < NUM_MOST_PROBABLE_MODES; i++ )
+      {
+        intraPredMode += ( intraPredMode >= preds[i] );
+      }
+    }
+    pcCU->setIntraDirSubParts(CHANNEL_TYPE_LUMA, (UChar)intraPredMode, absPartIdx+partOffset*j, depth );
 #if H_3D_DIM
     }
@@ -1051,10 +1090,13 @@
 }
 
+
 Void TDecSbac::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
   UInt uiSymbol;
-
-  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
-
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__INTRA_DIR_ANG, g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()>>uiDepth]+2, CHANNEL_TYPE_CHROMA);
+#endif
+
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
   if( uiSymbol == 0 )
   {
@@ -1062,21 +1104,19 @@
     DTRACE_CU("intra_chroma_pred_mode", uiSymbol )
 #endif        
-      uiSymbol = DM_CHROMA_IDX;
-  } 
-  else 
-  {
-    {
-      UInt uiIPredMode;
-      m_pcTDecBinIf->decodeBinsEP( uiIPredMode, 2 );
+    uiSymbol = DM_CHROMA_IDX;
+  }
+  else
+  {
+    UInt uiIPredMode;
+    m_pcTDecBinIf->decodeBinsEP( uiIPredMode, 2 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
 #if H_MV_ENC_DEC_TRAC          
       DTRACE_CU("intra_chroma_pred_mode", uiIPredMode )
 #endif        
-        UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
-      pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
-      uiSymbol = uiAllowedChromaDir[ uiIPredMode ];
-    }
-  }
-  pcCU->setChromIntraDirSubParts( uiSymbol, uiAbsPartIdx, uiDepth );
-  return;
+    UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
+    pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
+    uiSymbol = uiAllowedChromaDir[ uiIPredMode ];
+  }
+
+  pcCU->setIntraDirSubParts( CHANNEL_TYPE_CHROMA, uiSymbol, uiAbsPartIdx, uiDepth );
 }
 
@@ -1156,8 +1196,9 @@
   const UInt uiCtx = pcCU->getCtxInterDir( uiAbsPartIdx );
   ContextModel *pCtx = m_cCUInterDirSCModel.get( 0 );
+
   uiSymbol = 0;
   if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N || pcCU->getHeight(uiAbsPartIdx) != 8 )
   {
-    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + uiCtx ) );
+    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + uiCtx ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__INTER_DIR) );
   }
 
@@ -1168,5 +1209,5 @@
   else
   {
-    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + 4 ) );
+    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + 4 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__INTER_DIR) );
     assert(uiSymbol == 0 || uiSymbol == 1);
   }
@@ -1184,33 +1225,31 @@
 {
   UInt uiSymbol;
-  {
-    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
-    m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
-
-    if( uiSymbol )
-    {
-      UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
-      pCtx++;
-      UInt ui;
-      for( ui = 0; ui < uiRefNum; ++ui )
-      {
-        if( ui == 0 )
-        {
-          m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
-        }
-        else
-        {
-          m_pcTDecBinIf->decodeBinEP( uiSymbol );
-        }
-        if( uiSymbol == 0 )
-        {
-          break;
-        }
-      }
-      uiSymbol = ui + 1;
-    }
-    riRefFrmIdx = uiSymbol;
-  }
-
+
+  ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+  m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__REF_FRM_IDX) );
+
+  if( uiSymbol )
+  {
+    UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
+    pCtx++;
+    UInt ui;
+    for( ui = 0; ui < uiRefNum; ++ui )
+    {
+      if( ui == 0 )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__REF_FRM_IDX) );
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinEP( uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__REF_FRM_IDX) );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+    uiSymbol = ui + 1;
+  }
+  riRefFrmIdx = uiSymbol;
 #if H_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
@@ -1225,4 +1264,5 @@
 #endif
 #endif
+
   return;
 }
@@ -1244,6 +1284,6 @@
   else
   {
-    m_pcTDecBinIf->decodeBin( uiHorAbs, *pCtx );
-    m_pcTDecBinIf->decodeBin( uiVerAbs, *pCtx );
+    m_pcTDecBinIf->decodeBin( uiHorAbs, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD) );
+    m_pcTDecBinIf->decodeBin( uiVerAbs, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD) );
 
     const Bool bHorAbsGr0 = uiHorAbs != 0;
@@ -1253,5 +1293,5 @@
     if( bHorAbsGr0 )
     {
-      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD) );
       uiHorAbs += uiSymbol;
     }
@@ -1259,5 +1299,5 @@
     if( bVerAbsGr0 )
     {
-      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD) );
       uiVerAbs += uiSymbol;
     }
@@ -1267,9 +1307,9 @@
       if( 2 == uiHorAbs )
       {
-        xReadEpExGolomb( uiSymbol, 1 );
+        xReadEpExGolomb( uiSymbol, 1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD_EP) );
         uiHorAbs += uiSymbol;
       }
 
-      m_pcTDecBinIf->decodeBinEP( uiHorSign );
+      m_pcTDecBinIf->decodeBinEP( uiHorSign RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD_EP) );
     }
 
@@ -1278,9 +1318,9 @@
       if( 2 == uiVerAbs )
       {
-        xReadEpExGolomb( uiSymbol, 1 );
+        xReadEpExGolomb( uiSymbol, 1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD_EP) );
         uiVerAbs += uiSymbol;
       }
 
-      m_pcTDecBinIf->decodeBinEP( uiVerSign );
+      m_pcTDecBinIf->decodeBinEP( uiVerSign RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD_EP) );
     }
 
@@ -1292,8 +1332,62 @@
 }
 
+Void TDecSbac::parseCrossComponentPrediction( TComTU &rTu, ComponentID compID )
+{
+  TComDataCU *pcCU = rTu.getCU();
+
+  if( isLuma(compID) || !pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag() )
+  {
+    return;
+  }
+
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+
+  if (!pcCU->isIntra(uiAbsPartIdx) || (pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx ) == DM_CHROMA_IDX))
+  {
+    Char alpha  = 0;
+    UInt symbol = 0;
+
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T("\tparseCrossComponentPrediction()")
+    DTRACE_CABAC_T( "\tAddr=" )
+    DTRACE_CABAC_V( compID )
+    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+    DTRACE_CABAC_V( uiAbsPartIdx )
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__CROSS_COMPONENT_PREDICTION, (g_aucConvertToBit[rTu.getRect(compID).width] + 2), compID);
+#endif
+    ContextModel *pCtx = m_cCrossComponentPredictionSCModel.get(0, 0) + ((compID == COMPONENT_Cr) ? (NUM_CROSS_COMPONENT_PREDICTION_CTX >> 1) : 0);
+    m_pcTDecBinIf->decodeBin( symbol, pCtx[0] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+    if(symbol != 0)
+    {
+      // Cross-component prediction alpha is non-zero.
+      UInt sign = 0;
+      m_pcTDecBinIf->decodeBin( symbol, pCtx[1] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+      if (symbol != 0)
+      {
+        // alpha is 2 (symbol=1), 4(symbol=2) or 8(symbol=3).
+        // Read up to two more bits
+        xReadUnaryMaxSymbol( symbol, (pCtx + 2), 1, 2 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+        symbol += 1;
+      }
+      m_pcTDecBinIf->decodeBin( sign, pCtx[4] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+      alpha = (sign != 0) ? -(1 << symbol) : (1 << symbol);
+    }
+    DTRACE_CABAC_T( "\tAlpha=" )
+    DTRACE_CABAC_V( alpha )
+    DTRACE_CABAC_T( "\n" )
+
+    pcCU->setCrossComponentPredictionAlphaPartRange( alpha, compID, uiAbsPartIdx, rTu.GetAbsPartIdxNumParts( compID ) );
+  }
+}
 
 Void TDecSbac::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
 {
-  m_pcTDecBinIf->decodeBin( ruiSubdivFlag, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiLog2TransformBlockSize ) );
+  m_pcTDecBinIf->decodeBin( ruiSubdivFlag, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiLog2TransformBlockSize )
+      RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__TRANSFORM_SUBDIV_FLAG, 5-uiLog2TransformBlockSize))
+                          );
 #if !H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
@@ -1307,4 +1401,5 @@
   DTRACE_TU("split_transform_flag", ruiSubdivFlag )
 #endif
+
 }
 
@@ -1313,5 +1408,5 @@
   UInt uiSymbol;
   const UInt uiCtx = 0;
-  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__QT_ROOT_CBF) );
 #if !H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
@@ -1327,5 +1422,5 @@
   DTRACE_CU( "rqt_root_cbf", uiSymbol )
 #endif
-  
+
   uiQtRootCbf = uiSymbol;
 }
@@ -1336,12 +1431,12 @@
   UInt uiDQp;
   Int  iDQp;
-  
+
   UInt uiSymbol;
 
-  xReadUnaryMaxSymbol (uiDQp,  &m_cCUDeltaQpSCModel.get( 0, 0, 0 ), 1, CU_DQP_TU_CMAX);
+  xReadUnaryMaxSymbol (uiDQp,  &m_cCUDeltaQpSCModel.get( 0, 0, 0 ), 1, CU_DQP_TU_CMAX RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__DELTA_QP_EP) );
 
   if( uiDQp >= CU_DQP_TU_CMAX)
   {
-    xReadEpExGolomb( uiSymbol, CU_DQP_EG_k );
+    xReadEpExGolomb( uiSymbol, CU_DQP_EG_k RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__DELTA_QP_EP));
     uiDQp+=uiSymbol;
   }
@@ -1350,6 +1445,6 @@
   {
     UInt uiSign;
-    Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
-    m_pcTDecBinIf->decodeBinEP(uiSign);
+    Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
+    m_pcTDecBinIf->decodeBinEP(uiSign RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__DELTA_QP_EP));
     iDQp = uiDQp;
     if(uiSign)
@@ -1359,68 +1454,192 @@
     qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+qpBdOffsetY)) - qpBdOffsetY;
   }
-  else 
+  else
   {
     qp = pcCU->getRefQP(uiAbsPartIdx);
   }
-  pcCU->setQPSubParts(qp, uiAbsPartIdx, uiDepth);  
+
+  pcCU->setQPSubParts(qp, uiAbsPartIdx, uiDepth);
   pcCU->setCodedQP(qp);
 }
 
-Void TDecSbac::parseQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth )
-{
-  UInt uiSymbol;
-  const UInt uiCtx = pcCU->getCtxQtCbf( eType, uiTrDepth );
-  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA: eType, uiCtx ) );
+/** parse chroma qp adjustment, converting to the internal table representation.
+ * \returns Void
+ */
+Void TDecSbac::parseChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx, UInt depth )
+{
+  UInt symbol;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__CHROMA_QP_ADJUSTMENT, g_aucConvertToBit[cu->getSlice()->getSPS()->getMaxCUWidth()>>depth]+2, CHANNEL_TYPE_CHROMA);
+#endif
+
+  Int chromaQpOffsetListLen = cu->getSlice()->getPPS()->getPpsRangeExtension().getChromaQpOffsetListLen();
+
+  // cu_chroma_qp_offset_flag
+  m_pcTDecBinIf->decodeBin( symbol, m_ChromaQpAdjFlagSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+  if (symbol && chromaQpOffsetListLen > 1)
+  {
+    // cu_chroma_qp_offset_idx
+    xReadUnaryMaxSymbol( symbol,  &m_ChromaQpAdjIdcSCModel.get( 0, 0, 0 ), 0, chromaQpOffsetListLen - 1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+    symbol++;
+  }
+  /* NB, symbol = 0 if outer flag is not set,
+   *              1 if outer flag is set and there is no inner flag
+   *              1+ otherwise */
+  cu->setChromaQpAdjSubParts( symbol, absPartIdx, depth );
+  cu->setCodedChromaQpAdj(symbol);
+}
+
+Void TDecSbac::parseQtCbf( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
+{
+  TComDataCU* pcCU = rTu.getCU();
+
+  const UInt absPartIdx       = rTu.GetAbsPartIdxTU(compID);
+  const UInt TUDepth          = rTu.GetTransformDepthRel();
+  const UInt uiCtx            = pcCU->getCtxQtCbf( rTu, toChannelType(compID) );
+  const UInt contextSet       = toChannelType(compID);
+
+  const UInt width            = rTu.getRect(compID).width;
+  const UInt height           = rTu.getRect(compID).height;
+  const Bool canQuadSplit     = (width >= (MIN_TU_SIZE * 2)) && (height >= (MIN_TU_SIZE * 2));
+  const UInt coveredPartIdxes = rTu.GetAbsPartIdxNumParts(compID);
+
+  //             Since the CBF for chroma is coded at the highest level possible, if sub-TUs are
+  //             to be coded for a 4x8 chroma TU, their CBFs must be coded at the highest 4x8 level
+  //             (i.e. where luma TUs are 8x8 rather than 4x4)
+  //    ___ ___
+  //   |   |   | <- 4 x (8x8 luma + 4x8 4:2:2 chroma)
+  //   |___|___|    each quadrant has its own chroma CBF
+  //   |   |   | _ _ _ _
+  //   |___|___|        |
+  //   <--16--->        V
+  //                   _ _
+  //                  |_|_| <- 4 x 4x4 luma + 1 x 4x8 4:2:2 chroma
+  //                  |_|_|    no chroma CBF is coded - instead the parent CBF is inherited
+  //                  <-8->    if sub-TUs are present, their CBFs had to be coded at the parent level
+
+  const UInt lowestTUDepth = TUDepth + ((!lowestLevel && !canQuadSplit) ? 1 : 0); //unsplittable TUs inherit their parent's CBF
+        UInt lowestTUCBF   = 0;
+
+  if ((width != height) && (lowestLevel || !canQuadSplit)) //if sub-TUs are present
+  {
+    const UInt subTUDepth        = lowestTUDepth + 1;
+    const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
+
+    UInt combinedSubTUCBF = 0;
+
+    for (UInt subTU = 0; subTU < 2; subTU++)
+    {
+      UInt uiCbf = MAX_UINT;
+      m_pcTDecBinIf->decodeBin(uiCbf, m_cCUQtCbfSCModel.get(0, contextSet, uiCtx) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__QT_CBF, g_aucConvertToBit[rTu.getRect(compID).width]+2, compID)));
+
+      const UInt subTUAbsPartIdx = absPartIdx + (subTU * partIdxesPerSubTU);
+      pcCU->setCbfPartRange((uiCbf << subTUDepth), compID, subTUAbsPartIdx, partIdxesPerSubTU);
+      combinedSubTUCBF |= uiCbf;
 #if !H_MV_ENC_DEC_TRAC  
-  DTRACE_CABAC_VL( g_nSymbolCounter++ )
-  DTRACE_CABAC_T( "\tparseQtCbf()" )
-  DTRACE_CABAC_T( "\tsymbol=" )
-  DTRACE_CABAC_V( uiSymbol )
-  DTRACE_CABAC_T( "\tctx=" )
-  DTRACE_CABAC_V( uiCtx )
-  DTRACE_CABAC_T( "\tetype=" )
-  DTRACE_CABAC_V( eType )
-  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
-  DTRACE_CABAC_V( uiAbsPartIdx )
-  DTRACE_CABAC_T( "\n" )
+      DTRACE_CABAC_VL( g_nSymbolCounter++ )
+      DTRACE_CABAC_T( "\tparseQtCbf()" )
+      DTRACE_CABAC_T( "\tsub-TU=" )
+      DTRACE_CABAC_V( subTU )
+      DTRACE_CABAC_T( "\tsymbol=" )
+      DTRACE_CABAC_V( uiCbf )
+      DTRACE_CABAC_T( "\tctx=" )
+      DTRACE_CABAC_V( uiCtx )
+      DTRACE_CABAC_T( "\tetype=" )
+      DTRACE_CABAC_V( compID )
+      DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+      DTRACE_CABAC_V( subTUAbsPartIdx )
+      DTRACE_CABAC_T( "\n" )
 #else
-  if ( eType == TEXT_CHROMA_U )
-  {
-    DTRACE_TU("cbf_cb", uiSymbol )
-  }
-  else if ( eType == TEXT_CHROMA_V )
-  {
-    DTRACE_TU("cbf_cr", uiSymbol )
+  if ( compID == COMPONENT_Cb )
+  {
+    DTRACE_TU("cbf_cb", uiCbf )
+  }
+  else if ( compID == COMPONENT_Cr )
+  {
+    DTRACE_TU("cbf_cr", uiCbf )
   }
   else
   {
-    DTRACE_TU("cbf_luma", uiSymbol )
-  }
-#endif
-  
-  pcCU->setCbfSubParts( uiSymbol << uiTrDepth, eType, uiAbsPartIdx, uiDepth );
-}
-
-void TDecSbac::parseTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType)
-{
+    DTRACE_TU("cbf_luma", uiCbf )
+  }
+#endif
+
+    }
+
+    //propagate the sub-TU CBF up to the lowest TU level
+    if (combinedSubTUCBF != 0)
+    {
+      pcCU->bitwiseOrCbfPartRange((combinedSubTUCBF << lowestTUDepth), compID, absPartIdx, coveredPartIdxes);
+      lowestTUCBF = combinedSubTUCBF;
+    }
+  }
+  else
+  {
+    UInt uiCbf = MAX_UINT;
+    m_pcTDecBinIf->decodeBin(uiCbf, m_cCUQtCbfSCModel.get(0, contextSet, uiCtx) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__QT_CBF, g_aucConvertToBit[rTu.getRect(compID).width]+2, compID)));
+
+    pcCU->setCbfSubParts((uiCbf << lowestTUDepth), compID, absPartIdx, rTu.GetTransformDepthTotalAdj(compID));
+#if !H_MV_ENC_DEC_TRAC
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tparseQtCbf()" )
+    DTRACE_CABAC_T( "\tsymbol=" )
+    DTRACE_CABAC_V( uiCbf )
+    DTRACE_CABAC_T( "\tctx=" )
+    DTRACE_CABAC_V( uiCtx )
+    DTRACE_CABAC_T( "\tetype=" )
+    DTRACE_CABAC_V( compID )
+    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+    DTRACE_CABAC_V( rTu.GetAbsPartIdxTU(compID) )
+    DTRACE_CABAC_T( "\n" )
+#else
+    if ( compID == COMPONENT_Cb )
+    {
+      DTRACE_TU("cbf_cb", uiCbf )
+    }
+    else if ( compID == COMPONENT_Cr )
+    {
+      DTRACE_TU("cbf_cr", uiCbf )
+    }
+    else
+    {
+      DTRACE_TU("cbf_luma", uiCbf )
+    }
+#endif
+    lowestTUCBF = uiCbf;
+  }
+
+  //propagate the lowest level CBF up to the current level
+  if (lowestTUCBF != 0)
+  {
+    for (UInt depth = TUDepth; depth < lowestTUDepth; depth++)
+    {
+      pcCU->bitwiseOrCbfPartRange((lowestTUCBF << depth), compID, absPartIdx, coveredPartIdxes);
+    }
+  }
+}
+
+
+Void TDecSbac::parseTransformSkipFlags (TComTU &rTu, ComponentID component)
+{
+  TComDataCU* pcCU=rTu.getCU();
+  UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU(component);
+
   if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
   {
     return;
   }
-  if(width != 4 || height != 4)
+
+  if (!TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(component), pcCU->getSlice()->getPPS()->getPpsRangeExtension().getLog2MaxTransformSkipBlockSize()))
   {
     return;
   }
-  
+
   UInt useTransformSkip;
-  m_pcTDecBinIf->decodeBin( useTransformSkip , m_cTransformSkipSCModel.get( 0, eTType? TEXT_CHROMA: TEXT_LUMA, 0 ) );
-  if(eTType!= TEXT_LUMA)
-  {
-    const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiDepth;
-    if(uiLog2TrafoSize == 2) 
-    { 
-      uiDepth --;
-    }
-  }
+
+  m_pcTDecBinIf->decodeBin( useTransformSkip , m_cTransformSkipSCModel.get( 0, toChannelType(component), 0 )
+      RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__TRANSFORM_SKIP_FLAGS, component))
+                          );
+
 #if !H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
@@ -1429,14 +1648,15 @@
   DTRACE_CABAC_V( useTransformSkip )
   DTRACE_CABAC_T( "\tAddr=" )
-  DTRACE_CABAC_V( pcCU->getAddr() )
+  DTRACE_CABAC_V( pcCU->getCtuRsAddr() )
   DTRACE_CABAC_T( "\tetype=" )
-  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_V( component )
   DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
-  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_V( rTu.GetAbsPartIdxTU() )
   DTRACE_CABAC_T( "\n" )
 #endif
 
-  pcCU->setTransformSkipSubParts( useTransformSkip, eTType, uiAbsPartIdx, uiDepth);
-}
+  pcCU->setTransformSkipPartRange( useTransformSkip, component, uiAbsPartIdx, rTu.GetAbsPartIdxNumParts(component));
+}
+
 
 /** Parse (X,Y) position of the last significant coefficient
@@ -1445,24 +1665,37 @@
  * \param width  Block width
  * \param height Block height
- * \param eTType plane type / luminance or chrominance
+ * \param component chroma compinent ID
  * \param uiScanIdx scan type (zig-zag, hor, ver)
  *
  * This method decodes the X and Y component within a block of the last significant coefficient.
  */
-Void TDecSbac::parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, TextType eTType, UInt uiScanIdx )
+Void TDecSbac::parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, ComponentID component, UInt uiScanIdx )
 {
   UInt uiLast;
-  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType );
-  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType );
+
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, toChannelType(component) );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, toChannelType(component) );
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__LAST_SIG_X_Y, g_aucConvertToBit[width]+2, component);
+#endif
+
+
+  if ( uiScanIdx == SCAN_VER )
+  {
+    swap( width, height );
+  }
 
   Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
-  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
-  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
-  shiftX= eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
-  shiftY= eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
+  getLastSignificantContextParameters(component, width, height, blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY);
+
+  //------------------
+
   // posX
+
   for( uiPosLastX = 0; uiPosLastX < g_uiGroupIdx[ width - 1 ]; uiPosLastX++ )
   {
-    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxX + blkSizeOffsetX + (uiPosLastX >>shiftX) ) );
+    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxX + blkSizeOffsetX + (uiPosLastX >>shiftX) ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
     if( !uiLast )
     {
@@ -1472,7 +1705,9 @@
 
   // posY
+
   for( uiPosLastY = 0; uiPosLastY < g_uiGroupIdx[ height - 1 ]; uiPosLastY++ )
   {
-    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxY + blkSizeOffsetY + (uiPosLastY >>shiftY)) );
+    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxY + blkSizeOffsetY + (uiPosLastY >>shiftY)) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
     if( !uiLast )
     {
@@ -1480,4 +1715,7 @@
     }
   }
+
+  // EP-coded part
+
   if ( uiPosLastX > 3 )
   {
@@ -1486,5 +1724,5 @@
     for ( Int i = uiCount - 1; i >= 0; i-- )
     {
-      m_pcTDecBinIf->decodeBinEP( uiLast );
+      m_pcTDecBinIf->decodeBinEP( uiLast RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
       uiTemp += uiLast << i;
     }
@@ -1497,10 +1735,10 @@
     for ( Int i = uiCount - 1; i >= 0; i-- )
     {
-      m_pcTDecBinIf->decodeBinEP( uiLast );
+      m_pcTDecBinIf->decodeBinEP( uiLast RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
       uiTemp += uiLast << i;
     }
     uiPosLastY = g_uiMinInGroup[ uiPosLastY ] + uiTemp;
   }
-  
+
   if( uiScanIdx == SCAN_VER )
   {
@@ -1509,10 +1747,17 @@
 }
 
-Void TDecSbac::parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
-{
+Void TDecSbac::parseCoeffNxN(  TComTU &rTu, ComponentID compID )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU(compID);
+  const TComRectangle &rRect=rTu.getRect(compID);
+  const UInt uiWidth=rRect.width;
+  const UInt uiHeight=rRect.height;
+  TCoeff* pcCoef=(pcCU->getCoeff(compID)+rTu.getCoefficientOffset(compID));
+  const TComSPS &sps=*(pcCU->getSlice()->getSPS());
 #if !H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
-  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_V( compID )
   DTRACE_CABAC_T( "\twidth=" )
   DTRACE_CABAC_V( uiWidth )
@@ -1520,7 +1765,9 @@
   DTRACE_CABAC_V( uiHeight )
   DTRACE_CABAC_T( "\tdepth=" )
-  DTRACE_CABAC_V( uiDepth )
+//  DTRACE_CABAC_V( rTu.GetTransformDepthTotalAdj(compID) )
+  DTRACE_CABAC_V( rTu.GetTransformDepthTotal() )
   DTRACE_CABAC_T( "\tabspartidx=" )
-  DTRACE_CABAC_V( uiAbsPartIdx )
+//  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_V( rTu.GetAbsPartIdxTU(compID) )
   DTRACE_CABAC_T( "\ttoCU-X=" )
   DTRACE_CABAC_V( pcCU->getCUPelX() )
@@ -1528,44 +1775,119 @@
   DTRACE_CABAC_V( pcCU->getCUPelY() )
   DTRACE_CABAC_T( "\tCU-addr=" )
-  DTRACE_CABAC_V(  pcCU->getAddr() )
+  DTRACE_CABAC_V(  pcCU->getCtuRsAddr() )
   DTRACE_CABAC_T( "\tinCU-X=" )
-  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+//  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
   DTRACE_CABAC_T( "\tinCU-Y=" )
-  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+// DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
   DTRACE_CABAC_T( "\tpredmode=" )
   DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
   DTRACE_CABAC_T( "\n" )
 #endif
-  
-  if( uiWidth > pcCU->getSlice()->getSPS()->getMaxTrSize() )
-  {
-    uiWidth  = pcCU->getSlice()->getSPS()->getMaxTrSize();
-    uiHeight = pcCU->getSlice()->getSPS()->getMaxTrSize();
-  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  if( uiWidth > sps.getMaxTrSize() )
+  {
+    std::cerr << "ERROR: parseCoeffNxN was passed a TU with dimensions larger than the maximum allowed size" << std::endl;
+    assert(false);
+    exit(1);
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  //set parameters
+
+  const ChannelType  chType            = toChannelType(compID);
+  const UInt         uiLog2BlockWidth  = g_aucConvertToBit[ uiWidth  ] + 2;
+  const UInt         uiLog2BlockHeight = g_aucConvertToBit[ uiHeight ] + 2;
+  const UInt         uiMaxNumCoeff     = uiWidth * uiHeight;
+  const UInt         uiMaxNumCoeffM1   = uiMaxNumCoeff - 1;
+
+  const ChannelType  channelType       = toChannelType(compID);
+  const Bool         extendedPrecision = sps.getSpsRangeExtension().getExtendedPrecisionProcessingFlag();
+
+  const Bool         alignCABACBeforeBypass = sps.getSpsRangeExtension().getCabacBypassAlignmentEnabledFlag();
+  const Int          maxLog2TrDynamicRange  = sps.getMaxLog2TrDynamicRange(channelType);
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatisticsClassType ctype_group(STATS__CABAC_BITS__SIG_COEFF_GROUP_FLAG, uiLog2BlockWidth, compID);
+  TComCodingStatisticsClassType ctype_map(STATS__CABAC_BITS__SIG_COEFF_MAP_FLAG, uiLog2BlockWidth, compID);
+  TComCodingStatisticsClassType ctype_gt1(STATS__CABAC_BITS__GT1_FLAG, uiLog2BlockWidth, compID);
+  TComCodingStatisticsClassType ctype_gt2(STATS__CABAC_BITS__GT2_FLAG, uiLog2BlockWidth, compID);
+#endif
+
+  Bool beValid;
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    beValid = false;
+    if((!pcCU->isIntra(uiAbsPartIdx)) && pcCU->isRDPCMEnabled(uiAbsPartIdx))
+    {
+      parseExplicitRdpcmMode(rTu, compID);
+    }
+  }
+  else
+  {
+    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag();
+  }
+
+  UInt absSum = 0;
+
+  //--------------------------------------------------------------------------------------------------
+
   if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
   {
-    parseTransformSkipFlags( pcCU, uiAbsPartIdx, uiWidth, uiHeight, uiDepth, eTType);
-  }
-
-  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : ( eTType == TEXT_NONE ? TEXT_NONE : TEXT_CHROMA );
-  
-  //----- parse significance map -----
-  const UInt  uiLog2BlockSize   = g_aucConvertToBit[ uiWidth ] + 2;
-  const UInt  uiMaxNumCoeff     = uiWidth * uiHeight;
-  const UInt  uiMaxNumCoeffM1   = uiMaxNumCoeff - 1;
-  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
-  
+    parseTransformSkipFlags(rTu, compID);
+    //  This TU has coefficients and is transform skipped. Check whether is inter coded and if yes decode the explicit RDPCM mode
+    if(pcCU->getTransformSkip(uiAbsPartIdx, compID) && (!pcCU->isIntra(uiAbsPartIdx)) && pcCU->isRDPCMEnabled(uiAbsPartIdx) )
+    {
+      parseExplicitRdpcmMode(rTu, compID);
+      if(pcCU->getExplicitRdpcmMode(compID, uiAbsPartIdx) != RDPCM_OFF)
+      {
+        //  Sign data hiding is avoided for horizontal and vertical RDPCM modes
+        beValid = false;
+      }
+    }
+  }
+
+  Int uiIntraMode = -1;
+  const Bool       bIsLuma = isLuma(compID);
+  Int isIntra = pcCU->isIntra(uiAbsPartIdx) ? 1 : 0;
+  if ( isIntra && pcCU->isRDPCMEnabled(uiAbsPartIdx) )
+  {
+    const UInt partsPerMinCU = 1<<(2*(sps.getMaxTotalCUDepth() - sps.getLog2DiffMaxMinCodingBlockSize()));
+    uiIntraMode = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
+    uiIntraMode = (uiIntraMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, rTu.GetChromaFormat(), partsPerMinCU)) : uiIntraMode;
+    uiIntraMode = ((rTu.GetChromaFormat() == CHROMA_422) && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiIntraMode] : uiIntraMode;
+
+    Bool transformSkip = pcCU->getTransformSkip( uiAbsPartIdx,compID);
+    Bool rdpcm_lossy = ( transformSkip /*&& isIntra*/ && ( (uiIntraMode == HOR_IDX) || (uiIntraMode == VER_IDX) ) );
+    if ( rdpcm_lossy )
+    {
+      beValid = false;
+    }
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  const Bool  bUseGolombRiceParameterAdaptation = sps.getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag();
+        UInt &currentGolombRiceStatistic        = m_golombRiceAdaptationStatistics[rTu.getGolombRiceStatisticsIndex(compID)];
+
+  //select scans
+  TUEntropyCodingParameters codingParameters;
+  getTUEntropyCodingParameters(codingParameters, rTu, compID);
+
   //===== decode last significant =====
   UInt uiPosLastX, uiPosLastY;
-  parseLastSignificantXY( uiPosLastX, uiPosLastY, uiWidth, uiHeight, eTType, uiScanIdx );
-  UInt uiBlkPosLast      = uiPosLastX + (uiPosLastY<<uiLog2BlockSize);
+  parseLastSignificantXY( uiPosLastX, uiPosLastY, uiWidth, uiHeight, compID, codingParameters.scanType );
+  UInt uiBlkPosLast      = uiPosLastX + (uiPosLastY<<uiLog2BlockWidth);
   pcCoef[ uiBlkPosLast ] = 1;
 
   //===== decode significance flags =====
   UInt uiScanPosLast;
-  const UInt *scan   = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize-1 ];
   for( uiScanPosLast = 0; uiScanPosLast < uiMaxNumCoeffM1; uiScanPosLast++ )
   {
-    UInt uiBlkPos = scan[ uiScanPosLast ];
+    UInt uiBlkPos = codingParameters.scan[ uiScanPosLast ];
     if( uiBlkPosLast == uiBlkPos )
     {
@@ -1574,47 +1896,30 @@
   }
 
-  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, eTType );
-  ContextModel * const baseCtx = (eTType==TEXT_LUMA) ? m_cCUSigSCModel.get( 0, 0 ) : m_cCUSigSCModel.get( 0, 0 ) + NUM_SIG_FLAG_CTX_LUMA;
-
-  const Int  iLastScanSet      = uiScanPosLast >> LOG2_SCAN_SET_SIZE;
-  UInt c1 = 1;
-  UInt uiGoRiceParam           = 0;
-
-  Bool beValid; 
-  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
-  {
-    beValid = false;
-  }
-  else 
-  {
-    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
-  }
-  UInt absSum = 0;
+  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, isChroma(chType) );
+  ContextModel * const baseCtx = m_cCUSigSCModel.get( 0, 0 ) + getSignificanceMapContextOffset(compID);
+
+  const Int  iLastScanSet  = uiScanPosLast >> MLS_CG_SIZE;
+  UInt c1                  = 1;
+  UInt uiGoRiceParam       = 0;
+
 
   UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
-  ::memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
-  const UInt uiNumBlkSide = uiWidth >> (MLS_CG_SIZE >> 1);
-  const UInt * scanCG;
-  {
-    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0  ];    
-    if( uiLog2BlockSize == 3 )
-    {
-      scanCG = g_sigLastScan8x8[ uiScanIdx ];
-    }
-    else if( uiLog2BlockSize == 5 )
-    {
-      scanCG = g_sigLastScanCG32x32;
-    }
-  }
+  memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
+
   Int  iScanPosSig             = (Int) uiScanPosLast;
   for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
   {
-    Int  iSubPos     = iSubSet << LOG2_SCAN_SET_SIZE;
-    uiGoRiceParam    = 0;
+    Int  iSubPos   = iSubSet << MLS_CG_SIZE;
+    uiGoRiceParam  = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+    Bool updateGolombRiceStatistics = bUseGolombRiceParameterAdaptation; //leave the statistics at 0 when not using the adaptation system
     Int numNonZero = 0;
-    
-    Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE;
-
-    Int pos[SCAN_SET_SIZE];
+
+    Int lastNZPosInCG  = -1;
+    Int firstNZPosInCG = 1 << MLS_CG_SIZE;
+
+    Bool escapeDataPresentInGroup = false;
+
+    Int pos[1 << MLS_CG_SIZE];
+
     if( iScanPosSig == (Int) uiScanPosLast )
     {
@@ -1627,7 +1932,8 @@
 
     // decode significant_coeffgroup_flag
-    Int iCGBlkPos = scanCG[ iSubSet ];
-    Int iCGPosY   = iCGBlkPos / uiNumBlkSide;
-    Int iCGPosX   = iCGBlkPos - (iCGPosY * uiNumBlkSide);
+    Int iCGBlkPos = codingParameters.scanCG[ iSubSet ];
+    Int iCGPosY   = iCGBlkPos / codingParameters.widthInGroups;
+    Int iCGPosX   = iCGBlkPos - (iCGPosY * codingParameters.widthInGroups);
+
     if( iSubSet == iLastScanSet || iSubSet == 0)
     {
@@ -1637,25 +1943,24 @@
     {
       UInt uiSigCoeffGroup;
-      UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
-      m_pcTDecBinIf->decodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+      UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups );
+      m_pcTDecBinIf->decodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_group) );
       uiSigCoeffGroupFlag[ iCGBlkPos ] = uiSigCoeffGroup;
     }
 
     // decode significant_coeff_flag
-    Int patternSigCtx = TComTrQuant::calcPatternSigCtx( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
-    UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig;
+    const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups);
+
+    UInt uiBlkPos, uiSig, uiCtxSig;
     for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
     {
-      uiBlkPos  = scan[ iScanPosSig ];
-      uiPosY    = uiBlkPos >> uiLog2BlockSize;
-      uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+      uiBlkPos  = codingParameters.scan[ iScanPosSig ];
       uiSig     = 0;
-      
+
       if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
       {
         if( iScanPosSig > iSubPos || iSubSet == 0  || numNonZero )
         {
-          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, uiLog2BlockSize, eTType );
-          m_pcTDecBinIf->decodeBin( uiSig, baseCtx[ uiCtxSig ] );
+          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, codingParameters, iScanPosSig, uiLog2BlockWidth, uiLog2BlockHeight, chType );
+          m_pcTDecBinIf->decodeBin( uiSig, baseCtx[ uiCtxSig ] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_map) );
         }
         else
@@ -1676,20 +1981,23 @@
       }
     }
-    
-    if( numNonZero )
+
+    if( numNonZero > 0 )
     {
       Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD );
+
       absSum = 0;
-      UInt uiCtxSet    = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0;
+
+      const UInt uiCtxSet = getContextSetIndex(compID, iSubSet, (c1 == 0));
+      c1 = 1;
       UInt uiBin;
-      if( c1 == 0 )
-      {
-        uiCtxSet++;
-      }
-      c1 = 1;
-      ContextModel *baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUOneSCModel.get( 0, 0 ) + 4 * uiCtxSet : m_cCUOneSCModel.get( 0, 0 ) + NUM_ONE_FLAG_CTX_LUMA + 4 * uiCtxSet;
-      Int absCoeff[SCAN_SET_SIZE];
-
-      for ( Int i = 0; i < numNonZero; i++) absCoeff[i] = 1;   
+
+      ContextModel *baseCtxMod = m_cCUOneSCModel.get( 0, 0 ) + (NUM_ONE_FLAG_CTX_PER_SET * uiCtxSet);
+
+      Int absCoeff[1 << MLS_CG_SIZE];
+
+      for ( Int i = 0; i < numNonZero; i++)
+      {
+        absCoeff[i] = 1;
+      }
       Int numC1Flag = min(numNonZero, C1FLAG_NUMBER);
       Int firstC2FlagIdx = -1;
@@ -1697,5 +2005,5 @@
       for( Int idx = 0; idx < numC1Flag; idx++ )
       {
-        m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[c1] );
+        m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[c1] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_gt1) );
         if( uiBin == 1 )
         {
@@ -1705,4 +2013,8 @@
             firstC2FlagIdx = idx;
           }
+          else //if a greater-than-one has been encountered already this group
+          {
+            escapeDataPresentInGroup = true;
+          }
         }
         else if( (c1 < 3) && (c1 > 0) )
@@ -1712,13 +2024,31 @@
         absCoeff[ idx ] = uiBin + 1;
       }
-      
+
       if (c1 == 0)
       {
-        baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUAbsSCModel.get( 0, 0 ) + uiCtxSet : m_cCUAbsSCModel.get( 0, 0 ) + NUM_ABS_FLAG_CTX_LUMA + uiCtxSet;
+        baseCtxMod = m_cCUAbsSCModel.get( 0, 0 ) + (NUM_ABS_FLAG_CTX_PER_SET * uiCtxSet);
         if ( firstC2FlagIdx != -1)
         {
-          m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[0] ); 
+          m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[0] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_gt2) );
           absCoeff[ firstC2FlagIdx ] = uiBin + 2;
-        }
+          if (uiBin != 0)
+          {
+            escapeDataPresentInGroup = true;
+          }
+        }
+      }
+
+      escapeDataPresentInGroup = escapeDataPresentInGroup || (numNonZero > C1FLAG_NUMBER);
+
+      const Bool alignGroup = escapeDataPresentInGroup && alignCABACBeforeBypass;
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+      TComCodingStatisticsClassType ctype_signs((alignGroup ? STATS__CABAC_BITS__ALIGNED_SIGN_BIT    : STATS__CABAC_BITS__SIGN_BIT   ), uiLog2BlockWidth, compID);
+      TComCodingStatisticsClassType ctype_escs ((alignGroup ? STATS__CABAC_BITS__ALIGNED_ESCAPE_BITS : STATS__CABAC_BITS__ESCAPE_BITS), uiLog2BlockWidth, compID);
+#endif
+
+      if (alignGroup)
+      {
+        m_pcTDecBinIf->align();
       }
 
@@ -1726,15 +2056,15 @@
       if ( signHidden && beValid )
       {
-        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero-1 );
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero-1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_signs) );
         coeffSigns <<= 32 - (numNonZero-1);
       }
       else
       {
-        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero );
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_signs) );
         coeffSigns <<= 32 - numNonZero;
       }
-      
-      Int iFirstCoeff2 = 1;    
-      if (c1 == 0 || numNonZero > C1FLAG_NUMBER)
+
+      Int iFirstCoeff2 = 1;
+      if (escapeDataPresentInGroup)
       {
         for( Int idx = 0; idx < numNonZero; idx++ )
@@ -1745,13 +2075,31 @@
           {
             UInt uiLevel;
-            xReadCoefRemainExGolomb( uiLevel, uiGoRiceParam );
+            xReadCoefRemainExGolomb( uiLevel, uiGoRiceParam, extendedPrecision, maxLog2TrDynamicRange RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_escs) );
+
             absCoeff[ idx ] = uiLevel + baseLevel;
-            if(absCoeff[idx]>3*(1<<uiGoRiceParam))
+
+            if (absCoeff[idx] > (3 << uiGoRiceParam))
             {
-              uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+              uiGoRiceParam = bUseGolombRiceParameterAdaptation ? (uiGoRiceParam + 1) : (std::min<UInt>((uiGoRiceParam + 1), 4));
+            }
+
+            if (updateGolombRiceStatistics)
+            {
+              const UInt initialGolombRiceParameter = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+
+              if (uiLevel >= (3 << initialGolombRiceParameter))
+              {
+                currentGolombRiceStatistic++;
+              }
+              else if (((uiLevel * 2) < (1 << initialGolombRiceParameter)) && (currentGolombRiceStatistic > 0))
+              {
+                currentGolombRiceStatistic--;
+              }
+
+              updateGolombRiceStatistics = false;
             }
           }
 
-          if(absCoeff[ idx ] >= 2)  
+          if(absCoeff[ idx ] >= 2)
           {
             iFirstCoeff2 = 0;
@@ -1784,8 +2132,11 @@
     }
   }
-  
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  printSBACCoeffData(uiPosLastX, uiPosLastY, uiWidth, uiHeight, compID, uiAbsPartIdx, codingParameters.scanType, pcCoef);
+#endif
+
   return;
 }
-
 
 Void TDecSbac::parseSaoMaxUvlc ( UInt& val, UInt maxSymbol )
@@ -1799,5 +2150,5 @@
   UInt code;
   Int  i;
-  m_pcTDecBinIf->decodeBinEP( code );
+  m_pcTDecBinIf->decodeBinEP( code RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
   if ( code == 0 )
   {
@@ -1809,5 +2160,5 @@
   while (1)
   {
-    m_pcTDecBinIf->decodeBinEP( code );
+    m_pcTDecBinIf->decodeBinEP( code RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
     if ( code == 0 )
     {
@@ -1815,5 +2166,5 @@
     }
     i++;
-    if (i == maxSymbol) 
+    if (i == maxSymbol)
     {
       break;
@@ -1823,19 +2174,22 @@
   val = i;
 }
+
 Void TDecSbac::parseSaoUflc (UInt uiLength, UInt&  riVal)
 {
-  m_pcTDecBinIf->decodeBinsEP ( riVal, uiLength );
-}
+  m_pcTDecBinIf->decodeBinsEP ( riVal, uiLength RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+}
+
 Void TDecSbac::parseSaoMerge (UInt&  ruiVal)
 {
   UInt uiCode;
-  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeSCModel.get( 0, 0, 0 ) );
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
   ruiVal = (Int)uiCode;
 }
+
 Void TDecSbac::parseSaoTypeIdx (UInt&  ruiVal)
 {
   UInt uiCode;
-  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
-  if (uiCode == 0) 
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+  if (uiCode == 0)
   {
     ruiVal = 0;
@@ -1843,5 +2197,5 @@
   else
   {
-    m_pcTDecBinIf->decodeBinEP( uiCode ); 
+    m_pcTDecBinIf->decodeBinEP( uiCode RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
     if (uiCode == 0)
     {
@@ -1857,5 +2211,5 @@
 Void TDecSbac::parseSaoSign(UInt& val)
 {
-  m_pcTDecBinIf->decodeBinEP ( val ); 
+  m_pcTDecBinIf->decodeBinEP ( val RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
 }
 
@@ -1864,4 +2218,5 @@
                                 , Bool leftMergeAvail
                                 , Bool aboveMergeAvail
+                                , const BitDepths &bitDepths
                                 )
 {
@@ -1884,24 +2239,35 @@
 
   if(isLeftMerge || isAboveMerge) //merge mode
-      {
-    saoBlkParam[SAO_Y].modeIdc = saoBlkParam[SAO_Cb].modeIdc = saoBlkParam[SAO_Cr].modeIdc = SAO_MODE_MERGE;
-    saoBlkParam[SAO_Y].typeIdc = saoBlkParam[SAO_Cb].typeIdc = saoBlkParam[SAO_Cr].typeIdc = (isLeftMerge)?SAO_MERGE_LEFT:SAO_MERGE_ABOVE;
-      }   
+  {
+    for (UInt componentIndex = 0; componentIndex < MAX_NUM_COMPONENT; componentIndex++)
+    {
+      saoBlkParam[componentIndex].modeIdc = (sliceEnabled[componentIndex]) ? SAO_MODE_MERGE : SAO_MODE_OFF;
+      saoBlkParam[componentIndex].typeIdc = (isLeftMerge)?SAO_MERGE_LEFT:SAO_MERGE_ABOVE;
+    }
+  }
   else //new or off mode
-      {
-    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
-        {
+  {
+    for(Int compId=COMPONENT_Y; compId < MAX_NUM_COMPONENT; compId++)
+    {
+      const ComponentID compIdx=ComponentID(compId);
+      const ComponentID firstCompOfChType = getFirstComponentOfChannel(toChannelType(compIdx));
       SAOOffset& ctbParam = saoBlkParam[compIdx];
-
+#if O0043_BEST_EFFORT_DECODING
+      const Int bitDepthOrig = bitDepths.stream[toChannelType(compIdx)];
+      const Int forceBitDepthAdjust = bitDepthOrig - bitDepths.recon[toChannelType(compIdx)];
+#else
+      const Int bitDepthOrig = bitDepths.recon[toChannelType(compIdx)];
+#endif
+      const Int maxOffsetQVal=TComSampleAdaptiveOffset::getMaxOffsetQVal(bitDepthOrig);
       if(!sliceEnabled[compIdx])
-          {
+      {
         //off
         ctbParam.modeIdc = SAO_MODE_OFF;
         continue;
-        }
+      }
 
       //type
-      if(compIdx == SAO_Y || compIdx == SAO_Cb)
-    {
+      if(compIdx == firstCompOfChType)
+      {
         parseSaoTypeIdx(uiSymbol); //sao_type_idx_luma or sao_type_idx_chroma
 
@@ -1909,54 +2275,57 @@
 
         if(uiSymbol ==0) //OFF
-     {
+        {
           ctbParam.modeIdc = SAO_MODE_OFF;
-   }
+        }
         else if(uiSymbol == 1) //BO
         {
           ctbParam.modeIdc = SAO_MODE_NEW;
           ctbParam.typeIdc = SAO_TYPE_START_BO;
-  }
+        }
         else //2, EO
-  {
+        {
           ctbParam.modeIdc = SAO_MODE_NEW;
           ctbParam.typeIdc = SAO_TYPE_START_EO;
         }
 
-  }
+      }
       else //Cr, follow Cb SAO type
       {
-        ctbParam.modeIdc = saoBlkParam[SAO_Cb].modeIdc;
-        ctbParam.typeIdc = saoBlkParam[SAO_Cb].typeIdc;
-}
+        ctbParam.modeIdc = saoBlkParam[COMPONENT_Cb].modeIdc;
+        ctbParam.typeIdc = saoBlkParam[COMPONENT_Cb].typeIdc;
+      }
 
       if(ctbParam.modeIdc == SAO_MODE_NEW)
-{
+      {
         Int offset[4];
         for(Int i=0; i< 4; i++)
-  {
-          parseSaoMaxUvlc(uiSymbol,  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+        {
+          parseSaoMaxUvlc(uiSymbol, maxOffsetQVal ); //sao_offset_abs
           offset[i] = (Int)uiSymbol;
-  }
+        }
 
         if(ctbParam.typeIdc == SAO_TYPE_START_BO)
-  {
+        {
           for(Int i=0; i< 4; i++)
-    {
+          {
             if(offset[i] != 0)
-    {
+            {
               parseSaoSign(uiSymbol); //sao_offset_sign
               if(uiSymbol)
-      {
+              {
+#if O0043_BEST_EFFORT_DECODING
+                offset[i] >>= forceBitDepthAdjust;
+#endif
                 offset[i] = -offset[i];
-      }
-    }
-  }
+              }
+            }
+          }
           parseSaoUflc(NUM_SAO_BO_CLASSES_LOG2, uiSymbol ); //sao_band_position
           ctbParam.typeAuxInfo = uiSymbol;
 
           for(Int i=0; i<4; i++)
-      {
+          {
             ctbParam.offset[(ctbParam.typeAuxInfo+i)%MAX_NUM_SAO_CLASSES] = offset[i];
-      }
+          }
 
         }
@@ -1965,13 +2334,13 @@
           ctbParam.typeAuxInfo = 0;
 
-          if(compIdx == SAO_Y || compIdx == SAO_Cb)
-        {
+          if(firstCompOfChType == compIdx)
+          {
             parseSaoUflc(NUM_SAO_EO_TYPES_LOG2, uiSymbol ); //sao_eo_class_luma or sao_eo_class_chroma
             ctbParam.typeIdc += uiSymbol;
-        }
-        else
-        {
-            ctbParam.typeIdc = saoBlkParam[SAO_Cb].typeIdc;
-        }
+          }
+          else
+          {
+            ctbParam.typeIdc = saoBlkParam[firstCompOfChType].typeIdc;
+          }
           ctbParam.offset[SAO_CLASS_EO_FULL_VALLEY] = offset[0];
           ctbParam.offset[SAO_CLASS_EO_HALF_VALLEY] = offset[1];
@@ -1979,5 +2348,5 @@
           ctbParam.offset[SAO_CLASS_EO_HALF_PEAK  ] = -offset[2];
           ctbParam.offset[SAO_CLASS_EO_FULL_PEAK  ] = -offset[3];
-      }
+        }
       }
     }
@@ -1990,26 +2359,63 @@
  \param pSrc Contexts to be copied.
  */
-Void TDecSbac::xCopyContextsFrom( TDecSbac* pSrc )
+Void TDecSbac::xCopyContextsFrom( const TDecSbac* pSrc )
 {
   memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
-}
-
-Void TDecSbac::xCopyFrom( TDecSbac* pSrc )
+  memcpy(m_golombRiceAdaptationStatistics, pSrc->m_golombRiceAdaptationStatistics, (sizeof(UInt) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS));
+}
+
+Void TDecSbac::xCopyFrom( const TDecSbac* pSrc )
 {
   m_pcTDecBinIf->copyState( pSrc->m_pcTDecBinIf );
-
-  m_uiLastQp           = pSrc->m_uiLastQp;
   xCopyContextsFrom( pSrc );
-
-}
-
-Void TDecSbac::load ( TDecSbac* pScr )
-{
-  xCopyFrom(pScr);
-}
-
-Void TDecSbac::loadContexts ( TDecSbac* pScr )
-{
-  xCopyContextsFrom(pScr);
+}
+
+Void TDecSbac::load ( const TDecSbac* pSrc )
+{
+  xCopyFrom(pSrc);
+}
+
+Void TDecSbac::loadContexts ( const TDecSbac* pSrc )
+{
+  xCopyContextsFrom(pSrc);
+}
+
+/** Performs CABAC decoding of the explicit RDPCM mode
+ * \param rTu current TU data structure
+ * \param compID component identifier
+ */
+Void TDecSbac::parseExplicitRdpcmMode( TComTU &rTu, ComponentID compID )
+{
+  TComDataCU* cu = rTu.getCU();
+  const UInt absPartIdx=rTu.GetAbsPartIdxTU(compID);
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt tuHeight = g_aucConvertToBit[rect.height];
+  const UInt tuWidth  = g_aucConvertToBit[rect.width];
+  UInt code = 0;
+
+  assert(tuHeight == tuWidth);
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__EXPLICIT_RDPCM_BITS, g_aucConvertToBit[cu->getSlice()->getSPS()->getMaxCUWidth()>>rTu.GetTransformDepthTotal()]+2);
+#endif
+
+  m_pcTDecBinIf->decodeBin(code, m_explicitRdpcmFlagSCModel.get (0, toChannelType(compID), 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype));
+
+  if(code == 0)
+  {
+    cu->setExplicitRdpcmModePartRange( RDPCM_OFF, compID, absPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBin(code, m_explicitRdpcmDirSCModel.get (0, toChannelType(compID), 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype));
+    if(code == 0)
+    {
+      cu->setExplicitRdpcmModePartRange( RDPCM_HOR, compID, absPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+    }
+    else
+    {
+      cu->setExplicitRdpcmModePartRange( RDPCM_VER, compID, absPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+    }
+  }
 }
 
@@ -2154,4 +2560,3 @@
 
 
-
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSbac.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSbac.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -58,4 +58,6 @@
 // ====================================================================================================================
 
+class SEImessages;
+
 /// SBAC decoder class
 class TDecSbac : public TDecEntropyIf
@@ -64,12 +66,12 @@
   TDecSbac();
   virtual ~TDecSbac();
-  
+
   Void  init                      ( TDecBinIf* p )    { m_pcTDecBinIf = p; }
   Void  uninit                    (              )    { m_pcTDecBinIf = 0; }
-  
-  Void load                          ( TDecSbac* pScr );
-  Void loadContexts                  ( TDecSbac* pScr );
-  Void xCopyFrom           ( TDecSbac* pSrc );
-  Void xCopyContextsFrom       ( TDecSbac* pSrc );
+
+  Void load                       ( const TDecSbac* pSrc );
+  Void loadContexts               ( const TDecSbac* pSrc );
+  Void xCopyFrom                  ( const TDecSbac* pSrc );
+  Void xCopyContextsFrom          ( const TDecSbac* pSrc );
 
   Void  resetEntropy (TComSlice* pSlice );
@@ -82,23 +84,27 @@
   Void  parsePPS                  ( TComPPS* /*pcPPS*/ ) {}
 #endif
-
-#if H_MV
-  Void  parseSliceHeader          ( TComSlice*& /*rpcSlice*/, ParameterSetManagerDecoder* /*parameterSetManager*/, Int targetOlsIdx ) {}
-#else
-  Void  parseSliceHeader          ( TComSlice*& /*rpcSlice*/, ParameterSetManagerDecoder* /*parameterSetManager*/ ) {}
-#endif
+  Void  parseSliceHeader          ( TComSlice* /*pcSlice*/, ParameterSetManager* /*parameterSetManager*/, const Int /*prevTid0POC*/) {}
   Void  parseTerminatingBit       ( UInt& ruiBit );
+  Void  parseRemainingBytes       ( Bool noTrailingBytesExpected);
   Void  parseMVPIdx               ( Int& riMVPIdx          );
   Void  parseSaoMaxUvlc           ( UInt& val, UInt maxSymbol );
-  Void  parseSaoMerge         ( UInt&  ruiVal   );
+  Void  parseSaoMerge             ( UInt&  ruiVal   );
   Void  parseSaoTypeIdx           ( UInt&  ruiVal  );
   Void  parseSaoUflc              ( UInt uiLength, UInt& ruiVal     );
-  Void parseSAOBlkParam (SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail);
-  Void parseSaoSign(UInt& val);
+  Void parseSAOBlkParam           (SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, const BitDepths &bitDepths);
+  Void parseSaoSign               (UInt& val);
+
 private:
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  Void  xReadUnarySymbol    ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, const class TComCodingStatisticsClassType &whichStat );
+  Void  xReadUnaryMaxSymbol ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol, const class TComCodingStatisticsClassType &whichStat );
+  Void  xReadEpExGolomb     ( UInt& ruiSymbol, UInt uiCount, const class TComCodingStatisticsClassType &whichStat );
+  Void  xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange, const class TComCodingStatisticsClassType &whichStat );
+#else
   Void  xReadUnarySymbol    ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset );
   Void  xReadUnaryMaxSymbol ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol );
   Void  xReadEpExGolomb     ( UInt& ruiSymbol, UInt uiCount );
-  Void  xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam );
+  Void  xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange );
+#endif
 #if H_3D_DIM
   Void  xReadExGolombLevel   ( UInt& ruiSymbol, ContextModel& rcSCModel  );
@@ -118,10 +124,11 @@
   Void parseDBBPFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
+
 private:
   TComInputBitstream* m_pcBitstream;
   TDecBinIf*        m_pcTDecBinIf;
- 
+
 public:
-  
+
   Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #if H_3D
@@ -140,9 +147,8 @@
   Void parsePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void parsePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
   Void parseIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
   Void parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
 #if H_3D_DIM
   Void parseIntraDepth     ( TComDataCU* pcCU, UInt absPartIdx, UInt depth );
@@ -153,25 +159,25 @@
   Void parseRefFrmIdx     ( TComDataCU* pcCU, Int& riRefFrmIdx, RefPicList eRefList );
   Void parseMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList );
-  
+
+  Void parseCrossComponentPrediction ( class TComTU &rTu, ComponentID compID );
+
   Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
-  Void parseQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void parseQtCbf         ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel );
   Void parseQtRootCbf     ( UInt uiAbsPartIdx, UInt& uiQtRootCbf );
-  
+
   Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+  Void parseChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx, UInt depth );
+
   Void parseIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
 
-  Void parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, TextType eTType, UInt uiScanIdx );
-  Void parseCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
-  Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType);
-
-  Void updateContextTables( SliceType eSliceType, Int iQp );
+  Void parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, ComponentID component, UInt uiScanIdx );
+  Void parseCoeffNxN      ( class TComTU &rTu, ComponentID compID  );
+  Void parseTransformSkipFlags ( class TComTU &rTu, ComponentID component );
 
   Void  parseScalingList ( TComScalingList* /*scalingList*/ ) {}
 
+  Void  parseExplicitRdpcmMode( TComTU &rTu, ComponentID compID );
+
 private:
-  UInt m_uiLastDQpNonZero;
-  UInt m_uiLastQp;
-  
   ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
   Int                  m_numContextModels;
@@ -201,5 +207,5 @@
   ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
   ContextModel3DBuffer m_cCUQtRootCbfSCModel;
-  
+
   ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
   ContextModel3DBuffer m_cCUSigSCModel;
@@ -208,12 +214,17 @@
   ContextModel3DBuffer m_cCUOneSCModel;
   ContextModel3DBuffer m_cCUAbsSCModel;
-  
+
   ContextModel3DBuffer m_cMVPIdxSCModel;
-  
+
   ContextModel3DBuffer m_cSaoMergeSCModel;
   ContextModel3DBuffer m_cSaoTypeIdxSCModel;
   ContextModel3DBuffer m_cTransformSkipSCModel;
   ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
-
+  ContextModel3DBuffer m_explicitRdpcmFlagSCModel;
+  ContextModel3DBuffer m_explicitRdpcmDirSCModel;
+  ContextModel3DBuffer m_cCrossComponentPredictionSCModel;
+
+  ContextModel3DBuffer m_ChromaQpAdjFlagSCModel;
+  ContextModel3DBuffer m_ChromaQpAdjIdcSCModel;
 #if H_3D_DIM
   ContextModel3DBuffer m_cDepthIntraModeSCModel;
@@ -232,4 +243,7 @@
   ContextModel3DBuffer m_cDBBPFlagSCModel;
 #endif
+
+
+  UInt m_golombRiceAdaptationStatistics[RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS];
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -47,27 +47,8 @@
 TDecSlice::TDecSlice()
 {
-  m_pcBufferSbacDecoders = NULL;
-  m_pcBufferBinCABACs    = NULL;
-  m_pcBufferLowLatSbacDecoders = NULL;
-  m_pcBufferLowLatBinCABACs    = NULL;
 }
 
 TDecSlice::~TDecSlice()
 {
-  for (std::vector<TDecSbac*>::iterator i = CTXMem.begin(); i != CTXMem.end(); i++)
-  {
-    delete (*i);
-  }
-  CTXMem.clear();
-}
-
-Void TDecSlice::initCtxMem(  UInt i )                
-{   
-  for (std::vector<TDecSbac*>::iterator j = CTXMem.begin(); j != CTXMem.end(); j++)
-  {
-    delete (*j);
-  }
-  CTXMem.clear(); 
-  CTXMem.resize(i); 
 }
 
@@ -78,24 +59,4 @@
 Void TDecSlice::destroy()
 {
-  if ( m_pcBufferSbacDecoders )
-  {
-    delete[] m_pcBufferSbacDecoders;
-    m_pcBufferSbacDecoders = NULL;
-  }
-  if ( m_pcBufferBinCABACs )
-  {
-    delete[] m_pcBufferBinCABACs;
-    m_pcBufferBinCABACs = NULL;
-  }
-  if ( m_pcBufferLowLatSbacDecoders )
-  {
-    delete[] m_pcBufferLowLatSbacDecoders;
-    m_pcBufferLowLatSbacDecoders = NULL;
-  }
-  if ( m_pcBufferLowLatBinCABACs )
-  {
-    delete[] m_pcBufferLowLatBinCABACs;
-    m_pcBufferLowLatBinCABACs = NULL;
-  }
 }
 
@@ -106,15 +67,24 @@
 }
 
-Void TDecSlice::decompressSlice(TComInputBitstream** ppcSubstreams, TComPic*& rpcPic, TDecSbac* pcSbacDecoder, TDecSbac* pcSbacDecoders)
-{
-  TComDataCU* pcCU;
-  UInt        uiIsLast = 0;
-  Int   iStartCUEncOrder = max(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU(), rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr()/rpcPic->getNumPartInCU());
-  Int   iStartCUAddr = rpcPic->getPicSym()->getCUOrderMap(iStartCUEncOrder);
-
-  // decoder don't need prediction & residual frame buffer
-  rpcPic->setPicYuvPred( 0 );
-  rpcPic->setPicYuvResi( 0 );
-  
+Void TDecSlice::decompressSlice(TComInputBitstream** ppcSubstreams, TComPic* pcPic, TDecSbac* pcSbacDecoder)
+{
+  TComSlice* pcSlice                 = pcPic->getSlice(pcPic->getCurrSliceIdx());
+
+  const Int  startCtuTsAddr          = pcSlice->getSliceSegmentCurStartCtuTsAddr();
+  const Int  startCtuRsAddr          = pcPic->getPicSym()->getCtuTsToRsAddrMap(startCtuTsAddr);
+  const UInt numCtusInFrame          = pcPic->getNumberOfCtusInFrame();
+
+  const UInt frameWidthInCtus        = pcPic->getPicSym()->getFrameWidthInCtus();
+  const Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
+  const Bool wavefrontsEnabled       = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag();
+
+  m_pcEntropyDecoder->setEntropyDecoder ( pcSbacDecoder  );
+  m_pcEntropyDecoder->setBitstream      ( ppcSubstreams[0] );
+  m_pcEntropyDecoder->resetEntropy      (pcSlice);
+
+  // decoder doesn't need prediction & residual frame buffer
+  pcPic->setPicYuvPred( 0 );
+  pcPic->setPicYuvResi( 0 );
+
 #if ENC_DEC_TRACE
   g_bJustDoIt = g_bEncDecTraceEnable;
@@ -122,8 +92,8 @@
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
   DTRACE_CABAC_T( "\tPOC: " );
-  DTRACE_CABAC_V( rpcPic->getPOC() );
+  DTRACE_CABAC_V( pcPic->getPOC() );
 #if H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_T( " Layer: " );
-  DTRACE_CABAC_V( rpcPic->getLayerId() );
+  DTRACE_CABAC_V( pcPic->getLayerId() );
 #endif
   DTRACE_CABAC_T( "\n" );
@@ -133,90 +103,22 @@
 #endif
 
-  UInt uiTilesAcross   = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
-  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
-  Int  iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
-
-  // delete decoders if already allocated in previous slice
-  if (m_pcBufferSbacDecoders)
-  {
-    delete [] m_pcBufferSbacDecoders;
-  }
-  if (m_pcBufferBinCABACs) 
-  {
-    delete [] m_pcBufferBinCABACs;
-  }
-  // allocate new decoders based on tile numbaer
-  m_pcBufferSbacDecoders = new TDecSbac    [uiTilesAcross];  
-  m_pcBufferBinCABACs    = new TDecBinCABAC[uiTilesAcross];
-  for (UInt ui = 0; ui < uiTilesAcross; ui++)
-  {
-    m_pcBufferSbacDecoders[ui].init(&m_pcBufferBinCABACs[ui]);
-  }
-  //save init. state
-  for (UInt ui = 0; ui < uiTilesAcross; ui++)
-  {
-    m_pcBufferSbacDecoders[ui].load(pcSbacDecoder);
-  }
-
-  // free memory if already allocated in previous call
-  if (m_pcBufferLowLatSbacDecoders)
-  {
-    delete [] m_pcBufferLowLatSbacDecoders;
-  }
-  if (m_pcBufferLowLatBinCABACs)
-  {
-    delete [] m_pcBufferLowLatBinCABACs;
-  }
-  m_pcBufferLowLatSbacDecoders = new TDecSbac    [uiTilesAcross];  
-  m_pcBufferLowLatBinCABACs    = new TDecBinCABAC[uiTilesAcross];
-  for (UInt ui = 0; ui < uiTilesAcross; ui++)
-  {
-    m_pcBufferLowLatSbacDecoders[ui].init(&m_pcBufferLowLatBinCABACs[ui]);
-  }
-  //save init. state
-  for (UInt ui = 0; ui < uiTilesAcross; ui++)
-  {
-    m_pcBufferLowLatSbacDecoders[ui].load(pcSbacDecoder);
-  }
-
-  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
-  //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU();
-  UInt uiCol=0, uiLin=0, uiSubStrm=0;
-
-  UInt uiTileCol;
-  UInt uiTileStartLCU;
-  UInt uiTileLCUX;
-  Int iNumSubstreamsPerTile = 1; // if independent.
-  Bool depSliceSegmentsEnabled = rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getDependentSliceSegmentsEnabledFlag();
-  uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr))->getFirstCUAddr();
-  if( depSliceSegmentsEnabled )
-  {
-    if( (!rpcPic->getSlice(rpcPic->getCurrSliceIdx())->isNextSlice()) &&
-       iStartCUAddr != rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr))->getFirstCUAddr())
-    {
-      if(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
-      {
-        uiTileCol = rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1);
-        m_pcBufferSbacDecoders[uiTileCol].loadContexts( CTXMem[1]  );//2.LCU
-        if ( (iStartCUAddr%uiWidthInLCUs+1) >= uiWidthInLCUs  )
-        {
-          uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
-          uiCol     = iStartCUAddr % uiWidthInLCUs;
-          if(uiCol==uiTileLCUX)
-          {
-            CTXMem[0]->loadContexts(pcSbacDecoder);
-          }
-        }
-      }
-      pcSbacDecoder->loadContexts(CTXMem[0] ); //end of depSlice-1
-      pcSbacDecoders[uiSubStrm].loadContexts(pcSbacDecoder);
-    }
-    else
-    {
-      if(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
-      {
-        CTXMem[1]->loadContexts(pcSbacDecoder);
-      }
-      CTXMem[0]->loadContexts(pcSbacDecoder);
+  // The first CTU of the slice is the first coded substream, but the global substream number, as calculated by getSubstreamForCtuAddr may be higher.
+  // This calculates the common offset for all substreams in this slice.
+  const UInt subStreamOffset=pcPic->getSubstreamForCtuAddr(startCtuRsAddr, true, pcSlice);
+
+
+  if (depSliceSegmentsEnabled)
+  {
+    // modify initial contexts with previous slice segment if this is a dependent slice.
+    const UInt startTileIdx=pcPic->getPicSym()->getTileIdxMap(startCtuRsAddr);
+    const TComTile *pCurrentTile=pcPic->getPicSym()->getTComTile(startTileIdx);
+    const UInt firstCtuRsAddrOfTile = pCurrentTile->getFirstCtuRsAddr();
+
+    if( pcSlice->getDependentSliceSegmentFlag() && startCtuRsAddr != firstCtuRsAddrOfTile)
+    {
+      if ( pCurrentTile->getTileWidthInCtus() >= 2 || !wavefrontsEnabled)
+      {
+        pcSbacDecoder->loadContexts(&m_lastSliceSegmentEndContextState);
+      }
     }
   }
@@ -227,91 +129,48 @@
   }
 #endif
-  for( Int iCUAddr = iStartCUAddr; !uiIsLast && iCUAddr < rpcPic->getNumCUsInFrame(); iCUAddr = rpcPic->getPicSym()->xCalculateNxtCUAddr(iCUAddr) )
-  {
-    pcCU = rpcPic->getCU( iCUAddr );
-    pcCU->initCU( rpcPic, iCUAddr );
-    uiTileCol = rpcPic->getPicSym()->getTileIdxMap(iCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
-    uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getFirstCUAddr();
-    uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
-    uiCol     = iCUAddr % uiWidthInLCUs;
-    // The 'line' is now relative to the 1st line in the slice, not the 1st line in the picture.
-    uiLin     = (iCUAddr/uiWidthInLCUs)-(iStartCUAddr/uiWidthInLCUs);
-    // inherit from TR if necessary, select substream to use.
-    if( (pcSlice->getPPS()->getNumSubstreams() > 1) || ( depSliceSegmentsEnabled  && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) ))
-    {
-      // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
-      iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
-      uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(iCUAddr)*iNumSubstreamsPerTile
-                  + uiLin%iNumSubstreamsPerTile;
-      m_pcEntropyDecoder->setBitstream( ppcSubstreams[uiSubStrm] );
-      // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line.
-      if (((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled ) && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()))
-      {
-        // We'll sync if the TR is available.
-        TComDataCU *pcCUUp = pcCU->getCUAbove();
-        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
-        TComDataCU *pcCUTR = NULL;
-        if ( pcCUUp && ((iCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
-        {
-          pcCUTR = rpcPic->getCU( iCUAddr - uiWidthInCU + 1 );
-        }
-        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
-
-        if ( (true/*bEnforceSliceRestriction*/ &&
-             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
-             ((pcCUTR->getSCUAddr()+uiMaxParts-1) < pcSlice->getSliceCurStartCUAddr()) ||
-             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr)))
-             ))
-           )
-        {
-          // TR not available.
-        }
-        else
-        {
-          // TR is available, we use it.
-          pcSbacDecoders[uiSubStrm].loadContexts( &m_pcBufferSbacDecoders[uiTileCol] );
-        }
-      }
-      pcSbacDecoder->load(&pcSbacDecoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to pcSbacDecoders)
-    }
-    else if ( pcSlice->getPPS()->getNumSubstreams() <= 1 )
-    {
-      // Set variables to appropriate values to avoid later code change.
-      iNumSubstreamsPerTile = 1;
-    }
-
-    if ( (iCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getFirstCUAddr()) && // 1st in tile.
-         (iCUAddr!=0) && (iCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())
-         && (iCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr())/rpcPic->getNumPartInCU())
-         ) // !1st in frame && !1st in slice
-    {
-      if (pcSlice->getPPS()->getNumSubstreams() > 1)
-      {
-        // We're crossing into another tile, tiles are independent.
-        // When tiles are independent, we have "substreams per tile".  Each substream has already been terminated, and we no longer
-        // have to perform it here.
-        // For TILES_DECODER, there can be a header at the start of the 1st substream in a tile.  These are read when the substreams
-        // are extracted, not here.
-      }
-      else
-      {
-        SliceType sliceType  = pcSlice->getSliceType();
-        if (pcSlice->getCabacInitFlag())
-        {
-          switch (sliceType)
-          {
-          case P_SLICE:           // change initialization table to B_SLICE intialization
-            sliceType = B_SLICE; 
-            break;
-          case B_SLICE:           // change initialization table to P_SLICE intialization
-            sliceType = P_SLICE; 
-            break;
-          default     :           // should not occur
-            assert(0);
-          }
-        }
-        m_pcEntropyDecoder->updateContextTables( sliceType, pcSlice->getSliceQp() );
-      }
-      
+
+  // for every CTU in the slice segment...
+
+  Bool isLastCtuOfSliceSegment = false;
+  for( UInt ctuTsAddr = startCtuTsAddr; !isLastCtuOfSliceSegment && ctuTsAddr < numCtusInFrame; ctuTsAddr++)
+  {
+    const UInt ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddr);
+    const TComTile &currentTile = *(pcPic->getPicSym()->getTComTile(pcPic->getPicSym()->getTileIdxMap(ctuRsAddr)));
+    const UInt firstCtuRsAddrOfTile = currentTile.getFirstCtuRsAddr();
+    const UInt tileXPosInCtus = firstCtuRsAddrOfTile % frameWidthInCtus;
+    const UInt tileYPosInCtus = firstCtuRsAddrOfTile / frameWidthInCtus;
+    const UInt ctuXPosInCtus  = ctuRsAddr % frameWidthInCtus;
+    const UInt ctuYPosInCtus  = ctuRsAddr / frameWidthInCtus;
+    const UInt uiSubStrm=pcPic->getSubstreamForCtuAddr(ctuRsAddr, true, pcSlice)-subStreamOffset;
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+    pCtu->initCtu( pcPic, ctuRsAddr );
+
+    m_pcEntropyDecoder->setBitstream( ppcSubstreams[uiSubStrm] );
+
+    // set up CABAC contexts' state for this CTU
+    if (ctuRsAddr == firstCtuRsAddrOfTile)
+    {
+      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
+      {
+        m_pcEntropyDecoder->resetEntropy(pcSlice);
+      }
+    }
+    else if (ctuXPosInCtus == tileXPosInCtus && wavefrontsEnabled)
+    {
+      // Synchronize cabac probabilities with upper-right CTU if it's available and at the start of a line.
+      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
+      {
+        m_pcEntropyDecoder->resetEntropy(pcSlice);
+      }
+      TComDataCU *pCtuUp = pCtu->getCtuAbove();
+      if ( pCtuUp && ((ctuRsAddr%frameWidthInCtus+1) < frameWidthInCtus)  )
+      {
+        TComDataCU *pCtuTR = pcPic->getCtu( ctuRsAddr - frameWidthInCtus + 1 );
+        if ( pCtu->CUIsFromSameSliceAndTile(pCtuTR) )
+        {
+          // Top-right is available, so use it.
+          pcSbacDecoder->loadContexts( &m_entropyCodingSyncContextState );
+        }
+      }
     }
 
@@ -321,126 +180,88 @@
 
     if ( pcSlice->getSPS()->getUseSAO() )
-      {
-      SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[iCUAddr];
-      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
-      {
-        Bool sliceEnabled[NUM_SAO_COMPONENTS];
-        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
-        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
-
+    {
+      SAOBlkParam& saoblkParam = (pcPic->getPicSym()->getSAOBlkParam())[ctuRsAddr];
+      Bool bIsSAOSliceEnabled = false;
+      Bool sliceEnabled[MAX_NUM_COMPONENT];
+      for(Int comp=0; comp < MAX_NUM_COMPONENT; comp++)
+      {
+        ComponentID compId=ComponentID(comp);
+        sliceEnabled[compId] = pcSlice->getSaoEnabledFlag(toChannelType(compId)) && (comp < pcPic->getNumberValidComponents());
+        if (sliceEnabled[compId])
+        {
+          bIsSAOSliceEnabled=true;
+        }
+        saoblkParam[compId].modeIdc = SAO_MODE_OFF;
+      }
+      if (bIsSAOSliceEnabled)
+      {
         Bool leftMergeAvail = false;
         Bool aboveMergeAvail= false;
 
         //merge left condition
-        Int rx = (iCUAddr % uiWidthInLCUs);
+        Int rx = (ctuRsAddr % frameWidthInCtus);
         if(rx > 0)
         {
-          leftMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-1);
+          leftMergeAvail = pcPic->getSAOMergeAvailability(ctuRsAddr, ctuRsAddr-1);
         }
         //merge up condition
-        Int ry = (iCUAddr / uiWidthInLCUs);
+        Int ry = (ctuRsAddr / frameWidthInCtus);
         if(ry > 0)
         {
-          aboveMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-uiWidthInLCUs);
-      }
-
-        pcSbacDecoder->parseSAOBlkParam( saoblkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail);
-    }
-      else 
-        {
-        saoblkParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
-        saoblkParam[SAO_Cb].modeIdc = SAO_MODE_OFF;
-        saoblkParam[SAO_Cr].modeIdc = SAO_MODE_OFF;
-      }
-    }
-    m_pcCuDecoder->decodeCU     ( pcCU, uiIsLast );
-    m_pcCuDecoder->decompressCU ( pcCU );
-    
+          aboveMergeAvail = pcPic->getSAOMergeAvailability(ctuRsAddr, ctuRsAddr-frameWidthInCtus);
+        }
+
+        pcSbacDecoder->parseSAOBlkParam( saoblkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail, pcSlice->getSPS()->getBitDepths());
+      }
+    }
+
+    m_pcCuDecoder->decodeCtu     ( pCtu, isLastCtuOfSliceSegment );
+    m_pcCuDecoder->decompressCtu ( pCtu );
+
 #if ENC_DEC_TRACE
     g_bJustDoIt = g_bEncDecTraceDisable;
 #endif
-    pcSbacDecoders[uiSubStrm].load(pcSbacDecoder);
-
-    if ( uiCol == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getRightEdgePosInCU()
-        && pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()
-        && !uiIsLast )
-    {
-      // Parse end_of_substream_one_bit for WPP case
+
+    //Store probabilities of second CTU in line into buffer
+    if ( ctuXPosInCtus == tileXPosInCtus+1 && wavefrontsEnabled)
+    {
+      m_entropyCodingSyncContextState.loadContexts( pcSbacDecoder );
+    }
+
+    if (isLastCtuOfSliceSegment)
+    {
+#if DECODER_CHECK_SUBSTREAM_AND_SLICE_TRAILING_BYTES
+      pcSbacDecoder->parseRemainingBytes(false);
+#endif
+      if(!pcSlice->getDependentSliceSegmentFlag())
+      {
+        pcSlice->setSliceCurEndCtuTsAddr( ctuTsAddr+1 );
+      }
+      pcSlice->setSliceSegmentCurEndCtuTsAddr( ctuTsAddr+1 );
+    }
+    else if (  ctuXPosInCtus + 1 == tileXPosInCtus + currentTile.getTileWidthInCtus() &&
+             ( ctuYPosInCtus + 1 == tileYPosInCtus + currentTile.getTileHeightInCtus() || wavefrontsEnabled)
+            )
+    {
+      // The sub-stream/stream should be terminated after this CTU.
+      // (end of slice-segment, end of tile, end of wavefront-CTU-row)
       UInt binVal;
       pcSbacDecoder->parseTerminatingBit( binVal );
       assert( binVal );
-    }
-
-    //Store probabilities of second LCU in line into buffer
-    if ( (uiCol == uiTileLCUX+1)&& (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) )
-    {
-      m_pcBufferSbacDecoders[uiTileCol].loadContexts( &pcSbacDecoders[uiSubStrm] );
-    }
-    if( uiIsLast && depSliceSegmentsEnabled )
-    {
-      if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
-       {
-         CTXMem[1]->loadContexts( &m_pcBufferSbacDecoders[uiTileCol] );//ctx 2.LCU
-       }
-      CTXMem[0]->loadContexts( pcSbacDecoder );//ctx end of dep.slice
-      return;
-    }
-  }
-}
-
-ParameterSetManagerDecoder::ParameterSetManagerDecoder()
-: m_vpsBuffer(MAX_NUM_VPS)
-, m_spsBuffer(MAX_NUM_SPS)
-, m_ppsBuffer(MAX_NUM_PPS)
-{
-}
-
-ParameterSetManagerDecoder::~ParameterSetManagerDecoder()
-{
-
-}
-
-TComVPS* ParameterSetManagerDecoder::getPrefetchedVPS  (Int vpsId)
-{
-  if (m_vpsBuffer.getPS(vpsId) != NULL )
-  {
-    return m_vpsBuffer.getPS(vpsId);
-  }
-  else
-  {
-    return getVPS(vpsId);
-  }
-}
-
-
-TComSPS* ParameterSetManagerDecoder::getPrefetchedSPS  (Int spsId)
-{
-  if (m_spsBuffer.getPS(spsId) != NULL )
-  {
-    return m_spsBuffer.getPS(spsId);
-  }
-  else
-  {
-    return getSPS(spsId);
-  }
-}
-
-TComPPS* ParameterSetManagerDecoder::getPrefetchedPPS  (Int ppsId)
-{
-  if (m_ppsBuffer.getPS(ppsId) != NULL )
-  {
-    return m_ppsBuffer.getPS(ppsId);
-  }
-  else
-  {
-    return getPPS(ppsId);
-  }
-}
-
-Void     ParameterSetManagerDecoder::applyPrefetchedPS()
-{
-  m_vpsMap.mergePSList(m_vpsBuffer);
-  m_ppsMap.mergePSList(m_ppsBuffer);
-  m_spsMap.mergePSList(m_spsBuffer);
+#if DECODER_CHECK_SUBSTREAM_AND_SLICE_TRAILING_BYTES
+      pcSbacDecoder->parseRemainingBytes(true);
+#endif
+    }
+
+  }
+
+  assert(isLastCtuOfSliceSegment == true);
+
+
+  if( depSliceSegmentsEnabled )
+  {
+    m_lastSliceSegmentEndContextState.loadContexts( pcSbacDecoder );//ctx end of dep.slice
+  }
+
 }
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSlice.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecSlice.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -66,44 +66,17 @@
   TDecCu*         m_pcCuDecoder;
 
-  TDecSbac*       m_pcBufferSbacDecoders;   ///< line to store temporary contexts, one per column of tiles.
-  TDecBinCABAC*   m_pcBufferBinCABACs;
-  TDecSbac*       m_pcBufferLowLatSbacDecoders;   ///< dependent tiles: line to store temporary contexts, one per column of tiles.
-  TDecBinCABAC*   m_pcBufferLowLatBinCABACs;
-  std::vector<TDecSbac*> CTXMem;
-  
+  TDecSbac        m_lastSliceSegmentEndContextState;    ///< context storage for state at the end of the previous slice-segment (used for dependent slices only).
+  TDecSbac        m_entropyCodingSyncContextState;      ///< context storate for state of contexts at the wavefront/WPP/entropy-coding-sync second CTU of tile-row
+
 public:
   TDecSlice();
   virtual ~TDecSlice();
-  
+
   Void  init              ( TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder );
   Void  create            ();
   Void  destroy           ();
-  
-  Void  decompressSlice   ( TComInputBitstream** ppcSubstreams,   TComPic*& rpcPic, TDecSbac* pcSbacDecoder, TDecSbac* pcSbacDecoders );
-  Void      initCtxMem(  UInt i );
-  Void      setCtxMem( TDecSbac* sb, Int b )   { CTXMem[b] = sb; }
-  Int       getCtxMemSize( )                   { return (Int)CTXMem.size(); }
+
+  Void  decompressSlice   ( TComInputBitstream** ppcSubstreams,   TComPic* pcPic, TDecSbac* pcSbacDecoder );
 };
-
-
-class ParameterSetManagerDecoder:public ParameterSetManager
-{
-public:
-  ParameterSetManagerDecoder();
-  virtual ~ParameterSetManagerDecoder();
-  Void     storePrefetchedVPS(TComVPS *vps)  { m_vpsBuffer.storePS( vps->getVPSId(), vps); };
-  TComVPS* getPrefetchedVPS  (Int vpsId);
-  Void     storePrefetchedSPS(TComSPS *sps)  { m_spsBuffer.storePS( sps->getSPSId(), sps); };
-  TComSPS* getPrefetchedSPS  (Int spsId);
-  Void     storePrefetchedPPS(TComPPS *pps)  { m_ppsBuffer.storePS( pps->getPPSId(), pps); };
-  TComPPS* getPrefetchedPPS  (Int ppsId);
-  Void     applyPrefetchedPS();
-
-private:
-  ParameterSetMap<TComVPS> m_vpsBuffer;
-  ParameterSetMap<TComSPS> m_spsBuffer; 
-  ParameterSetMap<TComPPS> m_ppsBuffer;
-};
-
 
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,12 +38,12 @@
 #include "NALread.h"
 #include "TDecTop.h"
-
-#if H_MV
-ParameterSetManagerDecoder TDecTop::m_parameterSetManagerDecoder;
-#endif
+#if NH_MV
+ParameterSetManager TDecTop::m_parameterSetManager;
+#endif
+
 //! \ingroup TLibDecoder
 //! \{
 
-#if H_3D
+#if NH_3D
 CamParsCollector::CamParsCollector()
 : m_bInitialized( false )
@@ -81,11 +81,10 @@
 
 Void
-CamParsCollector::init( FILE* pCodedScaleOffsetFile, TComVPS* vps)
+CamParsCollector::init( const TComVPS* vps)
 {
   assert( !isInitialized() ); // Only one initialization currently supported
   m_bInitialized            = true;
   m_vps                     = vps; 
-  m_bCamParsVaryOverTime    = false; 
-  m_pCodedScaleOffsetFile   = pCodedScaleOffsetFile;
+  m_bCamParsVaryOverTime    = false;   
   m_lastPoc                 = -1;   
   m_firstReceivedPoc        = -2; 
@@ -348,47 +347,75 @@
 #endif
 
+
 TDecTop::TDecTop()
-{
-  m_pcPic = 0;
-  m_iMaxRefPicNum = 0;
+  : m_iMaxRefPicNum(0)
+  , m_associatedIRAPType(NAL_UNIT_INVALID)
+  , m_pocCRA(0)
+  , m_pocRandomAccess(MAX_INT)
+  , m_cListPic()
+#if !NH_MV
+  , m_parameterSetManager()
+#endif
+  , m_apcSlicePilot(NULL)
+  , m_SEIs()
+  , m_cPrediction()
+  , m_cTrQuant()
+  , m_cGopDecoder()
+  , m_cSliceDecoder()
+  , m_cCuDecoder()
+  , m_cEntropyDecoder()
+  , m_cCavlcDecoder()
+  , m_cSbacDecoder()
+  , m_cBinCABAC()
+  , m_seiReader()
+  , m_cLoopFilter()
+  , m_cSAO()
+  , m_pcPic(NULL)
+  , m_prevPOC(MAX_INT)
+  , m_prevTid0POC(0)
+  , m_bFirstSliceInPicture(true)
+  , m_bFirstSliceInSequence(true)
+  , m_prevSliceSkipped(false)
+  , m_skippedPOC(0)
+  , m_bFirstSliceInBitstream(true)
+  , m_lastPOCNoOutputPriorPics(-1)
+  , m_isNoOutputPriorPics(false)
+  , m_craNoRaslOutputFlag(false)
+#if O0043_BEST_EFFORT_DECODING
+  , m_forceDecodeBitDepth(8)
+#endif
+  , m_pDecodedSEIOutputStream(NULL)
+  , m_warningMessageSkipPicture(false)
+  , m_prefixSEINALUs()
+{
 #if ENC_DEC_TRACE
-#if H_MV
+#if NH_MV
   if ( g_hTrace == NULL )
   {
 #endif
-  g_hTrace = fopen( "TraceDec.txt", "wb" );
+  if (g_hTrace == NULL)
+  {
+    g_hTrace = fopen( "TraceDec.txt", "wb" );
+  }
   g_bJustDoIt = g_bEncDecTraceDisable;
   g_nSymbolCounter = 0;
-#if H_MV
-  }
-#endif
-#endif
-  m_associatedIRAPType = NAL_UNIT_INVALID;
-  m_pocCRA = 0;
-  m_pocRandomAccess = MAX_INT;  
-  m_prevPOC                = MAX_INT;
-  m_bFirstSliceInPicture    = true;
-  m_bFirstSliceInSequence   = true;
-  m_prevSliceSkipped = false;
-  m_skippedPOC = 0;
-#if SETTING_NO_OUT_PIC_PRIOR
-  m_bFirstSliceInBitstream  = true;
-  m_lastPOCNoOutputPriorPics = -1;
-  m_craNoRaslOutputFlag = false;
-  m_isNoOutputPriorPics = false;
-#endif
-#if H_MV
+#if NH_MV
+  }
+#endif
+#endif
+#if NH_MV
   m_isLastNALWasEos = false;
   m_layerId = 0;
   m_viewId = 0;
-#if H_3D
+#if NH_3D
   m_viewIndex = 0; 
   m_isDepth = false;
   m_pcCamParsCollector = 0;
 #endif
-#if H_MV
-  m_targetOptLayerSetIdx = -1; 
-#endif
-#endif
+#if NH_MV
+  m_targetOlsIdx = -1; 
+#endif
+#endif
+
 }
 
@@ -396,6 +423,14 @@
 {
 #if ENC_DEC_TRACE
-  fclose( g_hTrace );
-#endif
+  if (g_hTrace != stdout)
+  {
+    fclose( g_hTrace );
+  }
+#endif
+  while (!m_prefixSEINALUs.empty())
+  {
+    delete m_prefixSEINALUs.front();
+    m_prefixSEINALUs.pop_front();
+  }
 }
 
@@ -410,8 +445,8 @@
 {
   m_cGopDecoder.destroy();
-  
+
   delete m_apcSlicePilot;
   m_apcSlicePilot = NULL;
-  
+
   m_cSliceDecoder.destroy();
 }
@@ -420,11 +455,11 @@
 {
   // initialize ROM
-#if !H_MV
+#if !NH_MV
   initROM();
 #endif
-#if H_3D
+#if NH_MV
   m_cCavlcDecoder.setDecTop( this ); 
 #endif
-  m_cGopDecoder.init( &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cSAO );
+  m_cGopDecoder.init( &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cSAO);
   m_cSliceDecoder.init( &m_cEntropyDecoder, &m_cCuDecoder );
   m_cEntropyDecoder.init(&m_cPrediction);
@@ -435,26 +470,26 @@
   TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
   Int iSize = Int( m_cListPic.size() );
-  
+
   for (Int i = 0; i < iSize; i++ )
   {
     TComPic* pcPic = *(iterPic++);
-#if H_MV
+#if NH_MV
     if( pcPic )
     {
 #endif
     pcPic->destroy();
-    
+
     delete pcPic;
     pcPic = NULL;
-#if H_MV
-    }
-#endif
-  }
-  
+#if NH_MV
+    }
+#endif
+  }
+
   m_cSAO.destroy();
-  
+
   m_cLoopFilter.        destroy();
-  
-#if !H_MV
+
+#if !NH_MV
   // destroy ROM
   destroyROM();
@@ -462,31 +497,16 @@
 }
 
-Void TDecTop::xGetNewPicBuffer ( TComSlice* pcSlice, TComPic*& rpcPic )
-{
-  Int  numReorderPics[MAX_TLAYER];
-  Window &conformanceWindow = pcSlice->getSPS()->getConformanceWindow();
-  Window defaultDisplayWindow = pcSlice->getSPS()->getVuiParametersPresentFlag() ? pcSlice->getSPS()->getVuiParameters()->getDefaultDisplayWindow() : Window();
-
-#if H_MV
-    assert( conformanceWindow   .getScaledFlag() ); 
-    assert( defaultDisplayWindow.getScaledFlag() );
-#endif
-  for( Int temporalLayer=0; temporalLayer < MAX_TLAYER; temporalLayer++) 
-  {
-#if H_MV
-    numReorderPics[temporalLayer] = ( getLayerId() == 0 ) ? pcSlice->getSPS()->getNumReorderPics(temporalLayer) : pcSlice->getVPS()->getNumReorderPics(temporalLayer);
-#else
-    numReorderPics[temporalLayer] = pcSlice->getSPS()->getNumReorderPics(temporalLayer);
-#endif
-  }
-#if H_MV
+Void TDecTop::xGetNewPicBuffer ( const TComSPS &sps, const TComPPS &pps, TComPic*& rpcPic, const UInt temporalLayer )
+{
+#if NH_MV
   if ( getLayerId() == 0 )
   {  
-    m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());
+    m_iMaxRefPicNum = sps.getMaxDecPicBuffering(temporalLayer);     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
   }
   else
   {
-    m_iMaxRefPicNum = pcSlice->getVPS()->getMaxDecPicBuffering(pcSlice->getTLayer());
-#if H_MV_HLS7_GEN
+    //GTCIC
+    //m_iMaxRefPicNum = pcSlice->getVPS()->getMaxDecPicBuffering(pcSlice->getTLayer());    
+#if H_MV_HLS7_GEN 
     TComVPS* vps         = pcSlice->getVPS();
     TComDpbSize* dpbSize = vps->getDpbSize(); 
@@ -498,17 +518,17 @@
   }
 #else
-  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+  m_iMaxRefPicNum = sps.getMaxDecPicBuffering(temporalLayer);     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
 #endif
   if (m_cListPic.size() < (UInt)m_iMaxRefPicNum)
   {
     rpcPic = new TComPic();
-    
-    rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, 
-                     conformanceWindow, defaultDisplayWindow, numReorderPics, true);
+
+    rpcPic->create ( sps, pps, true);
+
     m_cListPic.pushBack( rpcPic );
-    
+
     return;
   }
-  
+
   Bool bBufferIsAvailable = false;
   TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
@@ -519,5 +539,5 @@
     {
       rpcPic->setOutputMark(false);
-#if H_MV
+#if NH_MV
       rpcPic->setPicOutputFlag(false); 
 #endif
@@ -529,5 +549,5 @@
     {
       rpcPic->setOutputMark(false);
-#if H_MV
+#if NH_MV
       rpcPic->setPicOutputFlag(false); 
 #endif
@@ -538,5 +558,5 @@
     }
   }
-  
+
   if ( !bBufferIsAvailable )
   {
@@ -547,9 +567,7 @@
   }
   rpcPic->destroy();
-  rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth,
-                   conformanceWindow, defaultDisplayWindow, numReorderPics, true);
-}
-
-#if H_MV
+  rpcPic->create ( sps, pps, true);
+}
+#if NH_MV
 Void TDecTop::endPicDecoding(Int& poc, TComList<TComPic*>*& rpcListPic, std::vector<Int>& targetDecLayerIdSet )
 #else
@@ -562,6 +580,6 @@
     return;
   }
-  
-  TComPic*&   pcPic         = m_pcPic;
+
+  TComPic*   pcPic         = m_pcPic;
 
   // Execute Deblock + Cleanup
@@ -571,7 +589,7 @@
   TComSlice::sortPicList( m_cListPic ); // sorting for application output
   poc                 = pcPic->getSlice(m_uiSliceIdx-1)->getPOC();
-  rpcListPic          = &m_cListPic;  
-  m_cCuDecoder.destroy();        
-#if H_MV 
+  rpcListPic          = &m_cListPic;
+  m_cCuDecoder.destroy();
+#if NH_MV 
   TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer0, m_refPicSetInterLayer1 );  
   TComSlice::markCurrPic( pcPic ); 
@@ -582,18 +600,20 @@
 }
 
-#if SETTING_NO_OUT_PIC_PRIOR
-Void TDecTop::checkNoOutputPriorPics (TComList<TComPic*>*& rpcListPic)
-{
-  if (!rpcListPic || !m_isNoOutputPriorPics) return;
-
-  TComList<TComPic*>::iterator  iterPic   = rpcListPic->begin();
-
-  while (iterPic != rpcListPic->end())
-  {
-    TComPic*& pcPicTmp = *(iterPic++);
+Void TDecTop::checkNoOutputPriorPics (TComList<TComPic*>* pcListPic)
+{
+  if (!pcListPic || !m_isNoOutputPriorPics)
+  {
+    return;
+  }
+
+  TComList<TComPic*>::iterator  iterPic   = pcListPic->begin();
+
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPicTmp = *(iterPic++);
     if (m_lastPOCNoOutputPriorPics != pcPicTmp->getPOC())
     {
       pcPicTmp->setOutputMark(false);
-#if H_MV
+#if NH_MV
       pcPicTmp->setPicOutputFlag(false); 
 #endif
@@ -601,19 +621,12 @@
   }
 }
-#endif
-
-Void TDecTop::xCreateLostPicture(Int iLostPoc) 
+
+Void TDecTop::xCreateLostPicture(Int iLostPoc)
 {
   printf("\ninserting lost poc : %d\n",iLostPoc);
-  TComSlice cFillSlice;
-  cFillSlice.setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
-  cFillSlice.setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
-  cFillSlice.initSlice();
   TComPic *cFillPic;
-  xGetNewPicBuffer(&cFillSlice,cFillPic);
-  cFillPic->getSlice(0)->setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
-  cFillPic->getSlice(0)->setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+  xGetNewPicBuffer(*(m_parameterSetManager.getFirstSPS()), *(m_parameterSetManager.getFirstPPS()), cFillPic, 0);
   cFillPic->getSlice(0)->initSlice();
-  
+
   TComList<TComPic*>::iterator iterPic = m_cListPic.begin();
   Int closestPoc = 1000000;
@@ -638,10 +651,11 @@
   }
   cFillPic->setCurrSliceIdx(0);
-  for(Int i=0; i<cFillPic->getNumCUsInFrame(); i++) 
-  {
-    cFillPic->getCU(i)->initCU(cFillPic,i);
+  for(Int ctuRsAddr=0; ctuRsAddr<cFillPic->getNumberOfCtusInFrame(); ctuRsAddr++)
+  {
+    cFillPic->getCtu(ctuRsAddr)->initCtu(cFillPic, ctuRsAddr);
   }
   cFillPic->getSlice(0)->setReferenced(true);
   cFillPic->getSlice(0)->setPOC(iLostPoc);
+  xUpdatePreviousTid0POC(cFillPic->getSlice(0));
   cFillPic->setReconMark(true);
   cFillPic->setOutputMark(true);
@@ -655,26 +669,27 @@
 Void TDecTop::xActivateParameterSets()
 {
-  m_parameterSetManagerDecoder.applyPrefetchedPS();
-  
-  TComPPS *pps = m_parameterSetManagerDecoder.getPPS(m_apcSlicePilot->getPPSId());
-  assert (pps != 0);
-
-  TComSPS *sps = m_parameterSetManagerDecoder.getSPS(pps->getSPSId());
-  assert (sps != 0);
-
-#if H_MV
-  TComVPS* vps = m_parameterSetManagerDecoder.getVPS(sps->getVPSId());
-  assert (vps != 0); 
-  if (!m_parameterSetManagerDecoder.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP(), m_layerId ) )
+  if (m_bFirstSliceInPicture)
+  {
+    const TComPPS *pps = m_parameterSetManager.getPPS(m_apcSlicePilot->getPPSId()); // this is a temporary PPS object. Do not store this value
+    assert (pps != 0);
+
+    const TComSPS *sps = m_parameterSetManager.getSPS(pps->getSPSId());             // this is a temporary SPS object. Do not store this value
+    assert (sps != 0);
+
+    m_parameterSetManager.clearSPSChangedFlag(sps->getSPSId());
+    m_parameterSetManager.clearPPSChangedFlag(pps->getPPSId());
+#if NH_MV
+    const TComVPS* vps = m_parameterSetManager.getVPS(sps->getVPSId());
+    assert (vps != 0); 
+    if (!m_parameterSetManager.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP(), m_layerId ) )
 #else
-  if (false == m_parameterSetManagerDecoder.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP()))
-#endif
-  {
-    printf ("Parameter set activation failed!");
-    assert (0);
-  }
-
-#if H_MV
-  sps->inferSpsMaxDecPicBufferingMinus1( vps, m_targetOptLayerSetIdx, getLayerId(), false ); 
+    if (false == m_parameterSetManager.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP()))
+#endif
+    {
+      printf ("Parameter set activation failed!");
+      assert (0);
+    }
+
+#if NH_MV
   // When the value of vps_num_rep_formats_minus1 in the active VPS is equal to 0
   if ( vps->getVpsNumRepFormatsMinus1() == 0 )
@@ -684,9 +699,4 @@
   }
   sps->checkRpsMaxNumPics( vps, getLayerId() ); 
-
-  if( sps->getLayerId() != 0 )
-  {
-    sps->inferSpsMaxSubLayersMinus1( true, vps ); 
-  }
 
   // It is a requirement of bitstream conformance that, when the SPS is referred to by 
@@ -698,84 +708,172 @@
     assert( sps->getMultiLayerExtSpsFlag() == 0 ); 
   }
-
-  if( sps->getMultiLayerExtSpsFlag() )
-  {
-    sps->setTemporalIdNestingFlag( (sps->getMaxTLayers() > 1) ? vps->getTemporalNestingFlag() : true );
-  }
-#endif
-
-  if( pps->getDependentSliceSegmentsEnabledFlag() )
-  {
-    Int NumCtx = pps->getEntropyCodingSyncEnabledFlag()?2:1;
-
-    if (m_cSliceDecoder.getCtxMemSize() != NumCtx)
-    {
-      m_cSliceDecoder.initCtxMem(NumCtx);
-      for ( UInt st = 0; st < NumCtx; st++ )
-      {
-        TDecSbac* ctx = NULL;
-        ctx = new TDecSbac;
-        ctx->init( &m_cBinCABAC );
-        m_cSliceDecoder.setCtxMem( ctx, st );
-      }
-    }
-  }
-
-  m_apcSlicePilot->setPPS(pps);
-  m_apcSlicePilot->setSPS(sps);
-#if H_MV
-  m_apcSlicePilot->setVPS(vps);  
-  // The nuh_layer_id value of the NAL unit containing the PPS that is activated for a layer layerA with nuh_layer_id equal to nuhLayerIdA shall be equal to 0, or nuhLayerIdA, or the nuh_layer_id of a direct or indirect reference layer of layerA.
-  assert( pps->getLayerId() == m_layerId || pps->getLayerId( ) == 0 || vps->getDependencyFlag( m_layerId, pps->getLayerId() ) );   
-  // The nuh_layer_id value of the NAL unit containing the SPS that is activated for a layer layerA with nuh_layer_id equal to nuhLayerIdA shall be equal to 0, or nuhLayerIdA, or the nuh_layer_id of a direct or indirect reference layer of layerA.
-  assert( sps->getLayerId() == m_layerId || sps->getLayerId( ) == 0 || vps->getDependencyFlag( m_layerId, sps->getLayerId() ) );
-  sps->inferRepFormat  ( vps , m_layerId ); 
-  sps->inferScalingList( m_parameterSetManagerDecoder.getActiveSPS( sps->getSpsScalingListRefLayerId() ) ); 
-
-#endif
-  pps->setSPS(sps);
-  pps->setNumSubstreams(pps->getEntropyCodingSyncEnabledFlag() ? ((sps->getPicHeightInLumaSamples() + sps->getMaxCUHeight() - 1) / sps->getMaxCUHeight()) * (pps->getNumTileColumnsMinus1() + 1) : 1);
-  pps->setMinCuDQPSize( sps->getMaxCUWidth() >> ( pps->getMaxCuDQPDepth()) );
-
-  g_bitDepthY     = sps->getBitDepthY();
-  g_bitDepthC     = sps->getBitDepthC();
-  g_uiMaxCUWidth  = sps->getMaxCUWidth();
-  g_uiMaxCUHeight = sps->getMaxCUHeight();
-  g_uiMaxCUDepth  = sps->getMaxCUDepth();
-  g_uiAddCUDepth  = max (0, sps->getLog2MinCodingBlockSize() - (Int)sps->getQuadtreeTULog2MinSize() );
-
-  for (Int i = 0; i < sps->getLog2DiffMaxMinCodingBlockSize(); i++)
-  {
-    sps->setAMPAcc( i, sps->getUseAMP() );
-  }
-
-  for (Int i = sps->getLog2DiffMaxMinCodingBlockSize(); i < sps->getMaxCUDepth(); i++)
-  {
-    sps->setAMPAcc( i, 0 );
-  }
-
-  m_cSAO.destroy();
-  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
-  m_cLoopFilter.create( sps->getMaxCUDepth() );
-}
-
-#if H_MV
+#endif
+
+    xParsePrefixSEImessages();
+
+#if RExt__HIGH_BIT_DEPTH_SUPPORT==0
+    if (sps->getSpsRangeExtension().getExtendedPrecisionProcessingFlag() || sps->getBitDepth(CHANNEL_TYPE_LUMA)>12 || sps->getBitDepth(CHANNEL_TYPE_CHROMA)>12 )
+    {
+      printf("High bit depth support must be enabled at compile-time in order to decode this bitstream\n");
+      assert (0);
+      exit(1);
+    }
+#endif
+
+    // NOTE: globals were set up here originally. You can now use:
+    // g_uiMaxCUDepth = sps->getMaxTotalCUDepth();
+    // g_uiAddCUDepth = sps->getMaxTotalCUDepth() - sps->getLog2DiffMaxMinCodingBlockSize()
+
+    //  Get a new picture buffer. This will also set up m_pcPic, and therefore give us a SPS and PPS pointer that we can use.
+    xGetNewPicBuffer (*(sps), *(pps), m_pcPic, m_apcSlicePilot->getTLayer());
+    m_apcSlicePilot->applyReferencePictureSet(m_cListPic, m_apcSlicePilot->getRPS());
+#if NH_MV
+    m_apcSlicePilot->createInterLayerReferencePictureSet( m_ivPicLists, m_refPicSetInterLayer0, m_refPicSetInterLayer1 ); 
+#endif
+
+    // make the slice-pilot a real slice, and set up the slice-pilot for the next slice
+    assert(m_pcPic->getNumAllocatedSlice() == (m_uiSliceIdx + 1));
+    m_apcSlicePilot = m_pcPic->getPicSym()->swapSliceObject(m_apcSlicePilot, m_uiSliceIdx);
+
+    // we now have a real slice:
+    TComSlice *pSlice = m_pcPic->getSlice(m_uiSliceIdx);
+
+    // Update the PPS and SPS pointers with the ones of the picture.
+    pps=pSlice->getPPS();
+    sps=pSlice->getSPS();
+
+#if NH_MV
+    vps=pSlice->getVPS();  
+    // The nuh_layer_id value of the NAL unit containing the PPS that is activated for a layer layerA with nuh_layer_id equal to nuhLayerIdA shall be equal to 0, or nuhLayerIdA, or the nuh_layer_id of a direct or indirect reference layer of layerA.
+    assert( pps->getLayerId() == m_layerId || pps->getLayerId( ) == 0 || vps->getDependencyFlag( m_layerId, pps->getLayerId() ) );   
+    // The nuh_layer_id value of the NAL unit containing the SPS that is activated for a layer layerA with nuh_layer_id equal to nuhLayerIdA shall be equal to 0, or nuhLayerIdA, or the nuh_layer_id of a direct or indirect reference layer of layerA.
+    assert( sps->getLayerId() == m_layerId || sps->getLayerId( ) == 0 || vps->getDependencyFlag( m_layerId, sps->getLayerId() ) );
+#endif
+
+#if NH_3D
+    if ( !m_pcCamParsCollector->isInitialized() )
+    {
+      m_pcCamParsCollector->init( vps );
+    }
+#endif
+    // Initialise the various objects for the new set of settings
+    m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getChromaFormatIdc(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxTotalCUDepth(), pps->getPpsRangeExtension().getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA), pps->getPpsRangeExtension().getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA) );
+    m_cLoopFilter.create( sps->getMaxTotalCUDepth() );
+    m_cPrediction.initTempBuff(sps->getChromaFormatIdc());
+
+
+    Bool isField = false;
+    Bool isTopField = false;
+
+    if(!m_SEIs.empty())
+    {
+      // Check if any new Picture Timing SEI has arrived
+      SEIMessages pictureTimingSEIs = getSeisByType(m_SEIs, SEI::PICTURE_TIMING);
+      if (pictureTimingSEIs.size()>0)
+      {
+        SEIPictureTiming* pictureTiming = (SEIPictureTiming*) *(pictureTimingSEIs.begin());
+        isField    = (pictureTiming->m_picStruct == 1) || (pictureTiming->m_picStruct == 2) || (pictureTiming->m_picStruct == 9) || (pictureTiming->m_picStruct == 10) || (pictureTiming->m_picStruct == 11) || (pictureTiming->m_picStruct == 12);
+        isTopField = (pictureTiming->m_picStruct == 1) || (pictureTiming->m_picStruct == 9) || (pictureTiming->m_picStruct == 11);
+      }
+    }
+
+    //Set Field/Frame coding mode
+    m_pcPic->setField(isField);
+    m_pcPic->setTopField(isTopField);
+
+    // transfer any SEI messages that have been received to the picture
+    m_pcPic->setSEIs(m_SEIs);
+    m_SEIs.clear();
+
+    // Recursive structure
+    m_cCuDecoder.create ( sps->getMaxTotalCUDepth(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getChromaFormatIdc() );
+    m_cCuDecoder.init   ( &m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction );
+    m_cTrQuant.init     ( sps->getMaxTrSize() );
+
+    m_cSliceDecoder.create();
+  }
+  else
+  {
+    // make the slice-pilot a real slice, and set up the slice-pilot for the next slice
+    m_pcPic->allocateNewSlice();
+    assert(m_pcPic->getNumAllocatedSlice() == (m_uiSliceIdx + 1));
+    m_apcSlicePilot = m_pcPic->getPicSym()->swapSliceObject(m_apcSlicePilot, m_uiSliceIdx);
+
+    TComSlice *pSlice = m_pcPic->getSlice(m_uiSliceIdx); // we now have a real slice.
+
+    const TComSPS *sps = pSlice->getSPS();
+    const TComPPS *pps = pSlice->getPPS();
+
+    // check that the current active PPS has not changed...
+    if (m_parameterSetManager.getSPSChangedFlag(sps->getSPSId()) )
+    {
+      printf("Error - a new SPS has been decoded while processing a picture\n");
+      exit(1);
+    }
+    if (m_parameterSetManager.getPPSChangedFlag(pps->getPPSId()) )
+    {
+      printf("Error - a new PPS has been decoded while processing a picture\n");
+      exit(1);
+    }
+
+    xParsePrefixSEImessages();
+
+    // Check if any new SEI has arrived
+     if(!m_SEIs.empty())
+     {
+       // Currently only decoding Unit SEI message occurring between VCL NALUs copied
+       SEIMessages &picSEI = m_pcPic->getSEIs();
+       SEIMessages decodingUnitInfos = extractSeisByType (m_SEIs, SEI::DECODING_UNIT_INFO);
+       picSEI.insert(picSEI.end(), decodingUnitInfos.begin(), decodingUnitInfos.end());
+       deleteSEIs(m_SEIs);
+     }
+  }
+}
+Void TDecTop::xParsePrefixSEIsForUnknownVCLNal()
+{
+  while (!m_prefixSEINALUs.empty())
+  {
+    // do nothing?
+    printf("Discarding Prefix SEI associated with unknown VCL NAL unit.\n");
+    delete m_prefixSEINALUs.front();
+  }
+  // TODO: discard following suffix SEIs as well?
+}
+
+
+Void TDecTop::xParsePrefixSEImessages()
+{
+  while (!m_prefixSEINALUs.empty())
+  {
+    InputNALUnit &nalu=*m_prefixSEINALUs.front();
+#if NH_MV
+    m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_SEIs, nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS( getLayerId() ), m_pDecodedSEIOutputStream );
+#else
+    m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_SEIs, nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
+#endif
+    delete m_prefixSEINALUs.front();
+    m_prefixSEINALUs.pop_front();
+  }
+}
+
+
+#if NH_MV
 Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, Bool newLayerFlag, Bool& sliceSkippedFlag  )
 {
-  assert( nalu.m_layerId == m_layerId ); 
+  assert( nalu.m_nuhLayerId == m_layerId ); 
 #else
 Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay )
 {
 #endif
-  TComPic*&   pcPic         = m_pcPic;
-  m_apcSlicePilot->initSlice();
+  m_apcSlicePilot->initSlice(); // the slice pilot is an object to prepare for a new slice
+                                // it is not associated with picture, sps or pps structures.
 
   if (m_bFirstSliceInPicture)
   {
-    m_uiSliceIdx     = 0;
+    m_uiSliceIdx = 0;
   }
   else
   {
-    m_apcSlicePilot->copySliceInfo( pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
+    m_apcSlicePilot->copySliceInfo( m_pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
   }
   m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
@@ -788,29 +886,33 @@
                            m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N);
   m_apcSlicePilot->setTemporalLayerNonReferenceFlag(nonReferenceFlag);
-  
   m_apcSlicePilot->setReferenced(true); // Putting this as true ensures that picture is referenced the first time it is in an RPS
   m_apcSlicePilot->setTLayerInfo(nalu.m_temporalId);
 
-#if H_MV
+#if ENC_DEC_TRACE
+  const UInt64 originalSymbolCount = g_nSymbolCounter;
+#endif
+
+#if NH_MV
   m_apcSlicePilot->setRefPicSetInterLayer( & m_refPicSetInterLayer0, &m_refPicSetInterLayer1 ); 
-  m_apcSlicePilot->setLayerId( nalu.m_layerId );
-  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder, m_targetOptLayerSetIdx );
-#else
-  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder);
-#endif
+  m_apcSlicePilot->setLayerId( nalu.m_nuhLayerId );
+#endif
+
+  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManager, m_prevTid0POC);
+
   // set POC for dependent slices in skipped pictures
-  if(m_apcSlicePilot->getDependentSliceSegmentFlag() && m_prevSliceSkipped) 
+  if(m_apcSlicePilot->getDependentSliceSegmentFlag() && m_prevSliceSkipped)
   {
     m_apcSlicePilot->setPOC(m_skippedPOC);
   }
+
+  xUpdatePreviousTid0POC(m_apcSlicePilot);
 
   m_apcSlicePilot->setAssociatedIRAPPOC(m_pocCRA);
   m_apcSlicePilot->setAssociatedIRAPType(m_associatedIRAPType);
-
-#if H_MV  
-  TComVPS* vps     = m_apcSlicePilot->getVPS();
-  Int layerId  = nalu.m_layerId;   
+#if NH_MV  
+  const TComVPS* vps     = m_apcSlicePilot->getVPS();
+  Int layerId            = nalu.m_nuhLayerId;   
   setViewId   ( vps->getViewId   ( layerId )      );  
-#if H_3D
+#if NH_3D
   setViewIndex( vps->getViewIndex( layerId )      );  
   setIsDepth  ( vps->getDepthId  ( layerId ) == 1 );  
@@ -819,5 +921,4 @@
 #endif
 
-#if SETTING_NO_OUT_PIC_PRIOR
   //For inference of NoOutputOfPriorPicsFlag
   if (m_apcSlicePilot->getRapPicFlag())
@@ -865,36 +966,44 @@
     }
   }
-#endif
-
-#if FIX_POC_CRA_NORASL_OUTPUT
+
   if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA && m_craNoRaslOutputFlag) //Reset POC MSB when CRA has NoRaslOutputFlag equal to 1
   {
-    Int iMaxPOClsb = 1 << m_apcSlicePilot->getSPS()->getBitsForPOC();
+    TComPPS *pps = m_parameterSetManager.getPPS(m_apcSlicePilot->getPPSId());
+    assert (pps != 0);
+    TComSPS *sps = m_parameterSetManager.getSPS(pps->getSPSId());
+    assert (sps != 0);
+    Int iMaxPOClsb = 1 << sps->getBitsForPOC();
     m_apcSlicePilot->setPOC( m_apcSlicePilot->getPOC() & (iMaxPOClsb - 1) );
-  }
-#endif
-#if H_MV
+    xUpdatePreviousTid0POC(m_apcSlicePilot);
+  }
+#if NH_MV
     xCeckNoClrasOutput();
 #endif
-    // Skip pictures due to random access
-    if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
-    {
+
+  // Skip pictures due to random access
+
+#if NH_MV
+  if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay, vps))
+#else
+  if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
+#endif
+  {
     m_prevSliceSkipped = true;
     m_skippedPOC = m_apcSlicePilot->getPOC();
-#if H_MV
+#if NH_MV
     sliceSkippedFlag = true; 
 #endif
-      return false;
-    }
-    // Skip TFD pictures associated with BLA/BLANT pictures
-    if (isSkipPictureForBLA(iPOCLastDisplay))
-    {
+    return false;
+  }
+  // Skip TFD pictures associated with BLA/BLANT pictures
+  if (isSkipPictureForBLA(iPOCLastDisplay))
+  {
     m_prevSliceSkipped = true;
     m_skippedPOC = m_apcSlicePilot->getPOC();
-#if H_MV
+#if NH_MV
     sliceSkippedFlag = true; 
 #endif
-      return false;
-    }
+    return false;
+  }
 
   // clear previous slice skipped flag
@@ -902,19 +1011,24 @@
 
   //we should only get a different poc for a new picture (with CTU address==0)
-  if (m_apcSlicePilot->isNextSlice() && m_apcSlicePilot->getPOC()!=m_prevPOC && !m_bFirstSliceInSequence && (m_apcSlicePilot->getSliceCurStartCUAddr()!=0))
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag() && m_apcSlicePilot->getPOC()!=m_prevPOC && !m_bFirstSliceInSequence && (m_apcSlicePilot->getSliceCurStartCtuTsAddr() != 0))
   {
     printf ("Warning, the first slice of a picture might have been lost!\n");
   }
+
   // exit when a new picture is found
-  if (m_apcSlicePilot->isNextSlice() && (m_apcSlicePilot->getSliceCurStartCUAddr() == 0 && !m_bFirstSliceInPicture) && !m_bFirstSliceInSequence )
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag() && (m_apcSlicePilot->getSliceCurStartCtuTsAddr() == 0 && !m_bFirstSliceInPicture) )
   {
     if (m_prevPOC >= m_pocRandomAccess)
     {
       m_prevPOC = m_apcSlicePilot->getPOC();
+#if ENC_DEC_TRACE
+      //rewind the trace counter since we didn't actually decode the slice
+      g_nSymbolCounter = originalSymbolCount;
+#endif
       return true;
     }
     m_prevPOC = m_apcSlicePilot->getPOC();
   }
-#if H_MV
+#if NH_MV
   if ( newLayerFlag )
   {
@@ -928,6 +1042,6 @@
 #endif
 #endif
-  // actual decoding starts here
-#if H_MV
+
+#if NH_MV
    // This part needs further testing !
    if ( m_apcSlicePilot->getPocResetFlag() )
@@ -958,7 +1072,40 @@
 #endif
 
+  //detect lost reference picture and insert copy of earlier frame.
+  {
+    Int lostPoc;
+    while((lostPoc=m_apcSlicePilot->checkThatAllRefPicsAreAvailable(m_cListPic, m_apcSlicePilot->getRPS(), true, m_pocRandomAccess)) > 0)
+    {
+      xCreateLostPicture(lostPoc-1);
+    }
+  }
+
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag())
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+
+  // actual decoding starts here
   xActivateParameterSets();
 
-#if H_MV
+  m_bFirstSliceInSequence = false;
+  m_bFirstSliceInBitstream  = false;
+
+
+  TComSlice* pcSlice = m_pcPic->getPicSym()->getSlice(m_uiSliceIdx);
+
+  // When decoding the slice header, the stored start and end addresses were actually RS addresses, not TS addresses.
+  // Now, having set up the maps, convert them to the correct form.
+  pcSlice->setSliceSegmentCurStartCtuTsAddr( m_pcPic->getPicSym()->getCtuRsToTsAddrMap(pcSlice->getSliceSegmentCurStartCtuTsAddr()) );
+  pcSlice->setSliceSegmentCurEndCtuTsAddr( m_pcPic->getPicSym()->getCtuRsToTsAddrMap(pcSlice->getSliceSegmentCurEndCtuTsAddr()) );
+  if(!pcSlice->getDependentSliceSegmentFlag())
+  {
+    pcSlice->setSliceCurStartCtuTsAddr(m_pcPic->getPicSym()->getCtuRsToTsAddrMap(pcSlice->getSliceCurStartCtuTsAddr()));
+    pcSlice->setSliceCurEndCtuTsAddr(m_pcPic->getPicSym()->getCtuRsToTsAddrMap(pcSlice->getSliceCurEndCtuTsAddr()));
+  }
+
+  m_pcPic->setTLayer(nalu.m_temporalId);
+
+#if NH_MV
   //Check Multiview Main profile constraint in G.11.1.1
   //  When ViewOrderIdx[ i ] derived according to any active VPS is equal to 1 
@@ -966,142 +1113,27 @@
   //  inter_view_mv_vert_constraint_flag shall be equal to 1 
   //  in the sps_multilayer_extension( ) syntax structure in each active SPS for that layer.
-  if( m_apcSlicePilot->getSPS()->getPTL()->getGeneralPTL()->getProfileIdc()==Profile::MULTIVIEWMAIN
+  if( pcSlice->getSPS()->getPTL()->getGeneralPTL()->getProfileIdc()==Profile::MULTIVIEWMAIN
       &&
-      m_apcSlicePilot->getVPS()->getViewOrderIdx(m_apcSlicePilot->getVPS()->getLayerIdInNuh(getLayerId()))==1 
+      pcSlice->getVPS()->getViewOrderIdx(pcSlice->getVPS()->getLayerIdInNuh(getLayerId()))==1 
      )
   {
-    assert( m_apcSlicePilot->getSPS()->getInterViewMvVertConstraintFlag()==1 );
-  }
-#endif
-
-  if (m_apcSlicePilot->isNextSlice()) 
-  {
-    m_prevPOC = m_apcSlicePilot->getPOC();
-  }
-  m_bFirstSliceInSequence = false;
-#if SETTING_NO_OUT_PIC_PRIOR  
-  m_bFirstSliceInBitstream  = false;
-#endif
-  //detect lost reference picture and insert copy of earlier frame.
-  Int lostPoc;
-  while((lostPoc=m_apcSlicePilot->checkThatAllRefPicsAreAvailable(m_cListPic, m_apcSlicePilot->getRPS(), true, m_pocRandomAccess)) > 0)
-  {
-    xCreateLostPicture(lostPoc-1);
-  }
-  if (m_bFirstSliceInPicture)
-  {
-    // Buffer initialize for prediction.
-    m_cPrediction.initTempBuff();
-    m_apcSlicePilot->applyReferencePictureSet(m_cListPic, m_apcSlicePilot->getRPS());
-#if H_MV
-    m_apcSlicePilot->createInterLayerReferencePictureSet( m_ivPicLists, m_refPicSetInterLayer0, m_refPicSetInterLayer1 ); 
-#endif
-    //  Get a new picture buffer
-    xGetNewPicBuffer (m_apcSlicePilot, pcPic);
-
-    Bool isField = false;
-    Bool isTff = false;
-    
-    if(!m_SEIs.empty())
-    {
-      // Check if any new Picture Timing SEI has arrived
-      SEIMessages pictureTimingSEIs = extractSeisByType (m_SEIs, SEI::PICTURE_TIMING);
-      if (pictureTimingSEIs.size()>0)
-      {
-        SEIPictureTiming* pictureTiming = (SEIPictureTiming*) *(pictureTimingSEIs.begin());
-        isField = (pictureTiming->m_picStruct == 1) || (pictureTiming->m_picStruct == 2);
-        isTff =  (pictureTiming->m_picStruct == 1);
-      }
-    }
-    
-    //Set Field/Frame coding mode
-    m_pcPic->setField(isField);
-    m_pcPic->setTopField(isTff);
-    
-    // transfer any SEI messages that have been received to the picture
-    pcPic->setSEIs(m_SEIs);
-    m_SEIs.clear();
-
-    // Recursive structure
-    m_cCuDecoder.create ( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight );
-    m_cCuDecoder.init   ( &m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction );
-    m_cTrQuant.init     ( g_uiMaxCUWidth, g_uiMaxCUHeight, m_apcSlicePilot->getSPS()->getMaxTrSize());
-
-    m_cSliceDecoder.create();
-  }
-  else
-  {
-    // Check if any new SEI has arrived
-    if(!m_SEIs.empty())
-    {
-      // Currently only decoding Unit SEI message occurring between VCL NALUs copied
-      SEIMessages &picSEI = pcPic->getSEIs();
-      SEIMessages decodingUnitInfos = extractSeisByType (m_SEIs, SEI::DECODING_UNIT_INFO);
-      picSEI.insert(picSEI.end(), decodingUnitInfos.begin(), decodingUnitInfos.end());
-      deleteSEIs(m_SEIs);
-    }
-  }
-  
-  //  Set picture slice pointer
-  TComSlice*  pcSlice = m_apcSlicePilot;
-  Bool bNextSlice     = pcSlice->isNextSlice();
-
-  UInt i;
-  pcPic->getPicSym()->initTiles(pcSlice->getPPS());
-
-  //generate the Coding Order Map and Inverse Coding Order Map
-  UInt uiEncCUAddr;
-  for(i=0, uiEncCUAddr=0; i<pcPic->getPicSym()->getNumberOfCUsInFrame(); i++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
-  {
-    pcPic->getPicSym()->setCUOrderMap(i, uiEncCUAddr);
-    pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, i);
-  }
-  pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
-  pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
-
-  //convert the start and end CU addresses of the slice and dependent slice into encoding order
-  pcSlice->setSliceSegmentCurStartCUAddr( pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceSegmentCurStartCUAddr()) );
-  pcSlice->setSliceSegmentCurEndCUAddr( pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceSegmentCurEndCUAddr()) );
-  if(pcSlice->isNextSlice())
-  {
-    pcSlice->setSliceCurStartCUAddr(pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceCurStartCUAddr()));
-    pcSlice->setSliceCurEndCUAddr(pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceCurEndCUAddr()));
-  }
-
-  if (m_bFirstSliceInPicture) 
-  {
-    if(pcPic->getNumAllocatedSlice() != 1)
-    {
-      pcPic->clearSliceBuffer();
-    }
-  }
-  else
-  {
-    pcPic->allocateNewSlice();
-  }
-  assert(pcPic->getNumAllocatedSlice() == (m_uiSliceIdx + 1));
-  m_apcSlicePilot = pcPic->getPicSym()->getSlice(m_uiSliceIdx); 
-  pcPic->getPicSym()->setSlice(pcSlice, m_uiSliceIdx);
-
-  pcPic->setTLayer(nalu.m_temporalId);
-
-#if H_MV
-  pcPic->setLayerId( nalu.m_layerId );
-  pcPic->setViewId ( getViewId() );
-#if H_3D
-  pcPic->setViewIndex( getViewIndex() );
-  pcPic->setIsDepth  ( getIsDepth  () );
+    assert( pcSlice->getSPS()->getInterViewMvVertConstraintFlag()==1 );
+  }
+#endif
+#if NH_MV
+  m_pcPic->setLayerId( nalu.m_nuhLayerId );
+  m_pcPic->setViewId ( getViewId() );
+#if NH_3D
+  m_pcPic->setViewIndex( getViewIndex() );
+  m_pcPic->setIsDepth  ( getIsDepth  () );
   pcSlice->setIvPicLists( m_ivPicLists );         
 #endif
 #endif
 
-
-
-
-  if (bNextSlice)
+  if (!pcSlice->getDependentSliceSegmentFlag())
   {
     pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_associatedIRAPType, m_cListPic );
     // Set reference list
-#if H_MV    
+#if NH_MV    
     std::vector< TComPic* > tempRefPicLists[2];
     std::vector< Bool     > usedAsLongTerm [2];
@@ -1118,5 +1150,5 @@
     {
       // GT: This seems to be broken, not all nuh_layer_ids are necessarily present
-      for(Int iLayerId = 0; iLayerId < nalu.m_layerId; iLayerId ++ )
+      for(Int iLayerId = 0; iLayerId < nalu.m_nuhLayerId; iLayerId ++ )
       {
         Int  iViewIdx =   pcSlice->getVPS()->getViewIndex(iLayerId);
@@ -1133,5 +1165,5 @@
 #endif
 
-#if H_3D
+#if NH_3D
     pcSlice->checkInCompPredRefLayers(); 
 #if H_3D_IV_MERGE
@@ -1143,5 +1175,5 @@
 #endif    
 #endif
-#if H_MV
+#if NH_MV
     if( m_layerId > 0 && !pcSlice->isIntra() && pcSlice->getEnableTMVPFlag() )
     {
@@ -1186,8 +1218,8 @@
             bLowDelay = false;
           }
-        }        
-      }
-
-      pcSlice->setCheckLDC(bLowDelay);            
+        }
+      }
+
+      pcSlice->setCheckLDC(bLowDelay);
     }
 
@@ -1202,22 +1234,31 @@
   }
 
-  pcPic->setCurrSliceIdx(m_uiSliceIdx);
+  m_pcPic->setCurrSliceIdx(m_uiSliceIdx);
   if(pcSlice->getSPS()->getScalingListFlag())
   {
-    pcSlice->setScalingList ( pcSlice->getSPS()->getScalingList()  );
+    TComScalingList scalingList;
     if(pcSlice->getPPS()->getScalingListPresentFlag())
     {
-      pcSlice->setScalingList ( pcSlice->getPPS()->getScalingList()  );
-    }
-    if(!pcSlice->getPPS()->getScalingListPresentFlag() && !pcSlice->getSPS()->getScalingListPresentFlag())
-    {
-      pcSlice->setDefaultScalingList();
-    }
-    m_cTrQuant.setScalingListDec(pcSlice->getScalingList());
+      scalingList = pcSlice->getPPS()->getScalingList();
+    }
+    else if (pcSlice->getSPS()->getScalingListPresentFlag())
+    {
+      scalingList = pcSlice->getSPS()->getScalingList();
+    }
+    else
+    {
+      scalingList.setDefaultScalingList();
+    }
+    m_cTrQuant.setScalingListDec(scalingList);
     m_cTrQuant.setUseScalingList(true);
   }
   else
   {
-    m_cTrQuant.setFlatScalingList();
+    const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE] =
+    {
+        pcSlice->getSPS()->getMaxLog2TrDynamicRange(CHANNEL_TYPE_LUMA),
+        pcSlice->getSPS()->getMaxLog2TrDynamicRange(CHANNEL_TYPE_CHROMA)
+    };
+    m_cTrQuant.setFlatScalingList(maxLog2TrDynamicRange, pcSlice->getSPS()->getBitDepths());
     m_cTrQuant.setUseScalingList(false);
   }
@@ -1233,8 +1274,8 @@
   }
 #endif
-
   //  Decode a picture
-  m_cGopDecoder.decompressSlice(nalu.m_Bitstream, pcPic);
-#if H_3D
+  m_cGopDecoder.decompressSlice(&(nalu.getBitstream()), m_pcPic);
+
+#if NH_3D
   if( m_pcCamParsCollector )
   {
@@ -1242,4 +1283,5 @@
   }
 #endif
+
   m_bFirstSliceInPicture = false;
   m_uiSliceIdx++;
@@ -1248,88 +1290,43 @@
 }
 
-Void TDecTop::xDecodeVPS()
+Void TDecTop::xDecodeVPS(const std::vector<UChar> &naluData)
 {
   TComVPS* vps = new TComVPS();
-  
+
   m_cEntropyDecoder.decodeVPS( vps );
-  m_parameterSetManagerDecoder.storePrefetchedVPS(vps);  
-}
-
-Void TDecTop::xDecodeSPS()
+  m_parameterSetManager.storeVPS(vps, naluData);
+}
+
+Void TDecTop::xDecodeSPS(const std::vector<UChar> &naluData)
 {
   TComSPS* sps = new TComSPS();
-#if H_MV
+#if NH_MV
   sps->setLayerId( getLayerId() ); 
 #endif
+#if O0043_BEST_EFFORT_DECODING
+  sps->setForceDecodeBitDepth(m_forceDecodeBitDepth);
+#endif
+#if NH_3D
+  // GT: Please don't add parsing dependency of SPS from VPS here again!!!
+#endif
+  m_cEntropyDecoder.decodeSPS( sps );
+  m_parameterSetManager.storeSPS(sps, naluData);
+}
+
+Void TDecTop::xDecodePPS(const std::vector<UChar> &naluData)
+{
+  TComPPS* pps = new TComPPS();
+#if NH_MV
+  pps->setLayerId( getLayerId() ); 
+#endif
 #if H_3D
-  // Preliminary fix. assuming that all sps refer to the same VPS. 
-  // Parsing dependency should be resolved!
-  TComVPS* vps = m_parameterSetManagerDecoder.getPrefetchedVPS( 0 ); 
-  assert( vps != 0 );
-  m_cEntropyDecoder.decodeSPS( sps );
-#else
-  m_cEntropyDecoder.decodeSPS( sps );
-#endif
-  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
-}
-
-Void TDecTop::xDecodePPS()
-{
-  TComPPS* pps = new TComPPS();
-#if H_MV
-  pps->setLayerId( getLayerId() ); 
-#endif
-#if H_3D
-  // Assuming that all PPS indirectly refer to the same VPS via different SPS
-  // There is no parsing dependency in decoding DLT in PPS. 
-  // The VPS information passed to decodePPS() is used to arrange the decoded DLT tables to their corresponding layers. 
-  // This is equivalent to the process of 
-  //   Step 1) decoding DLT tables based on the number of depth layers, and
-  //   Step 2) mapping DLT tables to the depth layers
-  // as described in the 3D-HEVC WD. 
-  TComVPS* vps = m_parameterSetManagerDecoder.getPrefetchedVPS( 0 );
-  m_cEntropyDecoder.decodePPS( pps, vps );
-#else
+  // GT: Please don't add parsing dependency of SPS from VPS here again!!!
+#endif
   m_cEntropyDecoder.decodePPS( pps );
-#endif
-  m_parameterSetManagerDecoder.storePrefetchedPPS( pps );
-}
-
-Void TDecTop::xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType )
-{
-  if(nalUnitType == NAL_UNIT_SUFFIX_SEI)
-  {
-#if H_MV
-    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS( m_layerId ) );
-#else
-    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
-#endif
-  }
-  else
-  {
-#if H_MV
-    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveSPS( m_layerId ) );
-#else
-    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
-#endif
-    SEIMessages activeParamSets = getSeisByType(m_SEIs, SEI::ACTIVE_PARAMETER_SETS);
-    if (activeParamSets.size()>0)
-    {
-      SEIActiveParameterSets *seiAps = (SEIActiveParameterSets*)(*activeParamSets.begin());
-      m_parameterSetManagerDecoder.applyPrefetchedPS();
-      assert(seiAps->activeSeqParameterSetId.size()>0);
-#if H_MV
-      if (! m_parameterSetManagerDecoder.activateSPSWithSEI(seiAps->activeSeqParameterSetId[0], m_layerId ))
-#else
-      if (! m_parameterSetManagerDecoder.activateSPSWithSEI(seiAps->activeSeqParameterSetId[0] ))
-#endif
-      {
-        printf ("Warning SPS activation with Active parameter set SEI failed");
-      }
-    }
-  }
-}
-
-#if H_MV
+
+  m_parameterSetManager.storePPS( pps, naluData);
+}
+
+#if NH_MV
 Bool TDecTop::decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, Bool newLayerFlag, Bool& sliceSkippedFlag )
 #else
@@ -1337,28 +1334,40 @@
 #endif
 {
+#if !NH_MV
+  // ignore all NAL units of layers > 0
+  if (nalu.m_nuhLayerId > 0)
+  {
+    fprintf (stderr, "Warning: found NAL unit with nuh_layer_id equal to %d. Ignoring.\n", nalu.m_nuhLayerId);
+    return false;
+  }
+#endif
   // Initialize entropy decoder
   m_cEntropyDecoder.setEntropyDecoder (&m_cCavlcDecoder);
-  m_cEntropyDecoder.setBitstream      (nalu.m_Bitstream);
+  m_cEntropyDecoder.setBitstream      (&(nalu.getBitstream()));
 
   switch (nalu.m_nalUnitType)
   {
     case NAL_UNIT_VPS:
-      xDecodeVPS();
-#if H_MV
+      xDecodeVPS(nalu.getBitstream().getFifo());
+#if NH_MV
       m_isLastNALWasEos = false;
 #endif
       return false;
-      
+
     case NAL_UNIT_SPS:
-      xDecodeSPS();
+      xDecodeSPS(nalu.getBitstream().getFifo());
       return false;
 
     case NAL_UNIT_PPS:
-      xDecodePPS();
+      xDecodePPS(nalu.getBitstream().getFifo());
       return false;
-      
+
     case NAL_UNIT_PREFIX_SEI:
+      // Buffer up prefix SEI messages until SPS of associated VCL is known.
+      m_prefixSEINALUs.push_back(new InputNALUnit(nalu));
+      return false;
+
     case NAL_UNIT_SUFFIX_SEI:
-#if H_MV
+#if NH_MV
       if ( nalu.m_nalUnitType == NAL_UNIT_SUFFIX_SEI )
       {
@@ -1366,5 +1375,16 @@
       }
 #endif
-      xDecodeSEI( nalu.m_Bitstream, nalu.m_nalUnitType );
+      if (m_pcPic)
+      {
+#if NH_MV
+        m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_pcPic->getSEIs(), nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS( getLayerId() ), m_pDecodedSEIOutputStream );
+#else
+        m_seiReader.parseSEImessage( &(nalu.getBitstream()), m_pcPic->getSEIs(), nalu.m_nalUnitType, m_parameterSetManager.getActiveSPS(), m_pDecodedSEIOutputStream );
+#endif
+      }
+      else
+      {
+        printf ("Note: received suffix SEI but no picture currently active.\n");
+      }
       return false;
 
@@ -1385,5 +1405,5 @@
     case NAL_UNIT_CODED_SLICE_RASL_N:
     case NAL_UNIT_CODED_SLICE_RASL_R:
-#if H_MV
+#if NH_MV
       if (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N ||
           nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N ||
@@ -1398,5 +1418,4 @@
         m_isLastNALWasEos = false;
       }
-
       return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay, newLayerFlag, sliceSkippedFlag );
 #else
@@ -1404,9 +1423,10 @@
 #endif
       break;
+
     case NAL_UNIT_EOS:
-#if H_MV
+#if NH_MV
       assert( m_isLastNALWasEos == false );
       //Check layer id of the nalu. if it is not 0, give a warning message and just return without doing anything.
-      if (nalu.m_layerId > 0)
+      if (nalu.m_nuhLayerId > 0)
       {
         printf( "\nThis bitstream has EOS with non-zero layer id.\n" );
@@ -1419,23 +1439,32 @@
       m_pocRandomAccess = MAX_INT;
       m_prevPOC = MAX_INT;
-      m_bFirstSliceInPicture = true;
-      m_bFirstSliceInSequence = true;
       m_prevSliceSkipped = false;
       m_skippedPOC = 0;
       return false;
-      
+
     case NAL_UNIT_ACCESS_UNIT_DELIMITER:
-      // TODO: process AU delimiter
+      {
+        AUDReader audReader;
+        UInt picType;
+        audReader.parseAccessUnitDelimiter(&(nalu.getBitstream()),picType);
+        printf ("Note: found NAL_UNIT_ACCESS_UNIT_DELIMITER\n");
       return false;
-      
+      }
+
     case NAL_UNIT_EOB:
       return false;
-      
+
     case NAL_UNIT_FILLER_DATA:
-#if H_MV
+      {
+        FDReader fdReader;
+        UInt size;
+        fdReader.parseFillerData(&(nalu.getBitstream()),size);
+        printf ("Note: found NAL_UNIT_FILLER_DATA with %u bytes payload.\n", size);
+#if NH_MV
       assert( m_isLastNALWasEos == false );
 #endif
       return false;
-      
+      }
+
     case NAL_UNIT_RESERVED_VCL_N10:
     case NAL_UNIT_RESERVED_VCL_R11:
@@ -1444,8 +1473,8 @@
     case NAL_UNIT_RESERVED_VCL_N14:
     case NAL_UNIT_RESERVED_VCL_R15:
-      
+
     case NAL_UNIT_RESERVED_IRAP_VCL22:
     case NAL_UNIT_RESERVED_IRAP_VCL23:
-      
+
     case NAL_UNIT_RESERVED_VCL24:
     case NAL_UNIT_RESERVED_VCL25:
@@ -1456,5 +1485,8 @@
     case NAL_UNIT_RESERVED_VCL30:
     case NAL_UNIT_RESERVED_VCL31:
-      
+      printf ("Note: found reserved VCL NAL unit.\n");
+      xParsePrefixSEIsForUnknownVCLNal();
+      return false;
+
     case NAL_UNIT_RESERVED_NVCL41:
     case NAL_UNIT_RESERVED_NVCL42:
@@ -1464,4 +1496,6 @@
     case NAL_UNIT_RESERVED_NVCL46:
     case NAL_UNIT_RESERVED_NVCL47:
+      printf ("Note: found reserved NAL unit.\n");
+      return false;
     case NAL_UNIT_UNSPECIFIED_48:
     case NAL_UNIT_UNSPECIFIED_49:
@@ -1480,6 +1514,9 @@
     case NAL_UNIT_UNSPECIFIED_62:
     case NAL_UNIT_UNSPECIFIED_63:
+      printf ("Note: found unspecified NAL unit.\n");
+      return false;
     default:
       assert (0);
+      break;
   }
 
@@ -1495,5 +1532,5 @@
 Bool TDecTop::isSkipPictureForBLA(Int& iPOCLastDisplay)
 {
-  if ((m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_N_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_RADL) && 
+  if ((m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_N_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_RADL) &&
        m_apcSlicePilot->getPOC() < m_pocCRA && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
   {
@@ -1513,16 +1550,20 @@
  * If the random access point is CRA/CRANT/BLA/BLANT, TFD pictures with POC less than the POC of the random access point are skipped.
  * If the random access point is IDR all pictures after the random access point are decoded.
- * If the random access point is none of the above, a warning is issues, and decoding of pictures with POC 
- * equal to or greater than the random access point POC is attempted. For non IDR/CRA/BLA random 
+ * If the random access point is none of the above, a warning is issues, and decoding of pictures with POC
+ * equal to or greater than the random access point POC is attempted. For non IDR/CRA/BLA random
  * access point there is no guarantee that the decoder will not crash.
  */
-Bool TDecTop::isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay)
-{
-  if (iSkipFrame) 
+#if NH_MV
+Bool TDecTop::isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay, const TComVPS* vps)
+#else
+Bool TDecTop::isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay )
+#endif
+{
+  if (iSkipFrame)
   {
     iSkipFrame--;   // decrement the counter
     return true;
   }
-#if H_MV
+#if NH_MV
   else if ( !m_layerInitilizedFlag[ m_layerId ] ) // start of random access point, m_pocRandomAccess has not been set yet.
 #else
@@ -1536,6 +1577,6 @@
     {
 
-#if H_MV
-      if ( xAllRefLayersInitilized() )
+#if NH_MV
+      if ( xAllRefLayersInitilized( vps ) )
       {
         m_layerInitilizedFlag[ m_layerId ] = true; 
@@ -1553,6 +1594,6 @@
     else if ( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
     {
-#if H_MV
-      if ( xAllRefLayersInitilized() )
+#if NH_MV
+      if ( xAllRefLayersInitilized( vps) )
       {
         m_layerInitilizedFlag[ m_layerId ] = true; 
@@ -1567,7 +1608,7 @@
 #endif
     }
-    else 
-    {
-#if H_MV
+    else
+    {
+#if NH_MV
       static Bool warningMessage[MAX_NUM_LAYERS];
       static Bool warningInitFlag = false;
@@ -1588,9 +1629,8 @@
       }
 #else
-      static Bool warningMessage = false;
-      if(!warningMessage)
+      if(!m_warningMessageSkipPicture)
       {
         printf("\nWarning: this is not a valid random access point and the data is discarded until the first CRA picture");
-        warningMessage = true;
+        m_warningMessageSkipPicture = true;
       }
 #endif
@@ -1604,13 +1644,12 @@
     return true;
   }
-#if H_MV
+  // if we reach here, then the picture is not skipped.
+#if NH_MV
   return !m_layerInitilizedFlag[ getLayerId() ]; 
 #else
-  // if we reach here, then the picture is not skipped.
-  return false; 
-#endif
-}
-
-#if H_MV
+  return false;
+#endif
+}
+#if NH_MV
 TComPic* TDecTop::getPic( Int poc )
 {
@@ -1672,8 +1711,7 @@
 }
 
-Bool TDecTop::xAllRefLayersInitilized()
-{
-  Bool allRefLayersInitilizedFlag = true; 
-  TComVPS* vps = m_parameterSetManagerDecoder.getPrefetchedVPS( 0 ); 
+Bool TDecTop::xAllRefLayersInitilized( const TComVPS* vps )
+{
+  Bool allRefLayersInitilizedFlag = true;   
   for (Int i = 0; i < vps->getNumDirectRefLayers( getLayerId()  ); i++ )
   {
@@ -1685,28 +1723,32 @@
 }
 
-#if H_3D
-Void TDecTop::setProfileIdc()
-{
-  if (m_targetOptLayerSetIdx != -1 )
-  {    
-    TComVPS* vps = getPrefetchedVPS(); 
-    Int lsIdx = vps->olsIdxToLsIdx( m_targetOptLayerSetIdx );
-    Int lIdx = -1; 
-    for (Int j = 0; j < vps->getNumLayersInIdList( lsIdx ); j++ )
-    {
-      if ( vps->getLayerSetLayerIdList( lsIdx, j ) == getLayerId() )
-      {
-        lIdx = j; 
-        break; 
-      }        
-    }
-    assert( lIdx != -1 ); 
-
-    Int profileIdc = vps->getPTL( vps->getProfileTierLevelIdx( m_targetOptLayerSetIdx, lIdx ) )->getGeneralPTL()->getProfileIdc();
-    assert( profileIdc == 1 || profileIdc == 6 || profileIdc == 8 ); 
-    m_profileIdc = profileIdc;   
-  };
-}
-#endif
-#endif
+
+Void TDecTop::initFromActiveVps( const TComVPS* vps )
+{
+  if ( m_targetOlsIdx == -1 )
+  {
+    // Not normative! Corresponds to specification by "External Means". (Should be set equal to 0, when no external means available. ) 
+    m_targetOlsIdx = vps->getVpsNumLayerSetsMinus1(); 
+  }
+#if NH_3D
+  // Set profile
+  Int lsIdx = vps->olsIdxToLsIdx( m_targetOlsIdx );
+  Int lIdx = -1; 
+  for (Int j = 0; j < vps->getNumLayersInIdList( lsIdx ); j++ )
+  {
+    if ( vps->getLayerSetLayerIdList( lsIdx, j ) == getLayerId() )
+    {
+      lIdx = j; 
+      break; 
+    }        
+  }
+  assert( lIdx != -1 ); 
+
+  Int profileIdc = vps->getPTL( vps->getProfileTierLevelIdx( m_targetOlsIdx, lIdx ) )->getGeneralPTL()->getProfileIdc();
+  assert( profileIdc == 1 || profileIdc == 6 || profileIdc == 8 ); 
+  m_profileIdc = profileIdc;   
+#endif
+}
+#endif
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecTop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibDecoder/TDecTop.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -44,4 +44,5 @@
 #include "TLibCommon/TComPic.h"
 #include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComPrediction.h"
 #include "TLibCommon/SEI.h"
 
@@ -52,5 +53,5 @@
 #include "SEIread.h"
 
-struct InputNALUnit;
+class InputNALUnit;
 
 //! \ingroup TLibDecoder
@@ -61,8 +62,8 @@
 // ====================================================================================================================
 
-#if H_MV
+#if NH_MV
 class TAppDecTop;
 #endif
-#if H_3D
+#if NH_3D
 class CamParsCollector
 {
@@ -71,5 +72,6 @@
   ~CamParsCollector ();
 
-  Void  init        ( FILE* pCodedScaleOffsetFile, TComVPS* vps );
+  Void  init        ( const TComVPS* vps );
+  Void  setCodeScaleOffsetFile( FILE* pCodedScaleOffsetFile ) { m_pCodedScaleOffsetFile = pCodedScaleOffsetFile; };     
 
   Void  uninit      ();
@@ -95,5 +97,5 @@
   Int**   m_aaiCodedScale;
   
-  TComVPS* m_vps; 
+  const TComVPS* m_vps; 
   Int**    m_receivedIdc; 
   Int      m_lastPoc; 
@@ -180,5 +182,5 @@
 private:
   Int                     m_iMaxRefPicNum;
-  
+
   NalUnitType             m_associatedIRAPType; ///< NAL unit type of the associated IRAP picture
   Int                     m_pocCRA;            ///< POC number of the latest CRA picture
@@ -186,14 +188,14 @@
 
   TComList<TComPic*>      m_cListPic;         //  Dynamic buffer
-#if H_MV
+#if NH_MV
   Bool*                    m_layerInitilizedFlag; // initialization Layers
-  static ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
-  Int                      m_targetOptLayerSetIdx; 
+  static ParameterSetManager m_parameterSetManager;  // storage for parameter sets 
+  Int                      m_targetOlsIdx; 
 #else
-  ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
+  ParameterSetManager     m_parameterSetManager;  // storage for parameter sets
 #endif
   TComSlice*              m_apcSlicePilot;
-  
-  SEIMessages             m_SEIs; ///< List of SEI messages that have been received before the first slice and between slices
+
+  SEIMessages             m_SEIs; ///< List of SEI messages that have been received before the first slice and between slices, excluding prefix SEIs...
 
   // functional classes
@@ -212,24 +214,33 @@
 
   Bool isSkipPictureForBLA(Int& iPOCLastDisplay);
+#if NH_MV
+  Bool isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay, const TComVPS* vps);
+#else
   Bool isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay);
+#endif
   TComPic*                m_pcPic;
   UInt                    m_uiSliceIdx;
   Int                     m_prevPOC;
+  Int                     m_prevTid0POC;
   Bool                    m_bFirstSliceInPicture;
   Bool                    m_bFirstSliceInSequence;
   Bool                    m_prevSliceSkipped;
   Int                     m_skippedPOC;
-#if SETTING_NO_OUT_PIC_PRIOR  
   Bool                    m_bFirstSliceInBitstream;
   Int                     m_lastPOCNoOutputPriorPics;
   Bool                    m_isNoOutputPriorPics;
   Bool                    m_craNoRaslOutputFlag;    //value of variable NoRaslOutputFlag of the last CRA pic
-#endif
-#if H_MV
+#if O0043_BEST_EFFORT_DECODING
+  UInt                    m_forceDecodeBitDepth;
+#endif
+  std::ostream           *m_pDecodedSEIOutputStream;
+
+  Bool                    m_warningMessageSkipPicture;
+#if NH_MV
   Bool                    m_isLastNALWasEos;
 #endif
 
-#if H_MV
-  // For H_MV m_bFirstSliceInSequence indicates first slice in sequence of the particular layer  
+#if NH_MV
+  // For NH_MV m_bFirstSliceInSequence indicates first slice in sequence of the particular layer  
   Int                     m_layerId;
   Int                     m_viewId;
@@ -237,5 +248,5 @@
   std::vector<TComPic*>   m_refPicSetInterLayer0; 
   std::vector<TComPic*>   m_refPicSetInterLayer1; 
-#if H_3D
+#if NH_3D
   Int                     m_viewIndex; 
   Bool                    m_isDepth;
@@ -245,15 +256,16 @@
 #endif
 
+  std::list<InputNALUnit*> m_prefixSEINALUs; /// Buffered up prefix SEI NAL Units.
 public:
   TDecTop();
   virtual ~TDecTop();
-  
+
   Void  create  ();
   Void  destroy ();
 
-  void setDecodedPictureHashSEIEnabled(Int enabled) { m_cGopDecoder.setDecodedPictureHashSEIEnabled(enabled); }
+  Void setDecodedPictureHashSEIEnabled(Int enabled) { m_cGopDecoder.setDecodedPictureHashSEIEnabled(enabled); }
 
   Void  init();
-#if H_MV  
+#if NH_MV  
   Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, Bool newLayer, Bool& sliceSkippedFlag );
   Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, Bool newLayer );
@@ -261,32 +273,35 @@
   Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay);
 #endif
-  
   Void  deletePicBuffer();
-#if H_MV
-  TComVPS* getActiveVPS() { return m_parameterSetManagerDecoder.getActiveVPS( ); }
-  TComSPS* getActiveSPS() { return m_parameterSetManagerDecoder.getActiveSPS( m_layerId ); }
-#else
-  TComSPS* getActiveSPS() { return m_parameterSetManagerDecoder.getActiveSPS(); }
-#endif
-
-#if H_MV
+
+#if NH_MV
+  const TComVPS* getActiveVPS() { return m_parameterSetManager.getActiveVPS( ); }
+  const TComSPS* getActiveSPS() { return m_parameterSetManager.getActiveSPS( m_layerId ); }
+#endif
+
+#if NH_MV
   Void endPicDecoding(Int& poc, TComList<TComPic*>*& rpcListPic,  std::vector<Int>& targetDecLayerIdSet);  
-#else
-  Void executeLoopFilters(Int& poc, TComList<TComPic*>*& rpcListPic);
-#endif
-  
-#if SETTING_NO_OUT_PIC_PRIOR  
-  Void  checkNoOutputPriorPics (TComList<TComPic*>*& rpcListPic);
+#else  
+  Void  executeLoopFilters(Int& poc, TComList<TComPic*>*& rpcListPic);
+#endif
+  Void  checkNoOutputPriorPics (TComList<TComPic*>* rpcListPic);
 
   Bool  getNoOutputPriorPicsFlag () { return m_isNoOutputPriorPics; }
-  Void  setNoOutputPriorPicsFlag (bool val) { m_isNoOutputPriorPics = val; }
-#endif
-#if H_MV    
+  Void  setNoOutputPriorPicsFlag (Bool val) { m_isNoOutputPriorPics = val; }
+  Void  setFirstSliceInPicture (bool val)  { m_bFirstSliceInPicture = val; }
+  Bool  getFirstSliceInSequence ()         { return m_bFirstSliceInSequence; }
+  Void  setFirstSliceInSequence (bool val) { m_bFirstSliceInSequence = val; }
+#if O0043_BEST_EFFORT_DECODING
+  Void  setForceDecodeBitDepth(UInt bitDepth) { m_forceDecodeBitDepth = bitDepth; }
+#endif
+  Void  setDecodedSEIMessageOutputStream(std::ostream *pOpStream) { m_pDecodedSEIOutputStream = pOpStream; }
+  UInt  getNumberOfChecksumErrorsDetected() const { return m_cGopDecoder.getNumberOfChecksumErrorsDetected(); }
+#if NH_MV    
   TComPic*                getPic                ( Int poc );
   TComList<TComPic*>*     getListPic            ()               { return &m_cListPic;  }  
   Void                    setIvPicLists         ( TComPicLists* picLists) { m_ivPicLists = picLists; }
   Void                    setLayerInitilizedFlags( Bool* val )    { m_layerInitilizedFlag = val; }
-  Void                    setTargetOptLayerSetIdx( Int targetOptLayerSetIdx ) { m_targetOptLayerSetIdx = targetOptLayerSetIdx; }    
-  TComVPS*                getPrefetchedVPS      ()               { return m_parameterSetManagerDecoder.getPrefetchedVPS( 0 ); }; //Assuming that currently only one VPS is present. 
+  Void                    setTargetOlsIdx       ( Int targetOlsIdx ) { m_targetOlsIdx = targetOlsIdx; }    
+  Int                     getTargetOlsIdx       ( )                  { return m_targetOlsIdx; }    
   Int                     getCurrPoc            ()               { return m_apcSlicePilot->getPOC(); }
   Void                    setLayerId            ( Int layer)     { m_layerId = layer;   }
@@ -294,5 +309,6 @@
   Void                    setViewId             ( Int viewId  )  { m_viewId  = viewId;  }
   Int                     getViewId             ()               { return m_viewId;     }  
-#if H_3D    
+  Void                    initFromActiveVps     ( const TComVPS* vps );
+#if NH_3D    
   Void                    setViewIndex          ( Int viewIndex  )  { m_viewIndex  = viewIndex;  }
   Int                     getViewIndex          ()               { return m_viewIndex;     }  
@@ -301,14 +317,15 @@
   Void                    setCamParsCollector( CamParsCollector* pcCamParsCollector ) { m_pcCamParsCollector = pcCamParsCollector; }
 
-  Void                    setProfileIdc();
+
   Bool                    decProcAnnexI()           { assert( m_profileIdc != -1 ); return ( m_profileIdc == 8); }    
 #endif
 #endif
+
 protected:
-  Void  xGetNewPicBuffer  (TComSlice* pcSlice, TComPic*& rpcPic);
+  Void  xGetNewPicBuffer  (const TComSPS &sps, const TComPPS &pps, TComPic*& rpcPic, const UInt temporalLayer);
   Void  xCreateLostPicture (Int iLostPOC);
 
   Void      xActivateParameterSets();
-#if H_MV  
+#if NH_MV  
   TComPic*  xGetPic( Int layerId, Int poc ); 
   Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, Bool newLayerFlag, Bool& sliceSkippedFlag );  
@@ -316,12 +333,15 @@
   Void      xCeckNoClrasOutput();
 
-  Bool      xAllRefLayersInitilized();
+  Bool      xAllRefLayersInitilized( const TComVPS* vps );
 #else
   Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay);
 #endif
-  Void      xDecodeVPS();
-  Void      xDecodeSPS();
-  Void      xDecodePPS();
-  Void      xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType );
+  Void      xDecodeVPS(const std::vector<UChar> &naluData);
+  Void      xDecodeSPS(const std::vector<UChar> &naluData);
+  Void      xDecodePPS(const std::vector<UChar> &naluData);
+  Void      xUpdatePreviousTid0POC( TComSlice *pSlice ) { if ((pSlice->getTLayer()==0) && (pSlice->isReferenceNalu() && (pSlice->getNalUnitType()!=NAL_UNIT_CODED_SLICE_RASL_R)&& (pSlice->getNalUnitType()!=NAL_UNIT_CODED_SLICE_RADL_R))) { m_prevTid0POC=pSlice->getPOC(); } }
+
+  Void      xParsePrefixSEImessages();
+  Void      xParsePrefixSEIsForUnknownVCLNal();
 
 };// END CLASS DEFINITION TDecTop
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -33,4 +33,7 @@
 
 #pragma once
+
+#ifndef __ANNEXBWRITE__
+#define __ANNEXBWRITE__
 
 #include <ostream>
@@ -85,2 +88,4 @@
 }
 //! \}
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -53,8 +53,8 @@
   bsNALUHeader.write(0,1);                    // forbidden_zero_bit
   bsNALUHeader.write(nalu.m_nalUnitType, 6);  // nal_unit_type
-#if H_MV
-  bsNALUHeader.write(nalu.m_layerId, 6);      // layerId       
+#if NH_MV
+  bsNALUHeader.write(nalu.m_nuhLayerId, 6);      // layerId       
 #else
-  bsNALUHeader.write(nalu.m_reservedZero6Bits, 6);                   // nuh_reserved_zero_6bits
+  bsNALUHeader.write(nalu.m_nuhLayerId, 6);   // nuh_layer_id
 #endif
   bsNALUHeader.write(nalu.m_temporalId+1, 3); // nuh_temporal_id_plus1
@@ -66,5 +66,5 @@
  * emulation as required.  nalu.m_RBSPayload must be byte aligned.
  */
-void write(ostream& out, OutputNALUnit& nalu)
+Void write(ostream& out, OutputNALUnit& nalu)
 {
   writeNalUnitHeader(out, nalu);
@@ -91,37 +91,27 @@
   vector<uint8_t>& rbsp   = nalu.m_Bitstream.getFIFO();
 
-  if (rbsp.size() == 0)
+  vector<uint8_t> outputBuffer;
+  outputBuffer.resize(rbsp.size()*2+1); //there can never be enough emulation_prevention_three_bytes to require this much space
+  std::size_t outputAmount = 0;
+  Int         zeroCount    = 0;
+  for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end(); it++)
   {
-    return;
+    const uint8_t v=(*it);
+    if (zeroCount==2 && v<=3)
+    {
+      outputBuffer[outputAmount++]=emulation_prevention_three_byte[0];
+      zeroCount=0;
+    }
+
+    if (v==0)
+    {
+      zeroCount++;
+    }
+    else
+    {
+      zeroCount=0;
+    }
+    outputBuffer[outputAmount++]=v;
   }
-
-  for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end();)
-  {
-    /* 1) find the next emulated 00 00 {00,01,02,03}
-     * 2a) if not found, write all remaining bytes out, stop.
-     * 2b) otherwise, write all non-emulated bytes out
-     * 3) insert emulation_prevention_three_byte
-     */
-    vector<uint8_t>::iterator found = it;
-    do
-    {
-      /* NB, end()-1, prevents finding a trailing two byte sequence */
-      found = search_n(found, rbsp.end()-1, 2, 0);
-      found++;
-      /* if not found, found == end, otherwise found = second zero byte */
-      if (found == rbsp.end())
-        break;
-      if (*(++found) <= 3)
-        break;
-    } while (true);
-
-    it = found;
-    if (found != rbsp.end())
-    {
-      it = rbsp.insert(found, emulation_prevention_three_byte[0]);
-    }
-  }
-
-  out.write((Char*)&(*rbsp.begin()), rbsp.end() - rbsp.begin());
 
   /* 7.4.1.1
@@ -130,32 +120,9 @@
    * to 0x03 is appended to the end of the data.
    */
-  if (rbsp.back() == 0x00)
+  if (zeroCount>0)
   {
-    out.write(emulation_prevention_three_byte, 1);
+    outputBuffer[outputAmount++]=emulation_prevention_three_byte[0];
   }
-}
-
-/**
- * Write rbsp_trailing_bits to bs causing it to become byte-aligned
- */
-void writeRBSPTrailingBits(TComOutputBitstream& bs)
-{
-  bs.write( 1, 1 );
-  bs.writeAlignZero();
-}
-
-/**
- * Copy NALU from naluSrc to naluDest
- */
-void copyNaluData(OutputNALUnit& naluDest, const OutputNALUnit& naluSrc)
-{
-  naluDest.m_nalUnitType = naluSrc.m_nalUnitType;
-#if H_MV
-  naluDest.m_layerId  = naluSrc.m_layerId;
-#else
-  naluDest.m_reservedZero6Bits  = naluSrc.m_reservedZero6Bits;
-#endif
-  naluDest.m_temporalId  = naluSrc.m_temporalId;
-  naluDest.m_Bitstream   = naluSrc.m_Bitstream;
+  out.write((Char*)&(*outputBuffer.begin()), outputAmount);
 }
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/NALwrite.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/NALwrite.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -34,7 +34,10 @@
 #pragma once
 
+#ifndef __NALWRITE__
+#define __NALWRITE__
+
 #include <ostream>
 
-#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/CommonDef.h"
 #include "TLibCommon/TComBitStream.h"
 #include "TLibCommon/NAL.h"
@@ -57,10 +60,10 @@
     NalUnitType nalUnitType,
     UInt temporalID = 0,
-#if H_MV
+#if NH_MV
     Int layerId = 0)
 #else
     UInt reserved_zero_6bits = 0)
 #endif
-#if H_MV
+#if NH_MV
   : NALUnit(nalUnitType, temporalID, layerId)
 #else
@@ -80,6 +83,5 @@
 };
 
-void write(std::ostream& out, OutputNALUnit& nalu);
-void writeRBSPTrailingBits(TComOutputBitstream& bs);
+Void write(std::ostream& out, OutputNALUnit& nalu);
 
 inline NALUnitEBSP::NALUnitEBSP(OutputNALUnit& nalu)
@@ -89,5 +91,5 @@
 }
 
-void copyNaluData(OutputNALUnit& naluDest, const OutputNALUnit& naluSrc);
+//! \}
 
-//! \}
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIEncoder.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIEncoder.cpp	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIEncoder.cpp	(revision 1200)
@@ -0,0 +1,480 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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.
+ */
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/SEI.h"
+#include "TEncGOP.h"
+#include "TEncTop.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+Void SEIEncoder::initSEIActiveParameterSets (SEIActiveParameterSets *seiActiveParameterSets, const TComVPS *vps, const TComSPS *sps)
+{
+  assert (m_isInitialized);
+  assert (seiActiveParameterSets!=NULL);
+  assert (vps!=NULL);
+  assert (sps!=NULL);
+
+  seiActiveParameterSets->activeVPSId = vps->getVPSId(); 
+  seiActiveParameterSets->m_selfContainedCvsFlag = false;
+  seiActiveParameterSets->m_noParameterSetUpdateFlag = false;
+  seiActiveParameterSets->numSpsIdsMinus1 = 0;
+  seiActiveParameterSets->activeSeqParameterSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1);
+  seiActiveParameterSets->activeSeqParameterSetId[0] = sps->getSPSId();
+}
+
+Void SEIEncoder::initSEIFramePacking(SEIFramePacking *seiFramePacking, Int currPicNum)
+{
+  assert (m_isInitialized);
+  assert (seiFramePacking!=NULL);
+
+  seiFramePacking->m_arrangementId = m_pcCfg->getFramePackingArrangementSEIId();
+  seiFramePacking->m_arrangementCancelFlag = 0;
+  seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
+  assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
+  seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
+  seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
+  seiFramePacking->m_spatialFlippingFlag = 0;
+  seiFramePacking->m_frame0FlippedFlag = 0;
+  seiFramePacking->m_fieldViewsFlag = (seiFramePacking->m_arrangementType == 2);
+  seiFramePacking->m_currentFrameIsFrame0Flag = ((seiFramePacking->m_arrangementType == 5) && (currPicNum&1) );
+  seiFramePacking->m_frame0SelfContainedFlag = 0;
+  seiFramePacking->m_frame1SelfContainedFlag = 0;
+  seiFramePacking->m_frame0GridPositionX = 0;
+  seiFramePacking->m_frame0GridPositionY = 0;
+  seiFramePacking->m_frame1GridPositionX = 0;
+  seiFramePacking->m_frame1GridPositionY = 0;
+  seiFramePacking->m_arrangementReservedByte = 0;
+  seiFramePacking->m_arrangementPersistenceFlag = true;
+  seiFramePacking->m_upsampledAspectRatio = 0;
+}
+
+Void SEIEncoder::initSEISegmentedRectFramePacking(SEISegmentedRectFramePacking *seiSegmentedRectFramePacking)
+{
+  assert (m_isInitialized);
+  assert (seiSegmentedRectFramePacking!=NULL);
+
+  seiSegmentedRectFramePacking->m_arrangementCancelFlag = m_pcCfg->getSegmentedRectFramePackingArrangementSEICancel();
+  seiSegmentedRectFramePacking->m_contentInterpretationType = m_pcCfg->getSegmentedRectFramePackingArrangementSEIType();
+  seiSegmentedRectFramePacking->m_arrangementPersistenceFlag = m_pcCfg->getSegmentedRectFramePackingArrangementSEIPersistence();
+}
+
+Void SEIEncoder::initSEIDisplayOrientation(SEIDisplayOrientation* seiDisplayOrientation)
+{
+  assert (m_isInitialized);
+  assert (seiDisplayOrientation!=NULL);
+
+  seiDisplayOrientation->cancelFlag = false;
+  seiDisplayOrientation->horFlip = false;
+  seiDisplayOrientation->verFlip = false;
+  seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
+}
+
+Void SEIEncoder::initSEIToneMappingInfo(SEIToneMappingInfo *seiToneMappingInfo)
+{
+  assert (m_isInitialized);
+  assert (seiToneMappingInfo!=NULL);
+
+  seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
+  seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
+  seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
+
+  seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
+  assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
+  seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
+  assert(seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17);
+  seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
+  assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
+
+  switch( seiToneMappingInfo->m_modelId)
+  {
+  case 0:
+    {
+      seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
+      seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
+      break;
+    }
+  case 1:
+    {
+      seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
+      seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
+      break;
+    }
+  case 2:
+    {
+      UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
+      seiToneMappingInfo->m_startOfCodedInterval.resize(num);
+      Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
+      if(ptmp)
+      {
+        for(Int i=0; i<num;i++)
+        {
+          seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
+        }
+      }
+      break;
+    }
+  case 3:
+    {
+      seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
+      seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
+      seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
+      Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
+      Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
+      if(ptmpcoded&&ptmptarget)
+      {
+        for(Int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
+        {
+          seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
+          seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
+        }
+      }
+      break;
+    }
+  case 4:
+    {
+      seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
+      seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
+      assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
+      seiToneMappingInfo->m_exposureIndexIdc = m_pcCfg->getTMISEIExposurIndexIdc();
+      seiToneMappingInfo->m_exposureIndexValue = m_pcCfg->getTMISEIExposurIndexValue();
+      assert( seiToneMappingInfo->m_exposureIndexValue !=0 );
+      seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
+      seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
+      seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
+      seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
+      seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
+      assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
+      seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
+      seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
+      assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
+      seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
+      assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
+      break;
+    }
+  default:
+    {
+      assert(!"Undefined SEIToneMapModelId");
+      break;
+    }
+  }
+}
+
+Void SEIEncoder::initSEISOPDescription(SEISOPDescription *sopDescriptionSEI, TComSlice *slice, Int picInGOP, Int lastIdr, Int currGOPSize)
+{
+  assert (m_isInitialized);
+  assert (sopDescriptionSEI != NULL);
+  assert (slice != NULL);
+
+  Int sopCurrPOC = slice->getPOC();
+  sopDescriptionSEI->m_sopSeqParameterSetId = slice->getSPS()->getSPSId();
+
+  Int i = 0;
+  Int prevEntryId = picInGOP;
+  for (Int j = picInGOP; j < currGOPSize; j++)
+  {
+    Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
+    if ((sopCurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
+    {
+      sopCurrPOC += deltaPOC;
+      sopDescriptionSEI->m_sopDescVclNaluType[i] = m_pcEncGOP->getNalUnitType(sopCurrPOC, lastIdr, slice->getPic()->isField());
+      sopDescriptionSEI->m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
+      sopDescriptionSEI->m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(sopCurrPOC, j);
+      sopDescriptionSEI->m_sopDescPocDelta[i] = deltaPOC;
+
+      prevEntryId = j;
+      i++;
+    }
+  }
+
+  sopDescriptionSEI->m_numPicsInSopMinus1 = i - 1;
+}
+
+Void SEIEncoder::initSEIBufferingPeriod(SEIBufferingPeriod *bufferingPeriodSEI, TComSlice *slice)
+{
+  assert (m_isInitialized);
+  assert (bufferingPeriodSEI != NULL);
+  assert (slice != NULL);
+
+  UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
+  bufferingPeriodSEI->m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
+  bufferingPeriodSEI->m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
+  bufferingPeriodSEI->m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
+  bufferingPeriodSEI->m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
+
+  Double dTmp = (Double)slice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)slice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
+
+  UInt uiTmp = (UInt)( dTmp * 90000.0 );
+  uiInitialCpbRemovalDelay -= uiTmp;
+  uiInitialCpbRemovalDelay -= uiTmp / ( slice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
+  bufferingPeriodSEI->m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
+  bufferingPeriodSEI->m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
+  bufferingPeriodSEI->m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
+  bufferingPeriodSEI->m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
+
+  bufferingPeriodSEI->m_rapCpbParamsPresentFlag = 0;
+  //for the concatenation, it can be set to one during splicing.
+  bufferingPeriodSEI->m_concatenationFlag = 0;
+  //since the temporal layer HRD is not ready, we assumed it is fixed
+  bufferingPeriodSEI->m_auCpbRemovalDelayDelta = 1;
+  bufferingPeriodSEI->m_cpbDelayOffset = 0;
+  bufferingPeriodSEI->m_dpbDelayOffset = 0;
+}
+
+//! initialize scalable nesting SEI message.
+//! Note: The SEI message structures input into this function will become part of the scalable nesting SEI and will be 
+//!       automatically freed, when the nesting SEI is disposed.
+Void SEIEncoder::initSEIScalableNesting(SEIScalableNesting *scalableNestingSEI, SEIMessages &nestedSEIs)
+{
+  assert (m_isInitialized);
+  assert (scalableNestingSEI != NULL);
+
+  scalableNestingSEI->m_bitStreamSubsetFlag           = 1;      // If the nested SEI messages are picture buffering SEI messages, picture timing SEI messages or sub-picture timing SEI messages, bitstream_subset_flag shall be equal to 1
+  scalableNestingSEI->m_nestingOpFlag                 = 0;
+  scalableNestingSEI->m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
+  scalableNestingSEI->m_allLayersFlag                 = 0;
+  scalableNestingSEI->m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
+  scalableNestingSEI->m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
+  scalableNestingSEI->m_nestingLayerId[0]             = 0;
+
+  scalableNestingSEI->m_nestedSEIs.clear();
+  for (SEIMessages::iterator it=nestedSEIs.begin(); it!=nestedSEIs.end(); it++)
+  {
+    scalableNestingSEI->m_nestedSEIs.push_back((*it));
+  }
+}
+
+Void SEIEncoder::initSEIRecoveryPoint(SEIRecoveryPoint *recoveryPointSEI, TComSlice *slice)
+{
+  assert (m_isInitialized);
+  assert (recoveryPointSEI != NULL);
+  assert (slice != NULL);
+
+  recoveryPointSEI->m_recoveryPocCnt    = 0;
+  recoveryPointSEI->m_exactMatchingFlag = ( slice->getPOC() == 0 ) ? (true) : (false);
+  recoveryPointSEI->m_brokenLinkFlag    = false;
+}
+
+//! calculate hashes for entire reconstructed picture
+Void SEIEncoder::initDecodedPictureHashSEI(SEIDecodedPictureHash *decodedPictureHashSEI, TComPic *pcPic, std::string &rHashString, const BitDepths &bitDepths)
+{
+  assert (m_isInitialized);
+  assert (decodedPictureHashSEI!=NULL);
+  assert (pcPic!=NULL);
+
+  if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
+  {
+    decodedPictureHashSEI->method = SEIDecodedPictureHash::MD5;
+    UInt numChar=calcMD5(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
+    rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
+  }
+  else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+  {
+    decodedPictureHashSEI->method = SEIDecodedPictureHash::CRC;
+    UInt numChar=calcCRC(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
+    rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
+  }
+  else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+  {
+    decodedPictureHashSEI->method = SEIDecodedPictureHash::CHECKSUM;
+    UInt numChar=calcChecksum(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
+    rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
+  }
+}
+
+Void SEIEncoder::initTemporalLevel0IndexSEI(SEITemporalLevel0Index *temporalLevel0IndexSEI, TComSlice *slice)
+{
+  assert (m_isInitialized);
+  assert (temporalLevel0IndexSEI!=NULL);
+  assert (slice!=NULL);
+
+  if (slice->getRapPicFlag())
+  {
+    m_tl0Idx = 0;
+    m_rapIdx = (m_rapIdx + 1) & 0xFF;
+  }
+  else
+  {
+    m_tl0Idx = (m_tl0Idx + (slice->getTLayer() ? 0 : 1)) & 0xFF;
+  }
+  temporalLevel0IndexSEI->tl0Idx = m_tl0Idx;
+  temporalLevel0IndexSEI->rapIdx = m_rapIdx;
+}
+
+Void SEIEncoder::initSEITempMotionConstrainedTileSets (SEITempMotionConstrainedTileSets *sei, const TComPPS *pps)
+{
+  assert (m_isInitialized);
+  assert (sei!=NULL);
+  assert (pps!=NULL);
+
+  if(pps->getTilesEnabledFlag())
+  {
+    sei->m_mc_all_tiles_exact_sample_value_match_flag = false;
+    sei->m_each_tile_one_tile_set_flag                = false;
+    sei->m_limited_tile_set_display_flag              = false;
+    sei->setNumberOfTileSets((pps->getNumTileColumnsMinus1() + 1) * (pps->getNumTileRowsMinus1() + 1));
+
+    for(Int i=0; i < sei->getNumberOfTileSets(); i++)
+    {
+      sei->tileSetData(i).m_mcts_id = i;  //depends the application;
+      sei->tileSetData(i).setNumberOfTileRects(1);
+
+      for(Int j=0; j<sei->tileSetData(i).getNumberOfTileRects(); j++)
+      {
+        sei->tileSetData(i).topLeftTileIndex(j)     = i+j;
+        sei->tileSetData(i).bottomRightTileIndex(j) = i+j;
+      }
+
+      sei->tileSetData(i).m_exact_sample_value_match_flag    = false;
+      sei->tileSetData(i).m_mcts_tier_level_idc_present_flag = false;
+    }
+  }
+  else
+  {
+    assert(!"Tile is not enabled");
+  }
+}
+
+Void SEIEncoder::initSEIKneeFunctionInfo(SEIKneeFunctionInfo *seiKneeFunctionInfo)
+{
+  assert (m_isInitialized);
+  assert (seiKneeFunctionInfo!=NULL);
+
+  seiKneeFunctionInfo->m_kneeId = m_pcCfg->getKneeSEIId();
+  seiKneeFunctionInfo->m_kneeCancelFlag = m_pcCfg->getKneeSEICancelFlag();
+  if ( !seiKneeFunctionInfo->m_kneeCancelFlag )
+  {
+    seiKneeFunctionInfo->m_kneePersistenceFlag = m_pcCfg->getKneeSEIPersistenceFlag();
+    seiKneeFunctionInfo->m_kneeInputDrange = m_pcCfg->getKneeSEIInputDrange();
+    seiKneeFunctionInfo->m_kneeInputDispLuminance = m_pcCfg->getKneeSEIInputDispLuminance();
+    seiKneeFunctionInfo->m_kneeOutputDrange = m_pcCfg->getKneeSEIOutputDrange();
+    seiKneeFunctionInfo->m_kneeOutputDispLuminance = m_pcCfg->getKneeSEIOutputDispLuminance();
+
+    seiKneeFunctionInfo->m_kneeNumKneePointsMinus1 = m_pcCfg->getKneeSEINumKneePointsMinus1();
+    Int* piInputKneePoint  = m_pcCfg->getKneeSEIInputKneePoint();
+    Int* piOutputKneePoint = m_pcCfg->getKneeSEIOutputKneePoint();
+    if(piInputKneePoint&&piOutputKneePoint)
+    {
+      seiKneeFunctionInfo->m_kneeInputKneePoint.resize(seiKneeFunctionInfo->m_kneeNumKneePointsMinus1+1);
+      seiKneeFunctionInfo->m_kneeOutputKneePoint.resize(seiKneeFunctionInfo->m_kneeNumKneePointsMinus1+1);
+      for(Int i=0; i<=seiKneeFunctionInfo->m_kneeNumKneePointsMinus1; i++)
+      {
+        seiKneeFunctionInfo->m_kneeInputKneePoint[i] = piInputKneePoint[i];
+        seiKneeFunctionInfo->m_kneeOutputKneePoint[i] = piOutputKneePoint[i];
+      }
+    }
+  }
+}
+
+Void SEIEncoder::initSEIChromaSamplingFilterHint(SEIChromaSamplingFilterHint *seiChromaSamplingFilterHint, Int iHorFilterIndex, Int iVerFilterIndex)
+{
+  assert (m_isInitialized);
+  assert (seiChromaSamplingFilterHint!=NULL);
+
+  seiChromaSamplingFilterHint->m_verChromaFilterIdc = iVerFilterIndex;
+  seiChromaSamplingFilterHint->m_horChromaFilterIdc = iHorFilterIndex;
+  seiChromaSamplingFilterHint->m_verFilteringProcessFlag = 1;
+  seiChromaSamplingFilterHint->m_targetFormatIdc = 3;
+  seiChromaSamplingFilterHint->m_perfectReconstructionFlag = false;
+  if(seiChromaSamplingFilterHint->m_verChromaFilterIdc == 1)
+  {
+    seiChromaSamplingFilterHint->m_numVerticalFilters = 1;
+    seiChromaSamplingFilterHint->m_verTapLengthMinus1 = (Int*)malloc(seiChromaSamplingFilterHint->m_numVerticalFilters * sizeof(Int));
+    seiChromaSamplingFilterHint->m_verFilterCoeff =    (Int**)malloc(seiChromaSamplingFilterHint->m_numVerticalFilters * sizeof(Int*));
+    for(Int i = 0; i < seiChromaSamplingFilterHint->m_numVerticalFilters; i ++)
+    {
+      seiChromaSamplingFilterHint->m_verTapLengthMinus1[i] = 0;
+      seiChromaSamplingFilterHint->m_verFilterCoeff[i] = (Int*)malloc(seiChromaSamplingFilterHint->m_verTapLengthMinus1[i] * sizeof(Int));
+      for(Int j = 0; j < seiChromaSamplingFilterHint->m_verTapLengthMinus1[i]; j ++)
+      {
+        seiChromaSamplingFilterHint->m_verFilterCoeff[i][j] = 0;
+      }
+    }
+  }
+  else
+  {
+    seiChromaSamplingFilterHint->m_numVerticalFilters = 0;
+    seiChromaSamplingFilterHint->m_verTapLengthMinus1 = NULL;
+    seiChromaSamplingFilterHint->m_verFilterCoeff = NULL;
+  }
+  if(seiChromaSamplingFilterHint->m_horChromaFilterIdc == 1)
+  {
+    seiChromaSamplingFilterHint->m_numHorizontalFilters = 1;
+    seiChromaSamplingFilterHint->m_horTapLengthMinus1 = (Int*)malloc(seiChromaSamplingFilterHint->m_numHorizontalFilters * sizeof(Int));
+    seiChromaSamplingFilterHint->m_horFilterCoeff = (Int**)malloc(seiChromaSamplingFilterHint->m_numHorizontalFilters * sizeof(Int*));
+    for(Int i = 0; i < seiChromaSamplingFilterHint->m_numHorizontalFilters; i ++)
+    {
+      seiChromaSamplingFilterHint->m_horTapLengthMinus1[i] = 0;
+      seiChromaSamplingFilterHint->m_horFilterCoeff[i] = (Int*)malloc(seiChromaSamplingFilterHint->m_horTapLengthMinus1[i] * sizeof(Int));
+      for(Int j = 0; j < seiChromaSamplingFilterHint->m_horTapLengthMinus1[i]; j ++)
+      {
+        seiChromaSamplingFilterHint->m_horFilterCoeff[i][j] = 0;
+      }
+    }
+  }
+  else
+  {
+    seiChromaSamplingFilterHint->m_numHorizontalFilters = 0;
+    seiChromaSamplingFilterHint->m_horTapLengthMinus1 = NULL;
+    seiChromaSamplingFilterHint->m_horFilterCoeff = NULL;
+  }
+}
+
+Void SEIEncoder::initSEITimeCode(SEITimeCode *seiTimeCode)
+{
+  assert (m_isInitialized);
+  assert (seiTimeCode!=NULL);
+  //  Set data as per command line options
+  seiTimeCode->numClockTs = m_pcCfg->getNumberOfTimesets();
+  for(Int i = 0; i < seiTimeCode->numClockTs; i++)
+  {
+    seiTimeCode->timeSetArray[i] = m_pcCfg->getTimeSet(i);
+  }
+}
+
+#if NH_MV
+Void SEIEncoder::initSEISubBitstreamProperty(SEISubBitstreamProperty *seiSubBitstreamProperty, const TComSPS *sps)
+{
+  seiSubBitstreamProperty->m_activeVpsId = sps->getVPSId();
+  /* These values can be determined by the encoder; for now we will use the input parameter */  
+  seiSubBitstreamProperty->m_numAdditionalSubStreams = m_pcCfg->getNumAdditionalSubStreams();
+  seiSubBitstreamProperty->m_subBitstreamMode        = m_pcCfg->getSubBitstreamMode();
+  seiSubBitstreamProperty->m_outputLayerSetIdxToVps  = m_pcCfg->getOutputLayerSetIdxToVps();
+  seiSubBitstreamProperty->m_highestSublayerId       = m_pcCfg->getHighestSublayerId();
+  seiSubBitstreamProperty->m_avgBitRate              = m_pcCfg->getAvgBitRate();
+  seiSubBitstreamProperty->m_maxBitRate              = m_pcCfg->getMaxBitRate();  
+}
+#endif
+
+//! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIEncoder.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIEncoder.h	(revision 1200)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIEncoder.h	(revision 1200)
@@ -0,0 +1,105 @@
+/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * 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.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * 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 HOLDER 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.
+ */
+
+#pragma once
+
+#ifndef __SEIENCODER__
+#define __SEIENCODER__
+
+#include "TLibCommon/SEI.h"
+
+// forward declarations
+class TEncCfg;
+class TEncTop;
+class TEncGOP;
+
+
+//! Initializes different SEI message types based on given encoder configuration parameters 
+class SEIEncoder
+{
+public:
+  SEIEncoder()
+    :m_pcCfg(NULL)
+    ,m_pcEncTop(NULL)
+    ,m_pcEncGOP(NULL)
+    ,m_tl0Idx(0)
+    ,m_rapIdx(0)
+    ,m_isInitialized(false)
+  {};
+  virtual ~SEIEncoder(){};
+
+  Void init(TEncCfg* encCfg, TEncTop *encTop, TEncGOP *encGOP) 
+  { 
+    m_pcCfg = encCfg;
+    m_pcEncGOP = encGOP;
+    m_pcEncTop = encTop;
+    m_isInitialized = true;
+  };
+
+  // leading SEIs
+  Void initSEIActiveParameterSets (SEIActiveParameterSets *sei, const TComVPS *vps, const TComSPS *sps);
+  Void initSEIFramePacking(SEIFramePacking *sei, Int currPicNum);
+  Void initSEIDisplayOrientation(SEIDisplayOrientation *sei);
+  Void initSEIToneMappingInfo(SEIToneMappingInfo *sei);
+  Void initSEISOPDescription(SEISOPDescription *sei, TComSlice *slice, Int picInGOP, Int lastIdr, Int currGOPSize);
+  Void initSEIBufferingPeriod(SEIBufferingPeriod *sei, TComSlice *slice);
+  Void initSEIScalableNesting(SEIScalableNesting *sei, SEIMessages &nestedSEIs);
+  Void initSEIRecoveryPoint(SEIRecoveryPoint *sei, TComSlice *slice);
+  Void initSEISegmentedRectFramePacking(SEISegmentedRectFramePacking *sei);
+  Void initSEITempMotionConstrainedTileSets (SEITempMotionConstrainedTileSets *sei, const TComPPS *pps);
+  Void initSEIKneeFunctionInfo(SEIKneeFunctionInfo *sei);
+  Void initSEIChromaSamplingFilterHint(SEIChromaSamplingFilterHint *sei, Int iHorFilterIndex, Int iVerFilterIndex);
+  Void initSEITimeCode(SEITimeCode *sei);
+
+  // trailing SEIs
+  Void initDecodedPictureHashSEI(SEIDecodedPictureHash *sei, TComPic *pcPic, std::string &rHashString, const BitDepths &bitDepths);
+  Void initTemporalLevel0IndexSEI(SEITemporalLevel0Index *sei, TComSlice *slice);
+#if NH_MV
+  Void initSEISubBitstreamProperty(SEISubBitstreamProperty *seiSubBitstreamProperty, const TComSPS *sps);
+#endif
+private:
+  TEncCfg* m_pcCfg;
+  TEncTop* m_pcEncTop;
+  TEncGOP* m_pcEncGOP;
+
+  // for temporal level 0 index SEI
+  UInt m_tl0Idx;
+  UInt m_rapIdx;
+
+  Bool m_isInitialized;
+};
+
+
+//! \}
+
+#endif // __SEIENCODER__
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,4 +36,5 @@
 #include "TLibCommon/SEI.h"
 #include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComPicYuv.h"
 #include "SEIwrite.h"
 
@@ -49,61 +50,9 @@
 Void  xTraceSEIMessageType(SEI::PayloadType payloadType)
 {
-  switch (payloadType)
-  {
-  case SEI::DECODED_PICTURE_HASH:
-    fprintf( g_hTrace, "=========== Decoded picture hash SEI message ===========\n");
-    break;
-  case SEI::USER_DATA_UNREGISTERED:
-    fprintf( g_hTrace, "=========== User Data Unregistered SEI message ===========\n");
-    break;
-  case SEI::ACTIVE_PARAMETER_SETS:
-    fprintf( g_hTrace, "=========== Active Parameter sets SEI message ===========\n");
-    break;
-  case SEI::BUFFERING_PERIOD:
-    fprintf( g_hTrace, "=========== Buffering period SEI message ===========\n");
-    break;
-  case SEI::PICTURE_TIMING:
-    fprintf( g_hTrace, "=========== Picture timing SEI message ===========\n");
-    break;
-  case SEI::RECOVERY_POINT:
-    fprintf( g_hTrace, "=========== Recovery point SEI message ===========\n");
-    break;
-  case SEI::FRAME_PACKING:
-    fprintf( g_hTrace, "=========== Frame Packing Arrangement SEI message ===========\n");
-    break;
-  case SEI::DISPLAY_ORIENTATION:
-    fprintf( g_hTrace, "=========== Display Orientation SEI message ===========\n");
-    break;
-  case SEI::TEMPORAL_LEVEL0_INDEX:
-    fprintf( g_hTrace, "=========== Temporal Level Zero Index SEI message ===========\n");
-    break;
-  case SEI::REGION_REFRESH_INFO:
-    fprintf( g_hTrace, "=========== Gradual Decoding Refresh Information SEI message ===========\n");
-    break;
-  case SEI::DECODING_UNIT_INFO:
-    fprintf( g_hTrace, "=========== Decoding Unit Information SEI message ===========\n");
-    break;
-  case SEI::TONE_MAPPING_INFO:
-    fprintf( g_hTrace, "=========== Tone Mapping Info SEI message ===========\n");
-    break;
-  case SEI::SOP_DESCRIPTION:
-    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
-    break;
-  case SEI::SCALABLE_NESTING:
-    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
-    break;
-#if H_MV
-    case SEI::SUB_BITSTREAM_PROPERTY:
-    fprintf( g_hTrace, "=========== Sub-bitstream property SEI message ===========\n");
-    break;
+  fprintf( g_hTrace, "=========== %s SEI message ===========\n", SEI::getSEIMessageString(payloadType));
+}
 #endif
-  default:
-    fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
-    break;
-  }
-}
-#endif
-
-void SEIWriter::xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps)
+
+Void SEIWriter::xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, const TComSPS *sps)
 {
   switch (sei.payloadType())
@@ -113,6 +62,6 @@
     break;
   case SEI::ACTIVE_PARAMETER_SETS:
-    xWriteSEIActiveParameterSets(*static_cast<const SEIActiveParameterSets*>(& sei)); 
-    break; 
+    xWriteSEIActiveParameterSets(*static_cast<const SEIActiveParameterSets*>(& sei));
+    break;
   case SEI::DECODING_UNIT_INFO:
     xWriteSEIDecodingUnitInfo(*static_cast<const SEIDecodingUnitInfo*>(& sei), sps);
@@ -133,4 +82,7 @@
     xWriteSEIFramePacking(*static_cast<const SEIFramePacking*>(&sei));
     break;
+  case SEI::SEGM_RECT_FRAME_PACKING:
+    xWriteSEISegmentedRectFramePacking(*static_cast<const SEISegmentedRectFramePacking*>(&sei));
+    break;
   case SEI::DISPLAY_ORIENTATION:
     xWriteSEIDisplayOrientation(*static_cast<const SEIDisplayOrientation*>(&sei));
@@ -142,4 +94,7 @@
     xWriteSEIGradualDecodingRefreshInfo(*static_cast<const SEIGradualDecodingRefreshInfo*>(&sei));
     break;
+  case SEI::NO_DISPLAY:
+    xWriteSEINoDisplay(*static_cast<const SEINoDisplay*>(&sei));
+    break;
   case SEI::TONE_MAPPING_INFO:
     xWriteSEIToneMappingInfo(*static_cast<const SEIToneMappingInfo*>(&sei));
@@ -151,67 +106,89 @@
     xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), sps);
     break;
-#if H_MV
+  case SEI::CHROMA_SAMPLING_FILTER_HINT:
+    xWriteSEIChromaSamplingFilterHint(*static_cast<const SEIChromaSamplingFilterHint*>(&sei)/*, sps*/);
+    break;
+  case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:
+    xWriteSEITempMotionConstrainedTileSets(*static_cast<const SEITempMotionConstrainedTileSets*>(&sei));
+    break;
+  case SEI::TIME_CODE:
+    xWriteSEITimeCode(*static_cast<const SEITimeCode*>(&sei));
+    break;
+  case SEI::KNEE_FUNCTION_INFO:
+    xWriteSEIKneeFunctionInfo(*static_cast<const SEIKneeFunctionInfo*>(&sei));
+    break;
+  case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
+    xWriteSEIMasteringDisplayColourVolume(*static_cast<const SEIMasteringDisplayColourVolume*>(&sei));
+    break;
+#if NH_MV
    case SEI::SUB_BITSTREAM_PROPERTY:
    xWriteSEISubBitstreamProperty(*static_cast<const SEISubBitstreamProperty*>(&sei));
    break;
 #endif
+
   default:
     assert(!"Unhandled SEI message");
-  }
+    break;
+  }
+  xWriteByteAlign();
 }
 
 /**
- * marshal a single SEI message sei, storing the marshalled representation
- * in bitstream bs.
+ * marshal all SEI messages in provided list into one bitstream bs
  */
-Void SEIWriter::writeSEImessage(TComBitIf& bs, const SEI& sei, TComSPS *sps)
-{
-  /* calculate how large the payload data is */
-  /* TODO: this would be far nicer if it used vectored buffers */
-  TComBitCounter bs_count;
-  bs_count.resetBits();
-  setBitstream(&bs_count);
-
-
-#if ENC_DEC_TRACE
-  Bool traceEnable = g_HLSTraceEnable;
-  g_HLSTraceEnable = false;
-#endif
-  xWriteSEIpayloadData(bs_count, sei, sps);
-#if ENC_DEC_TRACE
-  g_HLSTraceEnable = traceEnable;
-#endif
-
-  UInt payload_data_num_bits = bs_count.getNumberOfWrittenBits();
-  assert(0 == payload_data_num_bits % 8);
-
-  setBitstream(&bs);
-
+Void SEIWriter::writeSEImessages(TComBitIf& bs, const SEIMessages &seiList, const TComSPS *sps, Bool isNested)
+{
 #if ENC_DEC_TRACE
   if (g_HLSTraceEnable)
-  xTraceSEIHeader();
+    xTraceSEIHeader();
 #endif
 
-  UInt payloadType = sei.payloadType();
-  for (; payloadType >= 0xff; payloadType -= 0xff)
-  {
-    WRITE_CODE(0xff, 8, "payload_type");
-  }
-  WRITE_CODE(payloadType, 8, "payload_type");
-
-  UInt payloadSize = payload_data_num_bits/8;
-  for (; payloadSize >= 0xff; payloadSize -= 0xff)
-  {
-    WRITE_CODE(0xff, 8, "payload_size");
-  }
-  WRITE_CODE(payloadSize, 8, "payload_size");
-
-  /* payloadData */
+  TComBitCounter bs_count;
+
+  for (SEIMessages::const_iterator sei=seiList.begin(); sei!=seiList.end(); sei++)
+  {
+    // calculate how large the payload data is
+    // TODO: this would be far nicer if it used vectored buffers
+    bs_count.resetBits();
+    setBitstream(&bs_count);
+
 #if ENC_DEC_TRACE
-  if (g_HLSTraceEnable)
-  xTraceSEIMessageType(sei.payloadType());
+    Bool traceEnable = g_HLSTraceEnable;
+    g_HLSTraceEnable = false;
 #endif
-
-  xWriteSEIpayloadData(bs, sei, sps);
+    xWriteSEIpayloadData(bs_count, **sei, sps);
+#if ENC_DEC_TRACE
+    g_HLSTraceEnable = traceEnable;
+#endif
+    UInt payload_data_num_bits = bs_count.getNumberOfWrittenBits();
+    assert(0 == payload_data_num_bits % 8);
+
+    setBitstream(&bs);
+    UInt payloadType = (*sei)->payloadType();
+    for (; payloadType >= 0xff; payloadType -= 0xff)
+    {
+      WRITE_CODE(0xff, 8, "payload_type");
+    }
+    WRITE_CODE(payloadType, 8, "payload_type");
+
+    UInt payloadSize = payload_data_num_bits/8;
+    for (; payloadSize >= 0xff; payloadSize -= 0xff)
+    {
+      WRITE_CODE(0xff, 8, "payload_size");
+    }
+    WRITE_CODE(payloadSize, 8, "payload_size");
+
+    /* payloadData */
+#if ENC_DEC_TRACE
+    if (g_HLSTraceEnable)
+      xTraceSEIMessageType((*sei)->payloadType());
+#endif
+
+    xWriteSEIpayloadData(bs, **sei, sps);
+  }
+  if (!isNested)
+  {
+    xWriteRbspTrailingBits();
+  }
 }
 
@@ -222,5 +199,5 @@
 Void SEIWriter::xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei)
 {
-  for (UInt i = 0; i < 16; i++)
+  for (UInt i = 0; i < ISO_IEC_11578_LEN; i++)
   {
     WRITE_CODE(sei.uuid_iso_iec_11578[i], 8 , "sei.uuid_iso_iec_11578[i]");
@@ -239,26 +216,19 @@
 Void SEIWriter::xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei)
 {
-  UInt val;
-
-  WRITE_CODE(sei.method, 8, "hash_type");
-
-  for(Int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
-  {
-    if(sei.method == SEIDecodedPictureHash::MD5)
-    {
-      for (UInt i = 0; i < 16; i++)
-      {
-        WRITE_CODE(sei.digest[yuvIdx][i], 8, "picture_md5");
-      }
-    }
-    else if(sei.method == SEIDecodedPictureHash::CRC)
-    {
-      val = (sei.digest[yuvIdx][0] << 8)  + sei.digest[yuvIdx][1];
-      WRITE_CODE(val, 16, "picture_crc");
-    }
-    else if(sei.method == SEIDecodedPictureHash::CHECKSUM)
-    {
-      val = (sei.digest[yuvIdx][0] << 24)  + (sei.digest[yuvIdx][1] << 16) + (sei.digest[yuvIdx][2] << 8) + sei.digest[yuvIdx][3];
-      WRITE_CODE(val, 32, "picture_checksum");
+  const Char *traceString="\0";
+  switch (sei.method)
+  {
+    case SEIDecodedPictureHash::MD5: traceString="picture_md5"; break;
+    case SEIDecodedPictureHash::CRC: traceString="picture_crc"; break;
+    case SEIDecodedPictureHash::CHECKSUM: traceString="picture_checksum"; break;
+    default: assert(false); break;
+  }
+
+  if (traceString != 0) //use of this variable is needed to avoid a compiler error with G++ 4.6.1
+  {
+    WRITE_CODE(sei.method, 8, "hash_type");
+    for(UInt i=0; i<UInt(sei.m_pictureHash.hash.size()); i++)
+    {
+      WRITE_CODE(sei.m_pictureHash.hash[i], 8, traceString);
     }
   }
@@ -270,22 +240,21 @@
   WRITE_FLAG(sei.m_selfContainedCvsFlag,     "self_contained_cvs_flag");
   WRITE_FLAG(sei.m_noParameterSetUpdateFlag, "no_parameter_set_update_flag");
-  WRITE_UVLC(sei.numSpsIdsMinus1,    "num_sps_ids_minus1");
+  WRITE_UVLC(sei.numSpsIdsMinus1,            "num_sps_ids_minus1");
 
   assert (sei.activeSeqParameterSetId.size() == (sei.numSpsIdsMinus1 + 1));
 
   for (Int i = 0; i < sei.activeSeqParameterSetId.size(); i++)
-    {
+  {
     WRITE_UVLC(sei.activeSeqParameterSetId[i], "active_seq_parameter_set_id"); 
   }
-  xWriteByteAlign();
-}
-
-Void SEIWriter::xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, TComSPS *sps)
-{
-  TComVUI *vui = sps->getVuiParameters();
+}
+
+Void SEIWriter::xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, const TComSPS *sps)
+{
+  const TComVUI *vui = sps->getVuiParameters();
   WRITE_UVLC(sei.m_decodingUnitIdx, "decoding_unit_idx");
   if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
   {
-    WRITE_CODE( sei.m_duSptCpbRemovalDelay, (vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1), "du_spt_cpb_removal_delay");
+    WRITE_CODE( sei.m_duSptCpbRemovalDelay, (vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1), "du_spt_cpb_removal_delay_increment");
   }
   WRITE_FLAG( sei.m_dpbOutputDuDelayPresentFlag, "dpb_output_du_delay_present_flag");
@@ -294,12 +263,11 @@
     WRITE_CODE(sei.m_picSptDpbOutputDuDelay, vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, "pic_spt_dpb_output_du_delay");
   }
-  xWriteByteAlign();
-}
-
-Void SEIWriter::xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, TComSPS *sps)
+}
+
+Void SEIWriter::xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, const TComSPS *sps)
 {
   Int i, nalOrVcl;
-  TComVUI *vui = sps->getVuiParameters();
-  TComHRD *hrd = vui->getHrdParameters();
+  const TComVUI *vui = sps->getVuiParameters();
+  const TComHRD *hrd = vui->getHrdParameters();
 
   WRITE_UVLC( sei.m_bpSeqParameterSetId, "bp_seq_parameter_set_id" );
@@ -332,11 +300,10 @@
     }
   }
-  xWriteByteAlign();
-}
-Void SEIWriter::xWriteSEIPictureTiming(const SEIPictureTiming& sei,  TComSPS *sps)
+}
+Void SEIWriter::xWriteSEIPictureTiming(const SEIPictureTiming& sei, const TComSPS *sps)
 {
   Int i;
-  TComVUI *vui = sps->getVuiParameters();
-  TComHRD *hrd = vui->getHrdParameters();
+  const TComVUI *vui = sps->getVuiParameters();
+  const TComHRD *hrd = vui->getHrdParameters();
 
   if( vui->getFrameFieldInfoPresentFlag() )
@@ -373,5 +340,4 @@
     }
   }
-  xWriteByteAlign();
 }
 Void SEIWriter::xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei)
@@ -380,5 +346,4 @@
   WRITE_FLAG( sei.m_exactMatchingFlag, "exact_matching_flag" );
   WRITE_FLAG( sei.m_brokenLinkFlag,    "broken_link_flag"    );
-  xWriteByteAlign();
 }
 Void SEIWriter::xWriteSEIFramePacking(const SEIFramePacking& sei)
@@ -387,5 +352,6 @@
   WRITE_FLAG( sei.m_arrangementCancelFlag,          "frame_packing_arrangement_cancel_flag" );
 
-  if( sei.m_arrangementCancelFlag == 0 ) {
+  if( sei.m_arrangementCancelFlag == 0 )
+  {
     WRITE_CODE( sei.m_arrangementType, 7,           "frame_packing_arrangement_type" );
 
@@ -413,6 +379,14 @@
 
   WRITE_FLAG( sei.m_upsampledAspectRatio,           "upsampled_aspect_ratio" );
-
-  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEISegmentedRectFramePacking(const SEISegmentedRectFramePacking& sei)
+{
+  WRITE_FLAG( sei.m_arrangementCancelFlag,          "segmented_rect_frame_packing_arrangement_cancel_flag" );
+  if( sei.m_arrangementCancelFlag == 0 ) 
+  {
+    WRITE_CODE( sei.m_contentInterpretationType, 2, "segmented_rect_content_interpretation_type" );
+    WRITE_FLAG( sei.m_arrangementPersistenceFlag,   "segmented_rect_frame_packing_arrangement_persistence" );
+  }
 }
 
@@ -422,5 +396,5 @@
   WRITE_UVLC( sei.m_toneMapId,                    "tone_map_id" );
   WRITE_FLAG( sei.m_toneMapCancelFlag,            "tone_map_cancel_flag" );
-  if( !sei.m_toneMapCancelFlag ) 
+  if( !sei.m_toneMapCancelFlag )
   {
     WRITE_FLAG( sei.m_toneMapPersistenceFlag,     "tone_map_persistence_flag" );
@@ -490,6 +464,4 @@
     }//switch m_modelId
   }//if(!sei.m_toneMapCancelFlag)
-
-  xWriteByteAlign();
 }
 
@@ -504,5 +476,4 @@
     WRITE_FLAG( sei.persistenceFlag,          "display_orientation_persistence_flag" );
   }
-  xWriteByteAlign();
 }
 
@@ -511,5 +482,4 @@
   WRITE_CODE( sei.tl0Idx, 8 , "tl0_idx" );
   WRITE_CODE( sei.rapIdx, 8 , "rap_idx" );
-  xWriteByteAlign();
 }
 
@@ -517,5 +487,8 @@
 {
   WRITE_FLAG( sei.m_gdrForegroundFlag, "gdr_foreground_flag");
-  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEINoDisplay(const SEINoDisplay& /*sei*/)
+{
 }
 
@@ -537,9 +510,7 @@
     }
   }
-
-  xWriteByteAlign();
-}
-
-Void SEIWriter::xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps)
+}
+
+Void SEIWriter::xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, const TComSPS *sps)
 {
   WRITE_FLAG( sei.m_bitStreamSubsetFlag,             "bitstream_subset_flag"         );
@@ -548,9 +519,8 @@
   {
     WRITE_FLAG( sei.m_defaultOpFlag,                 "default_op_flag"               );
-    WRITE_UVLC( sei.m_nestingNumOpsMinus1,           "nesting_num_ops"               );
+    WRITE_UVLC( sei.m_nestingNumOpsMinus1,           "nesting_num_ops_minus1"        );
     for (UInt i = (sei.m_defaultOpFlag ? 1 : 0); i <= sei.m_nestingNumOpsMinus1; i++)
     {
-      WRITE_CODE( sei.m_nestingNoOpMaxTemporalIdPlus1, 3, "nesting_no_op_max_temporal_id" );
-      WRITE_CODE( sei.m_nestingMaxTemporalIdPlus1[i], 3,  "nesting_max_temporal_id"       );
+      WRITE_CODE( sei.m_nestingMaxTemporalIdPlus1[i], 3,  "nesting_max_temporal_id_plus1" );
       WRITE_UVLC( sei.m_nestingOpIdx[i],                  "nesting_op_idx"                );
     }
@@ -561,6 +531,6 @@
     if (!sei.m_allLayersFlag)
     {
-      WRITE_CODE( sei.m_nestingNoOpMaxTemporalIdPlus1, 3, "nesting_no_op_max_temporal_id" );
-      WRITE_UVLC( sei.m_nestingNumLayersMinus1,           "nesting_num_layers"            );
+      WRITE_CODE( sei.m_nestingNoOpMaxTemporalIdPlus1, 3, "nesting_no_op_max_temporal_id_plus1" );
+      WRITE_UVLC( sei.m_nestingNumLayersMinus1,           "nesting_num_layers"                  );
       for (UInt i = 0; i <= sei.m_nestingNumLayersMinus1; i++)
       {
@@ -569,5 +539,5 @@
     }
   }
- 
+
   // byte alignment
   while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
@@ -577,11 +547,205 @@
 
   // write nested SEI messages
-  for (SEIMessages::const_iterator it = sei.m_nestedSEIs.begin(); it != sei.m_nestedSEIs.end(); it++)
-  {
-    writeSEImessage(bs, *(*it), sps);
-  }
-}
-
-#if H_MV
+  writeSEImessages(bs, sei.m_nestedSEIs, sps, true);
+}
+
+Void SEIWriter::xWriteSEITempMotionConstrainedTileSets(const SEITempMotionConstrainedTileSets& sei)
+{
+  //UInt code;
+  WRITE_FLAG((sei.m_mc_all_tiles_exact_sample_value_match_flag ? 1 : 0), "mc_all_tiles_exact_sample_value_match_flag"); 
+  WRITE_FLAG((sei.m_each_tile_one_tile_set_flag                ? 1 : 0), "each_tile_one_tile_set_flag"               );
+
+  if(!sei.m_each_tile_one_tile_set_flag)
+  {
+    WRITE_FLAG((sei.m_limited_tile_set_display_flag ? 1 : 0), "limited_tile_set_display_flag");
+    WRITE_UVLC((sei.getNumberOfTileSets() - 1),               "num_sets_in_message_minus1"   );
+
+    if(sei.getNumberOfTileSets() > 0)
+    {
+      for(Int i = 0; i < sei.getNumberOfTileSets(); i++)
+      {
+        WRITE_UVLC(sei.tileSetData(i).m_mcts_id, "mcts_id");
+
+        if(sei.m_limited_tile_set_display_flag)
+        { 
+          WRITE_FLAG((sei.tileSetData(i).m_display_tile_set_flag ? 1 : 0), "display_tile_set_flag");  
+        }
+
+        WRITE_UVLC((sei.tileSetData(i).getNumberOfTileRects() - 1), "num_tile_rects_in_set_minus1"); 
+        
+        for(Int j = 0; j < sei.tileSetData(i).getNumberOfTileRects(); j++)
+        {
+          WRITE_UVLC(sei.tileSetData(i).topLeftTileIndex    (j), "top_left_tile_index");  
+          WRITE_UVLC(sei.tileSetData(i).bottomRightTileIndex(j), "bottom_right_tile_index");  
+        }
+
+        if(!sei.m_mc_all_tiles_exact_sample_value_match_flag)
+        {
+          WRITE_FLAG((sei.tileSetData(i).m_exact_sample_value_match_flag ? 1 : 0), "exact_sample_value_match_flag");  
+        }
+
+        WRITE_FLAG((sei.tileSetData(i).m_mcts_tier_level_idc_present_flag ? 1 : 0), "mcts_tier_level_idc_present_flag");
+
+        if(sei.tileSetData(i).m_mcts_tier_level_idc_present_flag)
+        {
+          WRITE_FLAG((sei.tileSetData(i).m_mcts_tier_flag ? 1 : 0), "mcts_tier_flag");
+          WRITE_CODE( sei.tileSetData(i).m_mcts_level_idc, 8,       "mcts_level_idc"); 
+        }
+      }
+    }
+  }
+  else
+  {
+    WRITE_FLAG((sei.m_max_mcs_tier_level_idc_present_flag ? 1 : 0), "max_mcs_tier_level_idc_present_flag");
+
+    if(sei.m_max_mcs_tier_level_idc_present_flag)
+    {
+      WRITE_FLAG((sei.m_max_mcts_tier_flag ? 1 : 0), "max_mcts_tier_flag");  
+      WRITE_CODE( sei.m_max_mcts_level_idc, 8,       "max_mcts_level_idc"); 
+    }
+  }
+}
+
+Void SEIWriter::xWriteSEITimeCode(const SEITimeCode& sei)
+{
+  WRITE_CODE(sei.numClockTs, 2, "num_clock_ts");
+  for(Int i = 0; i < sei.numClockTs; i++)
+  {
+    const TComSEITimeSet &currentTimeSet = sei.timeSetArray[i];
+    WRITE_FLAG(currentTimeSet.clockTimeStampFlag, "clock_time_stamp_flag");
+    if(currentTimeSet.clockTimeStampFlag)
+    {
+      WRITE_FLAG(currentTimeSet.numUnitFieldBasedFlag, "units_field_based_flag");
+      WRITE_CODE(currentTimeSet.countingType, 5, "counting_type");
+      WRITE_FLAG(currentTimeSet.fullTimeStampFlag, "full_timestamp_flag");
+      WRITE_FLAG(currentTimeSet.discontinuityFlag, "discontinuity_flag");
+      WRITE_FLAG(currentTimeSet.cntDroppedFlag, "cnt_dropped_flag");
+      WRITE_CODE(currentTimeSet.numberOfFrames, 9, "n_frames");
+      if(currentTimeSet.fullTimeStampFlag)
+      {
+        WRITE_CODE(currentTimeSet.secondsValue, 6, "seconds_value");
+        WRITE_CODE(currentTimeSet.minutesValue, 6, "minutes_value");
+        WRITE_CODE(currentTimeSet.hoursValue, 5, "hours_value");
+      }
+      else
+      {
+        WRITE_FLAG(currentTimeSet.secondsFlag, "seconds_flag");
+        if(currentTimeSet.secondsFlag)
+        {
+          WRITE_CODE(currentTimeSet.secondsValue, 6, "seconds_value");
+          WRITE_FLAG(currentTimeSet.minutesFlag, "minutes_flag");
+          if(currentTimeSet.minutesFlag)
+          {
+            WRITE_CODE(currentTimeSet.minutesValue, 6, "minutes_value");
+            WRITE_FLAG(currentTimeSet.hoursFlag, "hours_flag");
+            if(currentTimeSet.hoursFlag)
+            {
+              WRITE_CODE(currentTimeSet.hoursValue, 5, "hours_value");
+            }
+          }
+        }
+      }
+      WRITE_CODE(currentTimeSet.timeOffsetLength, 5, "time_offset_length");
+      if(currentTimeSet.timeOffsetLength > 0)
+      {
+        if(currentTimeSet.timeOffsetValue >= 0)
+        {
+          WRITE_CODE((UInt)currentTimeSet.timeOffsetValue, currentTimeSet.timeOffsetLength, "time_offset_value");
+        }
+        else
+        {
+          //  Two's complement conversion
+          UInt offsetValue = ~(currentTimeSet.timeOffsetValue) + 1;
+          offsetValue |= (1 << (currentTimeSet.timeOffsetLength-1));
+          WRITE_CODE(offsetValue, currentTimeSet.timeOffsetLength, "time_offset_value");
+        }
+      }
+    }
+  }
+}
+
+Void SEIWriter::xWriteSEIChromaSamplingFilterHint(const SEIChromaSamplingFilterHint &sei/*, TComSPS* sps*/)
+{
+  WRITE_CODE(sei.m_verChromaFilterIdc, 8, "ver_chroma_filter_idc");
+  WRITE_CODE(sei.m_horChromaFilterIdc, 8, "hor_chroma_filter_idc");
+  WRITE_FLAG(sei.m_verFilteringProcessFlag, "ver_filtering_process_flag");
+  if(sei.m_verChromaFilterIdc == 1 || sei.m_horChromaFilterIdc == 1)
+  {
+    writeUserDefinedCoefficients(sei);
+  }
+}
+
+// write hardcoded chroma filter coefficients in the SEI messages
+Void SEIWriter::writeUserDefinedCoefficients(const SEIChromaSamplingFilterHint &sei)
+{
+  Int const iNumVerticalFilters = 3;
+  Int verticalTapLength_minus1[iNumVerticalFilters] = {5,3,3};
+  Int* userVerticalCoefficients[iNumVerticalFilters];
+  for(Int i = 0; i < iNumVerticalFilters; i ++)
+  {
+    userVerticalCoefficients[i] = (Int*)malloc( (verticalTapLength_minus1[i]+1) * sizeof(Int));
+  }
+  userVerticalCoefficients[0][0] = -3;
+  userVerticalCoefficients[0][1] = 13;
+  userVerticalCoefficients[0][2] = 31;
+  userVerticalCoefficients[0][3] = 23;
+  userVerticalCoefficients[0][4] = 3;
+  userVerticalCoefficients[0][5] = -3;
+
+  userVerticalCoefficients[1][0] = -1;
+  userVerticalCoefficients[1][1] = 25;
+  userVerticalCoefficients[1][2] = 247;
+  userVerticalCoefficients[1][3] = -15;
+
+  userVerticalCoefficients[2][0] = -20;
+  userVerticalCoefficients[2][1] = 186;
+  userVerticalCoefficients[2][2] = 100;
+  userVerticalCoefficients[2][3] = -10;
+  
+  Int const iNumHorizontalFilters = 1;
+  Int horizontalTapLength_minus1[iNumHorizontalFilters] = {3};
+  Int* userHorizontalCoefficients[iNumHorizontalFilters];
+  for(Int i = 0; i < iNumHorizontalFilters; i ++)
+  {
+    userHorizontalCoefficients[i] = (Int*)malloc( (horizontalTapLength_minus1[i]+1) * sizeof(Int));
+  }
+  userHorizontalCoefficients[0][0] = 1;
+  userHorizontalCoefficients[0][1] = 6;
+  userHorizontalCoefficients[0][2] = 1;
+
+  WRITE_UVLC(3, "target_format_idc");
+  if(sei.m_verChromaFilterIdc == 1)
+  {
+    WRITE_UVLC(iNumVerticalFilters, "num_vertical_filters");
+    if(iNumVerticalFilters > 0)
+    {
+      for(Int i = 0; i < iNumVerticalFilters; i ++)
+      {
+        WRITE_UVLC(verticalTapLength_minus1[i], "ver_tap_length_minus_1");
+        for(Int j = 0; j < verticalTapLength_minus1[i]; j ++)
+        {
+          WRITE_SVLC(userVerticalCoefficients[i][j], "ver_filter_coeff");
+        }
+      }
+    }
+  }
+  if(sei.m_horChromaFilterIdc == 1)
+  {
+    WRITE_UVLC(iNumHorizontalFilters, "num_horizontal_filters");
+    if(iNumHorizontalFilters > 0)
+    {
+      for(Int i = 0; i < iNumHorizontalFilters; i ++)
+      {
+        WRITE_UVLC(horizontalTapLength_minus1[i], "hor_tap_length_minus_1");
+        for(Int j = 0; j < horizontalTapLength_minus1[i]; j ++)
+        {
+          WRITE_SVLC(userHorizontalCoefficients[i][j], "hor_filter_coeff");
+        }
+      }
+    }
+  }
+}
+
+#if NH_MV
 Void SEIWriter::xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei)
 {
@@ -602,15 +766,55 @@
 #endif
 
+Void SEIWriter::xWriteSEIKneeFunctionInfo(const SEIKneeFunctionInfo &sei)
+{
+  WRITE_UVLC( sei.m_kneeId, "knee_function_id" );
+  WRITE_FLAG( sei.m_kneeCancelFlag, "knee_function_cancel_flag" ); 
+  if ( !sei.m_kneeCancelFlag )
+  {
+    WRITE_FLAG( sei.m_kneePersistenceFlag, "knee_function_persistence_flag" );
+    WRITE_CODE( (UInt)sei.m_kneeInputDrange , 32,  "input_d_range" );
+    WRITE_CODE( (UInt)sei.m_kneeInputDispLuminance, 32,  "input_disp_luminance" );
+    WRITE_CODE( (UInt)sei.m_kneeOutputDrange, 32,  "output_d_range" );
+    WRITE_CODE( (UInt)sei.m_kneeOutputDispLuminance, 32,  "output_disp_luminance" );
+    WRITE_UVLC( sei.m_kneeNumKneePointsMinus1, "num_knee_points_minus1" );
+    for(Int i = 0; i <= sei.m_kneeNumKneePointsMinus1; i++ )
+    {
+      WRITE_CODE( (UInt)sei.m_kneeInputKneePoint[i], 10,"input_knee_point" );
+      WRITE_CODE( (UInt)sei.m_kneeOutputKneePoint[i], 10, "output_knee_point" );
+    }
+  }
+}
+
+
+Void SEIWriter::xWriteSEIMasteringDisplayColourVolume(const SEIMasteringDisplayColourVolume& sei)
+{
+  WRITE_CODE( sei.values.primaries[0][0],  16,  "display_primaries_x[0]" );
+  WRITE_CODE( sei.values.primaries[0][1],  16,  "display_primaries_y[0]" );
+
+  WRITE_CODE( sei.values.primaries[1][0],  16,  "display_primaries_x[1]" );
+  WRITE_CODE( sei.values.primaries[1][1],  16,  "display_primaries_y[1]" );
+
+  WRITE_CODE( sei.values.primaries[2][0],  16,  "display_primaries_x[2]" );
+  WRITE_CODE( sei.values.primaries[2][1],  16,  "display_primaries_y[2]" );
+
+  WRITE_CODE( sei.values.whitePoint[0],    16,  "white_point_x" );
+  WRITE_CODE( sei.values.whitePoint[1],    16,  "white_point_y" );
+    
+  WRITE_CODE( sei.values.maxLuminance,     32,  "max_display_mastering_luminance" );
+  WRITE_CODE( sei.values.minLuminance,     32,  "min_display_mastering_luminance" );
+}
+
+
 Void SEIWriter::xWriteByteAlign()
 {
   if( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0)
   {
-    WRITE_FLAG( 1, "bit_equal_to_one" );
+    WRITE_FLAG( 1, "payload_bit_equal_to_one" );
     while( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
     {
-      WRITE_FLAG( 0, "bit_equal_to_zero" );
-    }
-  }
-};
+      WRITE_FLAG( 0, "payload_bit_equal_to_zero" );
+    }
+  }
+}
 
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIwrite.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SEIwrite.h	(revision 1200)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -34,4 +34,7 @@
 #pragma once
 
+#ifndef __SEIWRITE__
+#define __SEIWRITE__
+
 #include "SyntaxElementWriter.h"
 #include "TLibCommon/SEI.h"
@@ -47,28 +50,39 @@
   virtual ~SEIWriter() {};
 
-  void writeSEImessage(TComBitIf& bs, const SEI& sei, TComSPS *sps);
+  Void writeSEImessages(TComBitIf& bs, const SEIMessages &seiList, const TComSPS *sps, Bool isNested);
 
 protected:
-  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps);
+  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, const TComSPS *sps);
   Void xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei);
   Void xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei);
-  Void xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, TComSPS *sps);
+  Void xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, const TComSPS *sps);
   Void xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei);
-  Void xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, TComSPS *sps);
-  Void xWriteSEIPictureTiming(const SEIPictureTiming& sei, TComSPS *sps);
+  Void xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, const TComSPS *sps);
+  Void xWriteSEIPictureTiming(const SEIPictureTiming& sei, const TComSPS *sps);
   TComSPS *m_pSPS;
   Void xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei);
   Void xWriteSEIFramePacking(const SEIFramePacking& sei);
+  Void xWriteSEISegmentedRectFramePacking(const SEISegmentedRectFramePacking& sei);
   Void xWriteSEIDisplayOrientation(const SEIDisplayOrientation &sei);
   Void xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei);
   Void xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei);
+  Void xWriteSEINoDisplay(const SEINoDisplay &sei);
   Void xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei);
   Void xWriteSEISOPDescription(const SEISOPDescription& sei);
-  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps);
-#if H_MV
+  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, const TComSPS *sps);
+#if NH_MV
   Void xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei);
 #endif
+  Void xWriteSEITempMotionConstrainedTileSets(const SEITempMotionConstrainedTileSets& sei);
+  Void xWriteSEITimeCode(const SEITimeCode& sei);
+  Void xWriteSEIChromaSamplingFilterHint(const SEIChromaSamplingFilterHint& sei/*, TComSPS *sps*/);
+  Void writeUserDefinedCoefficients(const SEIChromaSamplingFilterHint& sei);
+  Void xWriteSEIKneeFunctionInfo(const SEIKneeFunctionInfo &sei);
+  Void xWriteSEIMasteringDisplayColourVolume( const SEIMasteringDisplayColourVolume& sei);
+
   Void xWriteByteAlign();
 };
 
 //! \}
+
+#endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -60,9 +60,9 @@
     if( length<10 )
     {
-      fprintf( g_hTrace, "%-50s u(%d)  : %d\n", pSymbolName, length, value ); 
+      fprintf( g_hTrace, "%-50s u(%d)  : %d\n", pSymbolName, length, value );
     }
     else
     {
-      fprintf( g_hTrace, "%-50s u(%d) : %d\n", pSymbolName, length, value ); 
+      fprintf( g_hTrace, "%-50s u(%d) : %d\n", pSymbolName, length, value );
     }
   }
@@ -83,5 +83,5 @@
 #endif
 
-    fprintf( g_hTrace, "%-50s ue(v) : %d\n", pSymbolName, value ); 
+    fprintf( g_hTrace, "%-50s ue(v) : %d\n", pSymbolName, value );
   }
 }
@@ -101,5 +101,5 @@
 #endif
 
-    fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, value ); 
+    fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, value );
   }
 }
@@ -118,5 +118,5 @@
     }
 #endif
-    fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, value ); 
+    fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, value );
   }
 }
@@ -135,7 +135,7 @@
   UInt uiLength = 1;
   UInt uiTemp = ++uiCode;
-  
+
   assert ( uiTemp );
-  
+
   while( 1 != uiTemp )
   {
@@ -151,5 +151,5 @@
 {
   UInt uiCode;
-  
+
   uiCode = xConvertToUInt( iCode );
   xWriteUvlc( uiCode );
@@ -161,3 +161,15 @@
 }
 
+Void SyntaxElementWriter::xWriteRbspTrailingBits()
+{
+  WRITE_FLAG( 1, "rbsp_stop_one_bit");
+  Int cnt = 0;
+  while (m_pcBitIf->getNumBitsUntilByteAligned())
+  {
+    WRITE_FLAG( 0, "rbsp_alignment_zero_bit");
+    cnt++;
+  }
+  assert(cnt<8);
+}
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -88,4 +88,5 @@
   Void  xWriteFlagTr          ( UInt value,               const Char *pSymbolName);
 #endif
+  Void xWriteRbspTrailingBits();
 
   UInt  xConvertToUInt        ( Int iValue ) {  return ( iValue <= 0) ? -iValue<<1 : (iValue<<1)-1; }
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 1199)
+++ 	(revision )
@@ -1,58 +1,0 @@
-/* The copyright in this software is being made available under the 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) 2010-2015, ITU/ISO/IEC
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- *  * Redistributions of source code must retain the above copyright notice,
- *    this list of conditions and the following disclaimer.
- *  * 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.
- *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
- *    be used to endorse or promote products derived from this software without
- *    specific prior written permission.
- *
- * 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 HOLDER 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.
- */
-
-/** \file     TEncAnalyze.cpp
-    \brief    encoder analyzer class
-*/
-
-#if !H_MV
-#include "TEncAnalyze.h"
-#endif
-
-//! \ingroup TLibEncoder
-//! \{
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-#if !H_MV
-TEncAnalyze             m_gcAnalyzeAll;
-TEncAnalyze             m_gcAnalyzeI;
-TEncAnalyze             m_gcAnalyzeP;
-TEncAnalyze             m_gcAnalyzeB;
-
-TEncAnalyze             m_gcAnalyzeAll_in;
-#endif
-
-//! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -47,4 +47,6 @@
 #include <assert.h>
 #include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComChromaFormat.h"
+#include "math.h"
 
 //! \ingroup TLibEncoder
@@ -59,125 +61,324 @@
 {
 private:
-  Double    m_dPSNRSumY;
-  Double    m_dPSNRSumU;
-  Double    m_dPSNRSumV;
+  Double    m_dPSNRSum[MAX_NUM_COMPONENT];
   Double    m_dAddBits;
   UInt      m_uiNumPic;
   Double    m_dFrmRate; //--CFG_KDY
-  
+  Double    m_MSEyuvframe[MAX_NUM_COMPONENT]; // sum of MSEs
+
 public:
-  TEncAnalyze() { m_dPSNRSumY = m_dPSNRSumU = m_dPSNRSumV = m_dAddBits = m_uiNumPic = 0;  }
   virtual ~TEncAnalyze()  {}
-  
-  Void  addResult( Double psnrY, Double psnrU, Double psnrV, Double bits)
-  {
-    m_dPSNRSumY += psnrY;
-    m_dPSNRSumU += psnrU;
-    m_dPSNRSumV += psnrV;
+  TEncAnalyze() { clear(); }
+
+  Void  addResult( Double psnr[MAX_NUM_COMPONENT], Double bits, const Double MSEyuvframe[MAX_NUM_COMPONENT])
+  {
     m_dAddBits  += bits;
-    
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      m_dPSNRSum[i] += psnr[i];
+      m_MSEyuvframe[i] += MSEyuvframe[i];
+    }
+
     m_uiNumPic++;
   }
-  
-  Double  getPsnrY()  { return  m_dPSNRSumY;  }
-  Double  getPsnrU()  { return  m_dPSNRSumU;  }
-  Double  getPsnrV()  { return  m_dPSNRSumV;  }
-  Double  getBits()   { return  m_dAddBits;   }
-  UInt    getNumPic() { return  m_uiNumPic;   }
-  
+
+  Double  getPsnr(ComponentID compID) const { return  m_dPSNRSum[compID];  }
+  Double  getBits()                   const { return  m_dAddBits;   }
+  Void    setBits(Double numBits)     { m_dAddBits=numBits; }
+  UInt    getNumPic()                 const { return  m_uiNumPic;   }
+
   Void    setFrmRate  (Double dFrameRate) { m_dFrmRate = dFrameRate; } //--CFG_KDY
-  Void    clear() { m_dPSNRSumY = m_dPSNRSumU = m_dPSNRSumV = m_dAddBits = m_uiNumPic = 0;  }
-  Void    printOut ( Char cDelim )
+  Void    clear()
+  {
+    m_dAddBits = 0;
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      m_dPSNRSum[i] = 0;
+      m_MSEyuvframe[i] = 0;
+    }
+    m_uiNumPic = 0;
+  }
+
+
+  Void calculateCombinedValues(const ChromaFormat chFmt, Double &PSNRyuv, Double &MSEyuv, const BitDepths &bitDepths)
+  {
+    MSEyuv    = 0;
+    Int scale = 0;
+
+    Int maximumBitDepth = bitDepths.recon[CHANNEL_TYPE_LUMA];
+    for (UInt channelTypeIndex = 1; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+    {
+      if (bitDepths.recon[channelTypeIndex] > maximumBitDepth)
+      {
+        maximumBitDepth = bitDepths.recon[channelTypeIndex];
+      }
+    }
+
+    const UInt maxval                = 255 << (maximumBitDepth - 8);
+    const UInt numberValidComponents = getNumberValidComponents(chFmt);
+
+    for (UInt comp=0; comp<numberValidComponents; comp++)
+    {
+      const ComponentID compID        = ComponentID(comp);
+      const UInt        csx           = getComponentScaleX(compID, chFmt);
+      const UInt        csy           = getComponentScaleY(compID, chFmt);
+      const Int         scaleChan     = (4>>(csx+csy));
+      const UInt        bitDepthShift = 2 * (maximumBitDepth - bitDepths.recon[toChannelType(compID)]); //*2 because this is a squared number
+
+      const Double      channelMSE    = (m_MSEyuvframe[compID] * Double(1 << bitDepthShift)) / Double(getNumPic());
+
+      scale  += scaleChan;
+      MSEyuv += scaleChan * channelMSE;
+    }
+
+    MSEyuv /= Double(scale);  // i.e. divide by 6 for 4:2:0, 8 for 4:2:2 etc.
+    PSNRyuv = (MSEyuv==0 ? 999.99 : 10*log10((maxval*maxval)/MSEyuv));
+  }
+
+
+  Void    printOut ( Char cDelim, const ChromaFormat chFmt, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths )
   {
     Double dFps     =   m_dFrmRate; //--CFG_KDY
     Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
-    
-    printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
-    //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
-    printf( "\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
-           getNumPic(), cDelim,
-           getBits() * dScale,
-           getPsnrY() / (Double)getNumPic(),
-           getPsnrU() / (Double)getNumPic(),
-           getPsnrV() / (Double)getNumPic() );
-  }
-  
-  Void    printSummaryOut ()
-  {
-    FILE* pFile = fopen ("summaryTotal.txt", "at");
+
+    Double MSEBasedSNR[MAX_NUM_COMPONENT];
+    if (printMSEBasedSNR)
+    {
+      for (UInt componentIndex = 0; componentIndex < MAX_NUM_COMPONENT; componentIndex++)
+      {
+        const ComponentID compID = ComponentID(componentIndex);
+
+        if (getNumPic() == 0)
+        {
+          MSEBasedSNR[compID] = 0 * dScale; // this is the same calculation that will be evaluated for any other statistic when there are no frames (it should result in NaN). We use it here so all the output is consistent.
+        }
+        else
+        {
+          //NOTE: this is not the true maximum value for any bitDepth other than 8. It comes from the original HM PSNR calculation
+          const UInt maxval = 255 << (bitDepths.recon[toChannelType(compID)] - 8);
+          const Double MSE = m_MSEyuvframe[compID];
+
+          MSEBasedSNR[compID] = (MSE == 0) ? 999.99 : (10 * log10((maxval * maxval) / (MSE / (Double)getNumPic())));
+        }
+      }
+    }
+
+    switch (chFmt)
+    {
+      case CHROMA_400:
+        if (printMSEBasedSNR)
+        {
+          printf( "         \tTotal Frames |   "   "Bitrate     "  "Y-PSNR" );
+
+          if (printSequenceMSE)
+          {
+            printf( "    Y-MSE\n" );
+          }
+          else
+          {
+            printf("\n");
+          }
+
+          //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+          printf( "Average: \t %8d    %c "          "%12.4lf  "    "%8.4lf",
+                 getNumPic(), cDelim,
+                 getBits() * dScale,
+                 getPsnr(COMPONENT_Y) / (Double)getNumPic() );
+
+          if (printSequenceMSE)
+          {
+            printf( "  %8.4lf\n", m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic() );
+          }
+          else
+          {
+            printf("\n");
+          }
+
+          printf( "From MSE:\t %8d    %c "          "%12.4lf  "    "%8.4lf\n",
+                 getNumPic(), cDelim,
+                 getBits() * dScale,
+                 MSEBasedSNR[COMPONENT_Y] );
+        }
+        else
+        {
+          printf( "\tTotal Frames |   "   "Bitrate     "  "Y-PSNR" );
+
+          if (printSequenceMSE)
+          {
+            printf( "    Y-MSE\n" );
+          }
+          else
+          {
+            printf("\n");
+          }
+
+          //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+          printf( "\t %8d    %c "          "%12.4lf  "    "%8.4lf",
+                 getNumPic(), cDelim,
+                 getBits() * dScale,
+                 getPsnr(COMPONENT_Y) / (Double)getNumPic() );
+
+          if (printSequenceMSE)
+          {
+            printf( "  %8.4lf\n", m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic() );
+          }
+          else
+          {
+            printf("\n");
+          }
+        }
+        break;
+      case CHROMA_420:
+      case CHROMA_422:
+      case CHROMA_444:
+        {
+          Double PSNRyuv = MAX_DOUBLE;
+          Double MSEyuv  = MAX_DOUBLE;
+          
+          calculateCombinedValues(chFmt, PSNRyuv, MSEyuv, bitDepths);
+
+          if (printMSEBasedSNR)
+          {
+            printf( "         \tTotal Frames |   "   "Bitrate     "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR    "  "YUV-PSNR " );
+
+            if (printSequenceMSE)
+            {
+              printf( " Y-MSE     "  "U-MSE     "  "V-MSE    "  "YUV-MSE \n" );
+            }
+            else
+            {
+              printf("\n");
+            }
+
+            //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+            printf( "Average: \t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf",
+                   getNumPic(), cDelim,
+                   getBits() * dScale,
+                   getPsnr(COMPONENT_Y) / (Double)getNumPic(),
+                   getPsnr(COMPONENT_Cb) / (Double)getNumPic(),
+                   getPsnr(COMPONENT_Cr) / (Double)getNumPic(),
+                   PSNRyuv );
+
+            if (printSequenceMSE)
+            {
+              printf( "  %8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf\n",
+                     m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic(),
+                     m_MSEyuvframe[COMPONENT_Cb] / (Double)getNumPic(),
+                     m_MSEyuvframe[COMPONENT_Cr] / (Double)getNumPic(),
+                     MSEyuv );
+            }
+            else
+            {
+              printf("\n");
+            }
+
+            printf( "From MSE:\t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf\n",
+                   getNumPic(), cDelim,
+                   getBits() * dScale,
+                   MSEBasedSNR[COMPONENT_Y],
+                   MSEBasedSNR[COMPONENT_Cb],
+                   MSEBasedSNR[COMPONENT_Cr],
+                   PSNRyuv );
+          }
+          else
+          {
+            printf( "\tTotal Frames |   "   "Bitrate     "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR    "  "YUV-PSNR " );
+            
+            if (printSequenceMSE)
+            {
+              printf( " Y-MSE     "  "U-MSE     "  "V-MSE    "  "YUV-MSE \n" );
+            }
+            else
+            {
+              printf("\n");
+            }
+
+            //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+            printf( "\t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf",
+                   getNumPic(), cDelim,
+                   getBits() * dScale,
+                   getPsnr(COMPONENT_Y) / (Double)getNumPic(),
+                   getPsnr(COMPONENT_Cb) / (Double)getNumPic(),
+                   getPsnr(COMPONENT_Cr) / (Double)getNumPic(),
+                   PSNRyuv );
+
+            if (printSequenceMSE)
+            {
+              printf( "  %8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf\n",
+                     m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic(),
+                     m_MSEyuvframe[COMPONENT_Cb] / (Double)getNumPic(),
+                     m_MSEyuvframe[COMPONENT_Cr] / (Double)getNumPic(),
+                     MSEyuv );
+            }
+            else
+            {
+              printf("\n");
+            }
+          }
+        }
+        break;
+      default:
+        fprintf(stderr, "Unknown format during print out\n");
+        exit(1);
+        break;
+    }
+  }
+
+
+  Void    printSummary(const ChromaFormat chFmt, const Bool printSequenceMSE, const BitDepths &bitDepths, const std::string &sFilename)
+  {
+    FILE* pFile = fopen (sFilename.c_str(), "at");
+
     Double dFps     =   m_dFrmRate; //--CFG_KDY
     Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
-    
-    fprintf(pFile, "%f\t %f\t %f\t %f\n", getBits() * dScale,
-            getPsnrY() / (Double)getNumPic(),
-            getPsnrU() / (Double)getNumPic(),
-            getPsnrV() / (Double)getNumPic() );
+    switch (chFmt)
+    {
+      case CHROMA_400:
+        fprintf(pFile, "%f\t %f\n",
+            getBits() * dScale,
+            getPsnr(COMPONENT_Y) / (Double)getNumPic() );
+        break;
+      case CHROMA_420:
+      case CHROMA_422:
+      case CHROMA_444:
+        {
+          Double PSNRyuv = MAX_DOUBLE;
+          Double MSEyuv  = MAX_DOUBLE;
+          
+          calculateCombinedValues(chFmt, PSNRyuv, MSEyuv, bitDepths);
+
+          fprintf(pFile, "%f\t %f\t %f\t %f\t %f",
+              getBits() * dScale,
+              getPsnr(COMPONENT_Y) / (Double)getNumPic(),
+              getPsnr(COMPONENT_Cb) / (Double)getNumPic(),
+              getPsnr(COMPONENT_Cr) / (Double)getNumPic(),
+              PSNRyuv );
+
+          if (printSequenceMSE)
+          {
+            fprintf(pFile, "\t %f\t %f\t %f\t %f\n",
+                m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic(),
+                m_MSEyuvframe[COMPONENT_Cb] / (Double)getNumPic(),
+                m_MSEyuvframe[COMPONENT_Cr] / (Double)getNumPic(),
+                MSEyuv );
+          }
+          else
+          {
+            fprintf(pFile, "\n");
+          }
+
+          break;
+        }
+
+      default:
+          fprintf(stderr, "Unknown format during print out\n");
+          exit(1);
+          break;
+    }
+
     fclose(pFile);
   }
-  
-  Void    printOutInterlaced ( Char cDelim, Double bits )
-  {
-    Double dFps     =   m_dFrmRate; //--CFG_KDY
-    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
-    
-    printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
-    //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
-    printf( "\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
-           getNumPic(), cDelim,
-           bits * dScale,
-           getPsnrY() / (Double)getNumPic(),
-           getPsnrU() / (Double)getNumPic(),
-           getPsnrV() / (Double)getNumPic() );
-  }
-  
-  Void    printSummaryOutInterlaced (Int bits)
-  {
-    FILE* pFile = fopen ("summaryTotal.txt", "at");
-    Double dFps     =   m_dFrmRate; //--CFG_KDY
-    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
-    
-    fprintf(pFile, "%f\t %f\t %f\t %f\n", bits * dScale,
-            getPsnrY() / (Double)getNumPic(),
-            getPsnrU() / (Double)getNumPic(),
-            getPsnrV() / (Double)getNumPic() );
-    fclose(pFile);
-  }
-  
-  
-  Void    printSummary(Char ch)
-  {
-    FILE* pFile = NULL;
-    
-    switch( ch ) 
-    {
-      case 'I':
-        pFile = fopen ("summary_I.txt", "at");
-        break;
-      case 'P':
-        pFile = fopen ("summary_P.txt", "at");
-        break;
-      case 'B':
-        pFile = fopen ("summary_B.txt", "at");
-        break;
-      default:
-        assert(0);
-        return;
-        break;
-    }
-    
-    Double dFps     =   m_dFrmRate; //--CFG_KDY
-    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
-    
-    fprintf(pFile, "%f\t %f\t %f\t %f\n",
-            getBits() * dScale,
-            getPsnrY() / (Double)getNumPic(),
-            getPsnrU() / (Double)getNumPic(),
-            getPsnrV() / (Double)getNumPic() );
-    
-    fclose(pFile);
-  }
 };
 
-#if !H_MV
 extern TEncAnalyze             m_gcAnalyzeAll;
 extern TEncAnalyze             m_gcAnalyzeI;
@@ -186,5 +387,4 @@
 
 extern TEncAnalyze             m_gcAnalyzeAll_in;
-#endif
 
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,6 +36,6 @@
 */
 
-#ifndef __TENC_BIN_CODER__
-#define __TENC_BIN_CODER__
+#ifndef __TENCBINCODER__
+#define __TENCBINCODER__
 
 #include "TLibCommon/ContextModel.h"
@@ -55,5 +55,5 @@
   virtual Void  start             ()                                          = 0;
   virtual Void  finish            ()                                          = 0;
-  virtual Void  copyState         ( TEncBinIf* pcTEncBinIf )                  = 0;
+  virtual Void  copyState         ( const TEncBinIf* pcTEncBinIf )            = 0;
   virtual Void  flush            ()                                           = 0;
 
@@ -70,6 +70,9 @@
   virtual Void  encodeBinTrm      ( UInt  uiBin                            )  = 0;
 
+  virtual Void  align             ()                                          = 0;
+
   virtual TEncBinCABAC*   getTEncBinCABAC   ()  { return 0; }
-  
+  virtual const TEncBinCABAC*   getTEncBinCABAC   () const { return 0; }
+
   virtual ~TEncBinIf() {}
 };
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,5 +38,5 @@
 #include "TEncBinCoderCABAC.h"
 #include "TLibCommon/TComRom.h"
-
+#include "TLibCommon/Debug.h"
 
 //! \ingroup TLibEncoder
@@ -74,4 +74,7 @@
   m_numBufferedBytes = 0;
   m_bufferedByte     = 0xff;
+#if FAST_BIT_EST
+  m_fracBits         = 0;
+#endif
 }
 
@@ -100,5 +103,5 @@
       m_pcTComBitIf->write( 0xff, 8 );
       m_numBufferedBytes--;
-    }    
+    }
   }
   m_pcTComBitIf->write( m_uiLow >> 8, 24 - m_bitsLeft );
@@ -143,7 +146,7 @@
 }
 
-Void TEncBinCABAC::copyState( TEncBinIf* pcTEncBinIf )
-{
-  TEncBinCABAC* pcTEncBinCABAC = pcTEncBinIf->getTEncBinCABAC();
+Void TEncBinCABAC::copyState( const TEncBinIf* pcTEncBinIf )
+{
+  const TEncBinCABAC* pcTEncBinCABAC = pcTEncBinIf->getTEncBinCABAC();
   m_uiLow           = pcTEncBinCABAC->m_uiLow;
   m_uiRange         = pcTEncBinCABAC->m_uiRange;
@@ -184,20 +187,24 @@
 Void TEncBinCABAC::encodeBin( UInt binValue, ContextModel &rcCtxModel )
 {
-  {
-#if !H_MV
-    DTRACE_CABAC_VL( g_nSymbolCounter++ )
-    DTRACE_CABAC_T( "\tstate=" )
-    DTRACE_CABAC_V( ( rcCtxModel.getState() << 1 ) + rcCtxModel.getMps() )
-    DTRACE_CABAC_T( "\tsymbol=" )
-    DTRACE_CABAC_V( binValue )
-    DTRACE_CABAC_T( "\n" )
-#endif
-  }
+#if !NH_MV
+  //{
+  //  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  //  DTRACE_CABAC_T( "\tstate=" )
+  //  DTRACE_CABAC_V( ( rcCtxModel.getState() << 1 ) + rcCtxModel.getMps() )
+  //  DTRACE_CABAC_T( "\tsymbol=" )
+  //  DTRACE_CABAC_V( binValue )
+  //  DTRACE_CABAC_T( "\n" )
+  //}
+#endif
+#if DEBUG_CABAC_BINS
+  const UInt startingRange = m_uiRange;
+#endif
+
   m_uiBinsCoded += m_binCountIncrement;
   rcCtxModel.setBinsCoded( 1 );
-  
+
   UInt  uiLPS   = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) & 3 ];
   m_uiRange    -= uiLPS;
-  
+
   if( binValue != rcCtxModel.getMps() )
   {
@@ -206,21 +213,38 @@
     m_uiRange   = uiLPS << numBits;
     rcCtxModel.updateLPS();
-    
     m_bitsLeft -= numBits;
+    testAndWriteOut();
   }
   else
   {
     rcCtxModel.updateMPS();
-    if ( m_uiRange >= 256 )
-    {
-      return;
-    }
-    
-    m_uiLow <<= 1;
-    m_uiRange <<= 1;
-    m_bitsLeft--;
-  }
-  
-  testAndWriteOut();
+
+    if ( m_uiRange < 256 )
+    {
+      m_uiLow <<= 1;
+      m_uiRange <<= 1;
+      m_bitsLeft--;
+      testAndWriteOut();
+    }
+  }
+
+#if DEBUG_CABAC_BINS
+  if ((g_debugCounter + debugCabacBinWindow) >= debugCabacBinTargetLine)
+  {
+    std::cout << g_debugCounter << ": coding bin value " << binValue << ", range = [" << startingRange << "->" << m_uiRange << "]\n";
+  }
+
+  if (g_debugCounter >= debugCabacBinTargetLine)
+  {
+    Char breakPointThis;
+    breakPointThis = 7;
+  }
+  if (g_debugCounter >= (debugCabacBinTargetLine + debugCabacBinWindow))
+  {
+    exit(0);
+  }
+
+  g_debugCounter++;
+#endif
 }
 
@@ -232,6 +256,7 @@
 Void TEncBinCABAC::encodeBinEP( UInt binValue )
 {
-  {
-#if !H_MV
+  if (false)
+  {
+#if !NH_MV
     DTRACE_CABAC_VL( g_nSymbolCounter++ )
     DTRACE_CABAC_T( "\tEPsymbol=" )
@@ -240,5 +265,13 @@
 #endif
   }
+
   m_uiBinsCoded += m_binCountIncrement;
+
+  if (m_uiRange == 256)
+  {
+    encodeAlignedBinsEP(binValue, 1);
+    return;
+  }
+
   m_uiLow <<= 1;
   if( binValue )
@@ -247,5 +280,5 @@
   }
   m_bitsLeft--;
-  
+
   testAndWriteOut();
 }
@@ -260,32 +293,83 @@
 {
   m_uiBinsCoded += numBins & -m_binCountIncrement;
-  
-  for ( Int i = 0; i < numBins; i++ )
-  {
-#if !H_MV
-    DTRACE_CABAC_VL( g_nSymbolCounter++ )
-    DTRACE_CABAC_T( "\tEPsymbol=" )
-    DTRACE_CABAC_V( ( binValues >> ( numBins - 1 - i ) ) & 1 )
-    DTRACE_CABAC_T( "\n" )
-#endif
-  }
-  
+
+  if (false)
+  {
+    for ( Int i = 0; i < numBins; i++ )
+    {
+#if !NH_MV
+      DTRACE_CABAC_VL( g_nSymbolCounter++ )
+      DTRACE_CABAC_T( "\tEPsymbol=" )
+      DTRACE_CABAC_V( ( binValues >> ( numBins - 1 - i ) ) & 1 )
+      DTRACE_CABAC_T( "\n" )
+#endif
+    }
+  }
+
+  if (m_uiRange == 256)
+  {
+    encodeAlignedBinsEP(binValues, numBins);
+    return;
+  }
+
   while ( numBins > 8 )
   {
     numBins -= 8;
-    UInt pattern = binValues >> numBins; 
+    UInt pattern = binValues >> numBins;
     m_uiLow <<= 8;
     m_uiLow += m_uiRange * pattern;
     binValues -= pattern << numBins;
     m_bitsLeft -= 8;
-    
+
     testAndWriteOut();
   }
-  
+
   m_uiLow <<= numBins;
   m_uiLow += m_uiRange * binValues;
   m_bitsLeft -= numBins;
-  
+
   testAndWriteOut();
+}
+
+Void TEncBinCABAC::align()
+{
+  m_uiRange = 256;
+}
+
+Void TEncBinCABAC::encodeAlignedBinsEP( UInt binValues, Int numBins )
+{
+  Int binsRemaining = numBins;
+
+  assert(m_uiRange == 256); //aligned encode only works when range = 256
+
+  while (binsRemaining > 0)
+  {
+    const UInt binsToCode = std::min<UInt>(binsRemaining, 8); //code bytes if able to take advantage of the system's byte-write function
+    const UInt binMask    = (1 << binsToCode) - 1;
+
+    const UInt newBins = (binValues >> (binsRemaining - binsToCode)) & binMask;
+
+    //The process of encoding an EP bin is the same as that of coding a normal
+    //bin where the symbol ranges for 1 and 0 are both half the range:
+    //
+    //  low = (low + range/2) << 1       (to encode a 1)
+    //  low =  low            << 1       (to encode a 0)
+    //
+    //  i.e.
+    //  low = (low + (bin * range/2)) << 1
+    //
+    //  which is equivalent to:
+    //
+    //  low = (low << 1) + (bin * range)
+    //
+    //  this can be generalised for multiple bins, producing the following expression:
+    //
+    m_uiLow = (m_uiLow << binsToCode) + (newBins << 8); //range is known to be 256
+
+    binsRemaining -= binsToCode;
+    m_bitsLeft    -= binsToCode;
+
+    testAndWriteOut();
+  }
 }
 
@@ -314,7 +398,7 @@
     m_uiLow   <<= 1;
     m_uiRange <<= 1;
-    m_bitsLeft--;    
-  }
-  
+    m_bitsLeft--;
+  }
+
   testAndWriteOut();
 }
@@ -336,5 +420,5 @@
   m_bitsLeft += 8;
   m_uiLow &= 0xffffffffu >> m_bitsLeft;
-  
+
   if ( leadByte == 0xff )
   {
@@ -349,5 +433,5 @@
       m_bufferedByte = leadByte & 0xff;
       m_pcTComBitIf->write( byte, 8 );
-      
+
       byte = ( 0xff + carry ) & 0xff;
       while ( m_numBufferedBytes > 1 )
@@ -361,6 +445,6 @@
       m_numBufferedBytes = 1;
       m_bufferedByte = leadByte;
-    }      
-  }    
+    }
+  }
 }
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,6 +36,6 @@
 */
 
-#ifndef __TENC_BIN_CODER_CABAC__
-#define __TENC_BIN_CODER_CABAC__
+#ifndef __TENCBINCODERCABAC__
+#define __TENCBINCODERCABAC__
 
 #include "TLibCommon/TComCABACTables.h"
@@ -50,11 +50,11 @@
   TEncBinCABAC ();
   virtual ~TEncBinCABAC();
-  
+
   Void  init              ( TComBitIf* pcTComBitIf );
   Void  uninit            ();
-  
+
   Void  start             ();
   Void  finish            ();
-  Void  copyState         ( TEncBinIf* pcTEncBinIf );
+  Void  copyState         ( const TEncBinIf* pcTEncBinIf );
   Void  flush            ();
 
@@ -62,20 +62,24 @@
   Void  encodePCMAlignBits();
   Void  xWritePCMCode     ( UInt uiCode, UInt uiLength );
-  
+
   Void  resetBits         ();
   UInt  getNumWrittenBits ();
-  
+
   Void  encodeBin         ( UInt  binValue,  ContextModel& rcCtxModel );
   Void  encodeBinEP       ( UInt  binValue                            );
   Void  encodeBinsEP      ( UInt  binValues, Int numBins              );
   Void  encodeBinTrm      ( UInt  binValue                            );
-  
+
+  Void  align             ();
+  Void  encodeAlignedBinsEP( UInt  binValues, Int numBins             );
+
   TEncBinCABAC* getTEncBinCABAC()  { return this; }
-  
+  const TEncBinCABAC* getTEncBinCABAC() const { return this; }
+
   Void  setBinsCoded              ( UInt uiVal )  { m_uiBinsCoded = uiVal;               }
   UInt  getBinsCoded              ()              { return m_uiBinsCoded;                }
   Void  setBinCountingEnableFlag  ( Bool bFlag )  { m_binCountIncrement = bFlag ? 1 : 0; }
   Bool  getBinCountingEnableFlag  ()              { return m_binCountIncrement != 0;     }
-  
+
 #if FAST_BIT_EST
 protected:
@@ -85,5 +89,5 @@
   Void testAndWriteOut();
   Void writeOut();
-  
+
   TComBitIf*          m_pcTComBitIf;
   UInt                m_uiLow;
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,4 +38,6 @@
 #include "TEncBinCoderCABACCounter.h"
 #include "TLibCommon/TComRom.h"
+#include "TLibCommon/Debug.h"
+
 
 #if FAST_BIT_EST
@@ -72,8 +74,29 @@
 Void TEncBinCABACCounter::encodeBin( UInt binValue, ContextModel &rcCtxModel )
 {
+#if DEBUG_ENCODER_SEARCH_BINS
+  const UInt64 startingFracBits = m_fracBits;
+#endif
+
   m_uiBinsCoded += m_binCountIncrement;
-  
   m_fracBits += rcCtxModel.getEntropyBits( binValue );
   rcCtxModel.update( binValue );
+
+#if DEBUG_ENCODER_SEARCH_BINS
+  if ((g_debugCounter + debugEncoderSearchBinWindow) >= debugEncoderSearchBinTargetLine)
+  {
+    std::cout << g_debugCounter << ": coding bin value " << binValue << ", fracBits = [" << startingFracBits << "->" << m_fracBits << "]\n";
+  }
+
+  if (g_debugCounter >= debugEncoderSearchBinTargetLine)
+  {
+    Char breakPointThis;
+    breakPointThis = 7;
+  }
+  if (g_debugCounter >= (debugEncoderSearchBinTargetLine + debugEncoderSearchBinWindow))
+  {
+    exit(0);
+  }
+  g_debugCounter++;
+#endif
 }
 
@@ -83,5 +106,5 @@
  * \param binValue bin value
  */
-Void TEncBinCABACCounter::encodeBinEP( UInt binValue )
+Void TEncBinCABACCounter::encodeBinEP( UInt /*binValue*/ )
 {
   m_uiBinsCoded += m_binCountIncrement;
@@ -95,5 +118,5 @@
  * \param numBins number of bins
  */
-Void TEncBinCABACCounter::encodeBinsEP( UInt binValues, Int numBins )
+Void TEncBinCABACCounter::encodeBinsEP( UInt /*binValues*/, Int numBins )
 {
   m_uiBinsCoded += numBins & -m_binCountIncrement;
@@ -112,4 +135,9 @@
 }
 
+Void TEncBinCABACCounter::align()
+{
+  m_fracBits = (m_fracBits + 32767) & (~32767);
+}
+
 //! \}
 #endif
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,6 +36,6 @@
 */
 
-#ifndef __TENC_BIN_CODER_CABAC_COUNTER__
-#define __TENC_BIN_CODER_CABAC_COUNTER__
+#ifndef __TENCBINCODERCABACCOUNTER__
+#define __TENCBINCODERCABACCOUNTER__
 
 
@@ -53,5 +53,5 @@
   TEncBinCABACCounter ();
   virtual ~TEncBinCABACCounter();
-  
+
   Void  finish            ();
   UInt  getNumWrittenBits ();
@@ -61,5 +61,7 @@
   Void  encodeBinsEP      ( UInt  binValues, Int numBins              );
   Void  encodeBinTrm      ( UInt  binValue                            );
-  
+
+  Void  align             ();
+
 private:
 };
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,41 +39,35 @@
 #include "TEncCavlc.h"
 #include "SEIwrite.h"
-#include "../TLibCommon/TypeDef.h"
-#if H_3D
+
+#if NH_3D
 #include "TEncTop.h"
 #endif
+
 //! \ingroup TLibEncoder
 //! \{
 
-
 #if ENC_DEC_TRACE
 
-Void  xTraceSPSHeader (TComSPS *pSPS)
-{
-#if H_MV_ENC_DEC_TRAC
-  fprintf( g_hTrace, "=========== Sequence Parameter Set LayerId: %d ===========\n", pSPS->getLayerId() );
-#else
-  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
-#endif
-}
-
-Void  xTracePPSHeader (TComPPS *pPPS)
-{
-#if H_MV_ENC_DEC_TRAC
-  fprintf( g_hTrace, "=========== Picture Parameter Set LayerId: %d ===========\n", pPPS->getLayerId() );
-#else
-  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
-#endif
-}
-
-Void  xTraceSliceHeader (TComSlice *pSlice)
+#if !H_MV_ENC_DEC_TRAC
+Void  xTraceVPSHeader ()
+{
+  fprintf( g_hTrace, "=========== Video Parameter Set     ===========\n" );
+
+Void  xTraceSPSHeader ()
+{
+  fprintf( g_hTrace, "=========== Sequence Parameter Set  ===========\n" );
+}
+
+Void  xTracePPSHeader ()
+{
+  fprintf( g_hTrace, "=========== Picture Parameter Set  ===========\n");
+}
+
+Void  xTraceSliceHeader ( )
 {
   fprintf( g_hTrace, "=========== Slice ===========\n");
 }
-
-#endif
-
-
-
+#endif
+#endif
 // ====================================================================================================================
 // Constructor / destructor / create / destroy
@@ -83,5 +77,4 @@
 {
   m_pcBitIf           = NULL;
-  m_uiCoeffCost       = 0;
 }
 
@@ -95,19 +88,10 @@
 // ====================================================================================================================
 
-Void TEncCavlc::resetEntropy()
-{
-}
-
-
-Void TEncCavlc::codeDFFlag(UInt uiCode, const Char *pSymbolName)
-{
-  WRITE_FLAG(uiCode, pSymbolName);
-}
-Void TEncCavlc::codeDFSvlc(Int iCode, const Char *pSymbolName)
-{
-  WRITE_SVLC(iCode, pSymbolName);
-}
-
-Void TEncCavlc::codeShortTermRefPicSet( TComSPS* pcSPS, TComReferencePictureSet* rps, Bool calledFromSliceHeader, Int idx)
+Void TEncCavlc::resetEntropy(const TComSlice* /*pSlice*/)
+{
+}
+
+
+Void TEncCavlc::codeShortTermRefPicSet( const TComReferencePictureSet* rps, Bool calledFromSliceHeader, Int idx)
 {
 #if PRINT_RPS_INFO
@@ -132,6 +116,6 @@
     {
       Int refIdc = rps->getRefIdc(j);
-      WRITE_CODE( (refIdc==1? 1: 0), 1, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1 
-      if (refIdc != 1) 
+      WRITE_CODE( (refIdc==1? 1: 0), 1, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1
+      if (refIdc != 1)
       {
         WRITE_CODE( refIdc>>1, 1, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
@@ -143,5 +127,4 @@
     WRITE_UVLC( rps->getNumberOfNegativePictures(), "num_negative_pics" );
     WRITE_UVLC( rps->getNumberOfPositivePictures(), "num_positive_pics" );
-
     Int prev = 0;
     for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
@@ -149,5 +132,5 @@
       WRITE_UVLC( prev-rps->getDeltaPOC(j)-1, "delta_poc_s0_minus1" );
       prev = rps->getDeltaPOC(j);
-      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s0_flag"); 
+      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s0_flag");
     }
     prev = 0;
@@ -156,5 +139,5 @@
       WRITE_UVLC( rps->getDeltaPOC(j)-prev-1, "delta_poc_s1_minus1" );
       prev = rps->getDeltaPOC(j);
-      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s1_flag" ); 
+      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s1_flag" );
     }
   }
@@ -167,10 +150,13 @@
 
 
-Void TEncCavlc::codePPS( TComPPS* pcPPS )
-{
-#if ENC_DEC_TRACE  
-  xTracePPSHeader (pcPPS);
-#endif
-  
+Void TEncCavlc::codePPS( const TComPPS* pcPPS )
+{
+#if ENC_DEC_TRACE
+#if H_MV_ENC_DEC_TRAC
+  tracePSHeader( "PPS", pcPPS->getLayerId() ); 
+#else
+  xTracePPSHeader ();
+#endif
+#endif
   WRITE_UVLC( pcPPS->getPPSId(),                             "pps_pic_parameter_set_id" );
   WRITE_UVLC( pcPPS->getSPSId(),                             "pps_seq_parameter_set_id" );
@@ -196,5 +182,5 @@
   WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "init_qp_minus26");
   WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
-  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" ); 
+  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" );
   WRITE_FLAG( pcPPS->getUseDQP() ? 1 : 0, "cu_qp_delta_enabled_flag" );
   if ( pcPPS->getUseDQP() )
@@ -202,6 +188,8 @@
     WRITE_UVLC( pcPPS->getMaxCuDQPDepth(), "diff_cu_qp_delta_depth" );
   }
-  WRITE_SVLC( pcPPS->getChromaCbQpOffset(),                   "pps_cb_qp_offset" );
-  WRITE_SVLC( pcPPS->getChromaCrQpOffset(),                   "pps_cr_qp_offset" );
+
+  WRITE_SVLC( pcPPS->getQpOffset(COMPONENT_Cb), "pps_cb_qp_offset" );
+  WRITE_SVLC( pcPPS->getQpOffset(COMPONENT_Cr), "pps_cr_qp_offset" );
+
   WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "pps_slice_chroma_qp_offsets_present_flag" );
 
@@ -214,5 +202,5 @@
   {
     WRITE_UVLC( pcPPS->getNumTileColumnsMinus1(),                                    "num_tile_columns_minus1" );
-    WRITE_UVLC( pcPPS->getTileNumRowsMinus1(),                                       "num_tile_rows_minus1" );
+    WRITE_UVLC( pcPPS->getNumTileRowsMinus1(),                                       "num_tile_rows_minus1" );
     WRITE_FLAG( pcPPS->getTileUniformSpacingFlag(),                                  "uniform_spacing_flag" );
     if( !pcPPS->getTileUniformSpacingFlag() )
@@ -222,19 +210,19 @@
         WRITE_UVLC( pcPPS->getTileColumnWidth(i)-1,                                  "column_width_minus1" );
       }
-      for(UInt i=0; i<pcPPS->getTileNumRowsMinus1(); i++)
+      for(UInt i=0; i<pcPPS->getNumTileRowsMinus1(); i++)
       {
         WRITE_UVLC( pcPPS->getTileRowHeight(i)-1,                                    "row_height_minus1" );
       }
     }
-    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getTileNumRowsMinus1() !=0)
+    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getNumTileRowsMinus1() !=0)
     {
       WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
     }
   }
-  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "loop_filter_across_slices_enabled_flag");
+  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "pps_loop_filter_across_slices_enabled_flag");
   WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
   if(pcPPS->getDeblockingFilterControlPresentFlag())
   {
-    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" ); 
+    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" );
     WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag() ? 1 : 0,       "pps_disable_deblocking_filter_flag" );
     if(!pcPPS->getPicDisableDeblockingFilterFlag())
@@ -244,8 +232,8 @@
     }
   }
-  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
+  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" );
   if( pcPPS->getScalingListPresentFlag() )
   {
-    codeScalingList( m_pcSlice->getScalingList() );
+    codeScalingList( pcPPS->getScalingList() );
   }
 #if PPS_FIX_DEPTH
@@ -259,48 +247,128 @@
   WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
   WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
-
-  #if H_3D
-    if(( !pcPPS->getSPS()->getVPS()->getDepthId( pcPPS->getSPS()->getLayerId() ) )||
-        pcPPS->getLayerId() != 1  )
-    {
-      pcPPS->setPps3dExtensionFlag( false ); 
-    }
-  #endif
-
-#if !H_MV
-  WRITE_FLAG( 0, "pps_extension_flag" );
+#if !NH_MV
+  Bool pps_extension_present_flag=false;
+  Bool pps_extension_flags[NUM_PPS_EXTENSION_FLAGS]={false};
+
+  pps_extension_flags[PPS_EXT__REXT] = pcPPS->getPpsRangeExtension().settingsDifferFromDefaults(pcPPS->getUseTransformSkip());
+
+  // Other PPS extension flags checked here.
+
+  for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
+  {
+    pps_extension_present_flag|=pps_extension_flags[i];
+  }
+
+  WRITE_FLAG( (pps_extension_present_flag?1:0), "pps_extension_present_flag" );
+
+  if (pps_extension_present_flag)
+  {
+#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
+    static const char *syntaxStrings[]={ "pps_range_extension_flag",
+                                         "pps_multilayer_extension_flag",
+                                         "pps_extension_6bits[0]",
+                                         "pps_extension_6bits[1]",
+                                         "pps_extension_6bits[2]",
+                                         "pps_extension_6bits[3]",
+                                         "pps_extension_6bits[4]",
+                                         "pps_extension_6bits[5]" };
+#endif
+
+    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
+    {
+      WRITE_FLAG( pps_extension_flags[i]?1:0, syntaxStrings[i] );
+    }
+
+    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
+    {
+      if (pps_extension_flags[i])
+      {
+        switch (PPSExtensionFlagIndex(i))
+        {
+          case PPS_EXT__REXT:
+            {
+              const TComPPSRExt &ppsRangeExtension = pcPPS->getPpsRangeExtension();
+            if (pcPPS->getUseTransformSkip())
+            {
+                WRITE_UVLC( ppsRangeExtension.getLog2MaxTransformSkipBlockSize()-2,            "log2_max_transform_skip_block_size_minus2");
+            }
+
+              WRITE_FLAG((ppsRangeExtension.getCrossComponentPredictionEnabledFlag() ? 1 : 0), "cross_component_prediction_enabled_flag" );
+
+              WRITE_FLAG(UInt(ppsRangeExtension.getChromaQpOffsetListEnabledFlag()),           "chroma_qp_offset_list_enabled_flag" );
+              if (ppsRangeExtension.getChromaQpOffsetListEnabledFlag())
+            {
+                WRITE_UVLC(ppsRangeExtension.getDiffCuChromaQpOffsetDepth(),                   "diff_cu_chroma_qp_offset_depth");
+                WRITE_UVLC(ppsRangeExtension.getChromaQpOffsetListLen() - 1,                   "chroma_qp_offset_list_len_minus1");
+              /* skip zero index */
+                for (Int cuChromaQpOffsetIdx = 0; cuChromaQpOffsetIdx < ppsRangeExtension.getChromaQpOffsetListLen(); cuChromaQpOffsetIdx++)
+              {
+                  WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CbOffset,     "cb_qp_offset_list[i]");
+                  WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CrOffset,     "cr_qp_offset_list[i]");
+              }
+            }
+
+              WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA),           "log2_sao_offset_scale_luma"   );
+              WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA),         "log2_sao_offset_scale_chroma" );
+            }
+            break;
+          default:
+            assert(pps_extension_flags[i]==false); // Should never get here with an active PPS extension flag.
+            break;
+        } // switch
+      } // if flag present
+    } // loop over PPS flags
+  } // pps_extension_present_flag is non-zero
 #else
-  WRITE_FLAG( 1, "pps_extension_present_flag" );
+    WRITE_FLAG( 1, "pps_extension_present_flag" );
 
     WRITE_FLAG( pcPPS->getPpsRangeExtensionsFlag( ) ? 1 : 0 , "pps_range_extensions_flag" );
     WRITE_FLAG( pcPPS->getPpsMultilayerExtensionFlag( ) ? 1 : 0 , "pps_multilayer_extension_flag" );
-#if !H_3D
-    WRITE_CODE( pcPPS->getPpsExtension6bits( ), 6, "pps_extension_6bits" );
-#else
     WRITE_FLAG( pcPPS->getPps3dExtensionFlag( ) ? 1 : 0 , "pps_3d_extension_flag" );
     WRITE_CODE( pcPPS->getPpsExtension5bits( ), 5, "pps_extension_5bits" );
-#endif
     if ( pcPPS->getPpsRangeExtensionsFlag() )
     { 
-      assert(0); 
+              const TComPPSRExt &ppsRangeExtension = pcPPS->getPpsRangeExtension();
+              if (pcPPS->getUseTransformSkip())
+              {
+                WRITE_UVLC( ppsRangeExtension.getLog2MaxTransformSkipBlockSize()-2,            "log2_max_transform_skip_block_size_minus2");
+              }
+
+              WRITE_FLAG((ppsRangeExtension.getCrossComponentPredictionEnabledFlag() ? 1 : 0), "cross_component_prediction_enabled_flag" );
+
+              WRITE_FLAG(UInt(ppsRangeExtension.getChromaQpOffsetListEnabledFlag()),           "chroma_qp_offset_list_enabled_flag" );
+              if (ppsRangeExtension.getChromaQpOffsetListEnabledFlag())
+              {
+                WRITE_UVLC(ppsRangeExtension.getDiffCuChromaQpOffsetDepth(),                   "diff_cu_chroma_qp_offset_depth");
+                WRITE_UVLC(ppsRangeExtension.getChromaQpOffsetListLen() - 1,                   "chroma_qp_offset_list_len_minus1");
+                /* skip zero index */
+                for (Int cuChromaQpOffsetIdx = 0; cuChromaQpOffsetIdx < ppsRangeExtension.getChromaQpOffsetListLen(); cuChromaQpOffsetIdx++)
+                {
+                  WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CbOffset,     "cb_qp_offset_list[i]");
+                  WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CrOffset,     "cr_qp_offset_list[i]");
+                }
+              }
+
+              WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA),           "log2_sao_offset_scale_luma"   );
+              WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA),         "log2_sao_offset_scale_chroma" );
     }
 
     if ( pcPPS->getPpsMultilayerExtensionFlag() )
     { 
-      codePPSMultilayerExtension( pcPPS );
-    }
-
-#if H_3D
+      codePpsMultilayerExtension( pcPPS );
+    }
+
+#if NH_3D
     if( pcPPS->getPps3dExtensionFlag( )  ) // This probably needs to be aligned with Rext and SHVC
     {
-      codePPSExtension( pcPPS ); 
-    }
-#endif
-#endif
-
-}
-
-#if H_3D
-Void  TEncCavlc::codePPSExtension        ( TComPPS* pcPPS )
+      codePps3dExtension( pcPPS ); 
+    }
+#endif
+#endif
+  xWriteRbspTrailingBits();
+}
+
+#if NH_3D
+Void  TEncCavlc::codePps3dExtension        ( const TComPPS* pcPPS )
 {
   // Assuming that all PPS indirectly refer to the same VPS via different SPS
@@ -311,8 +379,10 @@
   //   Step 2) mapping DLT tables to the depth layers
   // as described in the 3D-HEVC WD.
-  TComVPS* pcVPS = pcPPS->getSPS()->getVPS();
-
-  TComDLT* pcDLT = pcPPS->getDLT();
-
+
+  // GT: Please remove dependency from VPS in the encoding as well as in the parsing function, e.g. using the equivalent process.
+  // GT: Moreover this function should only carry out the coding of the DLT and NO rate based decisions.
+  // GT: Please add a function e.g. xSetDLT in e.g. TEncSlice to find the best DLT syntax representation and do ONLY the coding of the DLT here !!
+
+#if H_3D
   WRITE_FLAG( pcDLT->getDltPresentFlag() ? 1 : 0, "dlt_present_flag" );
 
@@ -476,8 +546,9 @@
     }
   }
-}
-#endif
-
-Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
+#endif
+}
+#endif
+
+Void TEncCavlc::codeVUI( const TComVUI *pcVUI, const TComSPS* pcSPS )
 {
 #if ENC_DEC_TRACE
@@ -500,5 +571,5 @@
   }
   WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
-#if H_MV
+#if NH_MV
   assert( pcSPS->getLayerId() == 0 || !pcVUI->getVideoSignalTypePresentFlag() ); 
 #endif
@@ -512,5 +583,5 @@
       WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
       WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
-      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
+      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coeffs");
     }
   }
@@ -536,5 +607,5 @@
     WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset()/ TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_bottom_offset");
   }
-  TimingInfo *timingInfo = pcVUI->getTimingInfo();
+  const TimingInfo *timingInfo = pcVUI->getTimingInfo();
   WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
   if(timingInfo->getTimingInfoPresentFlag())
@@ -547,9 +618,9 @@
       WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
     }
-  WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
-  if( pcVUI->getHrdParametersPresentFlag() )
-  {
-    codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
-  }
+    WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "vui_hrd_parameters_present_flag");
+    if( pcVUI->getHrdParametersPresentFlag() )
+    {
+      codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
+    }
   }
 
@@ -562,5 +633,5 @@
     WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
     WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
-    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
+    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_min_cu_denom");
     WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
     WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
@@ -568,5 +639,5 @@
 }
 
-Void TEncCavlc::codeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
+Void TEncCavlc::codeHrdParameters( const TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
 {
   if( commonInfPresentFlag )
@@ -576,9 +647,9 @@
     if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
     {
-      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_cpb_params_present_flag" );
+      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_hrd_params_present_flag" );
       if( hrd->getSubPicCpbParamsPresentFlag() )
       {
         WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
-        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
+        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_increment_length_minus1" );
         WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
         WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
@@ -588,5 +659,5 @@
       if( hrd->getSubPicCpbParamsPresentFlag() )
       {
-        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" ); 
+        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" );
       }
       WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
@@ -599,18 +670,16 @@
   {
     WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
+    Bool fixedPixRateWithinCvsFlag = true;
     if( !hrd->getFixedPicRateFlag( i ) )
     {
+      fixedPixRateWithinCvsFlag = hrd->getFixedPicRateWithinCvsFlag( i );
       WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
     }
+    if( fixedPixRateWithinCvsFlag )
+    {
+      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
+    }
     else
     {
-      hrd->setFixedPicRateWithinCvsFlag( i, true );
-    }
-    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
-    {
-      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
-    }
-    else
-    {
       WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
     }
@@ -619,5 +688,5 @@
       WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
     }
-    
+
     for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
     {
@@ -631,5 +700,5 @@
           if( hrd->getSubPicCpbParamsPresentFlag() )
           {
-            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1");  
+            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1");
             WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
           }
@@ -641,16 +710,24 @@
 }
 
-Void TEncCavlc::codeSPS( TComSPS* pcSPS )
-{
-#if ENC_DEC_TRACE  
-  xTraceSPSHeader (pcSPS);
+Void TEncCavlc::codeSPS( const TComSPS* pcSPS )
+{
+
+  const ChromaFormat format                = pcSPS->getChromaFormatIdc();
+  const Bool         chromaEnabled         = isChromaEnabled(format);
+
+#if ENC_DEC_TRACE
+#if H_MV_ENC_DEC_TRAC
+  tracePSHeader( "SPS", pcSPS->getLayerId() ); 
+#else
+  xTraceSPSHeader ();
+#endif
 #endif
   WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
-#if H_MV
+#if NH_MV
   if ( pcSPS->getLayerId() == 0 )
   {
 #endif
   WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
-#if H_MV
+#if NH_MV
   }
   else
@@ -661,12 +738,11 @@
   {
 #endif
-
-  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "sps_temporal_id_nesting_flag" );
+  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0, "sps_temporal_id_nesting_flag" );
   codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
-#if H_MV
+#if NH_MV
 }
 #endif
   WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
-#if H_MV
+#if NH_MV
     if ( pcSPS->getMultiLayerExtSpsFlag() )
   {
@@ -680,10 +756,6 @@
   {
 #endif
-  WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
-#if !H_3D_DISABLE_CHROMA
-  assert(pcSPS->getChromaFormatIdc () == 1);
-#endif
-  // in the first version chroma_format_idc can only be equal to 1 (4:2:0)
-  if( pcSPS->getChromaFormatIdc () == 3 )
+  WRITE_UVLC( Int(pcSPS->getChromaFormatIdc ()),    "chroma_format_idc" );
+  if( format == CHROMA_444 )
   {
     WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
@@ -702,22 +774,24 @@
     WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
   }
-#if H_MV
-}
-#endif
-
-#if H_MV
+#if NH_MV
+}
+#endif
+#if NH_MV
   if ( !pcSPS->getMultiLayerExtSpsFlag() )
   { 
 #endif
-  WRITE_UVLC( pcSPS->getBitDepthY() - 8,             "bit_depth_luma_minus8" );
-  WRITE_UVLC( pcSPS->getBitDepthC() - 8,             "bit_depth_chroma_minus8" );
-#if H_MV
+
+  WRITE_UVLC( pcSPS->getBitDepth(CHANNEL_TYPE_LUMA) - 8,                      "bit_depth_luma_minus8" );
+
+  WRITE_UVLC( chromaEnabled ? (pcSPS->getBitDepth(CHANNEL_TYPE_CHROMA) - 8):0,  "bit_depth_chroma_minus8" );
+#if NH_MV
   }
 #endif
   WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
-#if H_MV
+#if NH_MV
   if ( !pcSPS->getMultiLayerExtSpsFlag()) 
   {  
 #endif
+
   const Bool subLayerOrderingInfoPresentFlag = 1;
   WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
@@ -725,5 +799,5 @@
   {
     WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
-    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
+    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_max_num_reorder_pics[i]" );
     WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
     if (!subLayerOrderingInfoPresentFlag)
@@ -732,20 +806,19 @@
     }
   }
-#if H_MV
+#if NH_MV
   }
 #endif
 
   assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
-  
-  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
-  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
-  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
-  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
+  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_luma_coding_block_size_minus3" );
+  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_luma_coding_block_size" );
+  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_luma_transform_block_size_minus2" );
+  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_luma_transform_block_size" );
   WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
   WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
-  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
+  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" );
   if(pcSPS->getScalingListFlag())
   {
-#if H_MV
+#if NH_MV
     if ( pcSPS->getMultiLayerExtSpsFlag() )
     {    
@@ -760,10 +833,11 @@
     {    
 #endif
-    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
+
+    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" );
     if(pcSPS->getScalingListPresentFlag())
     {
-      codeScalingList( m_pcSlice->getScalingList() );
-    }
-#if H_MV
+      codeScalingList( pcSPS->getScalingList() );
+    }
+#if NH_MV
     }
 #endif
@@ -775,6 +849,6 @@
   if( pcSPS->getUsePCM() )
   {
-    WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,                                  "pcm_sample_bit_depth_luma_minus1" );
-    WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4,                                "pcm_sample_bit_depth_chroma_minus1" );
+    WRITE_CODE( pcSPS->getPCMBitDepth(CHANNEL_TYPE_LUMA) - 1, 4,                            "pcm_sample_bit_depth_luma_minus1" );
+    WRITE_CODE( chromaEnabled ? (pcSPS->getPCMBitDepth(CHANNEL_TYPE_CHROMA) - 1) : 0, 4,    "pcm_sample_bit_depth_chroma_minus1" );
     WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_luma_coding_block_size_minus3" );
     WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_luma_coding_block_size" );
@@ -782,23 +856,22 @@
   }
 
-  assert( pcSPS->getMaxTLayers() > 0 );         
-
-  TComRPSList* rpsList = pcSPS->getRPSList();
-  TComReferencePictureSet*      rps;
+  assert( pcSPS->getMaxTLayers() > 0 );
+
+  const TComRPSList* rpsList = pcSPS->getRPSList();
 
   WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
   for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
   {
-    rps = rpsList->getReferencePictureSet(i);
-    codeShortTermRefPicSet(pcSPS,rps,false, i);
+    const TComReferencePictureSet*rps = rpsList->getReferencePictureSet(i);
+    codeShortTermRefPicSet( rps,false, i);
   }
   WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
-  if (pcSPS->getLongTermRefsPresent()) 
-  {
-    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
+  if (pcSPS->getLongTermRefsPresent())
+  {
+    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pics_sps" );
     for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
     {
       WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
-      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
+      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag[i]");
     }
   }
@@ -813,6 +886,65 @@
   }
 
-#if !H_MV
-  WRITE_FLAG( 0, "sps_extension_flag" );
+#if !NH_MV
+  Bool sps_extension_present_flag=false;
+  Bool sps_extension_flags[NUM_SPS_EXTENSION_FLAGS]={false};
+
+  sps_extension_flags[SPS_EXT__REXT] = pcSPS->getSpsRangeExtension().settingsDifferFromDefaults();
+
+  // Other SPS extension flags checked here.
+
+  for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
+  {
+    sps_extension_present_flag|=sps_extension_flags[i];
+  }
+
+  WRITE_FLAG( (sps_extension_present_flag?1:0), "sps_extension_present_flag" );
+
+  if (sps_extension_present_flag)
+  {
+#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
+    static const char *syntaxStrings[]={ "sps_range_extension_flag",
+      "sps_multilayer_extension_flag",
+      "sps_extension_6bits[0]",
+      "sps_extension_6bits[1]",
+      "sps_extension_6bits[2]",
+      "sps_extension_6bits[3]",
+      "sps_extension_6bits[4]",
+      "sps_extension_6bits[5]" };
+#endif
+
+    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
+    {
+      WRITE_FLAG( sps_extension_flags[i]?1:0, syntaxStrings[i] );
+    }
+
+    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
+    {
+      if (sps_extension_flags[i])
+      {
+        switch (SPSExtensionFlagIndex(i))
+        {
+        case SPS_EXT__REXT:
+          {
+            const TComSPSRExt &spsRangeExtension=pcSPS->getSpsRangeExtension();
+
+            WRITE_FLAG( (spsRangeExtension.getTransformSkipRotationEnabledFlag() ? 1 : 0),      "transform_skip_rotation_enabled_flag");
+            WRITE_FLAG( (spsRangeExtension.getTransformSkipContextEnabledFlag() ? 1 : 0),       "transform_skip_context_enabled_flag");
+            WRITE_FLAG( (spsRangeExtension.getRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT) ? 1 : 0), "implicit_rdpcm_enabled_flag" );
+            WRITE_FLAG( (spsRangeExtension.getRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT) ? 1 : 0), "explicit_rdpcm_enabled_flag" );
+            WRITE_FLAG( (spsRangeExtension.getExtendedPrecisionProcessingFlag() ? 1 : 0),       "extended_precision_processing_flag" );
+            WRITE_FLAG( (spsRangeExtension.getIntraSmoothingDisabledFlag() ? 1 : 0),            "intra_smoothing_disabled_flag" );
+            WRITE_FLAG( (spsRangeExtension.getHighPrecisionOffsetsEnabledFlag() ? 1 : 0),       "high_precision_offsets_enabled_flag" );
+            WRITE_FLAG( (spsRangeExtension.getPersistentRiceAdaptationEnabledFlag() ? 1 : 0),   "persistent_rice_adaptation_enabled_flag" );
+            WRITE_FLAG( (spsRangeExtension.getCabacBypassAlignmentEnabledFlag() ? 1 : 0),       "cabac_bypass_alignment_enabled_flag" );
+          break;
+          }
+        default:
+          assert(sps_extension_flags[i]==false); // Should never get here with an active SPS extension flag.
+          break;
+        }
+      }
+    }
+  }
 #else
   WRITE_FLAG( pcSPS->getSpsExtensionPresentFlag(), "sps_extension_present_flag" );
@@ -820,17 +952,23 @@
   if ( pcSPS->getSpsExtensionPresentFlag() )
   {
-    WRITE_FLAG( pcSPS->getSpsRangeExtensionsFlag( ) ? 1 : 0 , "sps_range_extensions_flag" );
+    WRITE_FLAG( pcSPS->getSpsRangeExtensionsFlag( )     ? 1 : 0 , "sps_range_extensions_flag" );
     WRITE_FLAG( pcSPS->getSpsMultilayerExtensionFlag( ) ? 1 : 0 , "sps_multilayer_extension_flag" );
-#if !H_3D
-    WRITE_CODE( pcSPS->getSpsExtension6bits( ), 6, "sps_extension_6bits" );  
-#else
-    WRITE_FLAG( pcSPS->getSps3dExtensionFlag( ) ? 1 : 0 , "sps_3d_extension_flag" );
-    WRITE_CODE( pcSPS->getSpsExtension5bits( ), 5, "sps_extension_5bits" );
-#endif
+    WRITE_FLAG( pcSPS->getSps3dExtensionFlag( )         ? 1 : 0 , "sps_3d_extension_flag" );
+    WRITE_CODE( pcSPS->getSpsExtension5bits( )              , 5 , "sps_extension_5bits" );
   }
 
   if ( pcSPS->getSpsRangeExtensionsFlag() )
   {
-    assert( 0 ); 
+    const TComSPSRExt &spsRangeExtension=pcSPS->getSpsRangeExtension();
+
+    WRITE_FLAG( (spsRangeExtension.getTransformSkipRotationEnabledFlag() ? 1 : 0),      "transform_skip_rotation_enabled_flag");
+    WRITE_FLAG( (spsRangeExtension.getTransformSkipContextEnabledFlag() ? 1 : 0),       "transform_skip_context_enabled_flag");
+    WRITE_FLAG( (spsRangeExtension.getRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT) ? 1 : 0), "implicit_rdpcm_enabled_flag" );
+    WRITE_FLAG( (spsRangeExtension.getRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT) ? 1 : 0), "explicit_rdpcm_enabled_flag" );
+    WRITE_FLAG( (spsRangeExtension.getExtendedPrecisionProcessingFlag() ? 1 : 0),       "extended_precision_processing_flag" );
+    WRITE_FLAG( (spsRangeExtension.getIntraSmoothingDisabledFlag() ? 1 : 0),            "intra_smoothing_disabled_flag" );
+    WRITE_FLAG( (spsRangeExtension.getHighPrecisionOffsetsEnabledFlag() ? 1 : 0),       "high_precision_offsets_enabled_flag" );
+    WRITE_FLAG( (spsRangeExtension.getPersistentRiceAdaptationEnabledFlag() ? 1 : 0),   "persistent_rice_adaptation_enabled_flag" );
+    WRITE_FLAG( (spsRangeExtension.getCabacBypassAlignmentEnabledFlag() ? 1 : 0),       "cabac_bypass_alignment_enabled_flag" );
   }
 
@@ -840,5 +978,5 @@
   }
 
-#if H_3D
+#if NH_3D
   if ( pcSPS->getSps3dExtensionFlag() )
   {
@@ -848,9 +986,9 @@
 #endif
 #endif
-
-}
-
-#if H_MV
-Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
+  xWriteRbspTrailingBits();
+}
+
+#if NH_MV
+Void TEncCavlc::codeSPSExtension( const TComSPS* pcSPS )
 {
   WRITE_FLAG( pcSPS->getInterViewMvVertConstraintFlag() ? 1 : 0, "inter_view_mv_vert_constraint_flag" );
@@ -858,5 +996,5 @@
 
 
-Void TEncCavlc::codePPSMultilayerExtension(TComPPS* pcPPS)
+Void TEncCavlc::codePpsMultilayerExtension(const TComPPS* pcPPS)
 {
   WRITE_FLAG( pcPPS->getPocResetInfoPresentFlag( ) ? 1 : 0 , "poc_reset_info_present_flag" );
@@ -873,8 +1011,8 @@
 #endif
 
-#if H_3D
-Void TEncCavlc::codeSPS3dExtension( TComSPS* pcSPS )
-{
-  TComSps3dExtension* sps3dExt = pcSPS->getSps3dExtension();
+#if NH_3D
+Void TEncCavlc::codeSPS3dExtension( const TComSPS* pcSPS )
+{
+  const TComSps3dExtension* sps3dExt = pcSPS->getSps3dExtension();
   for( Int d = 0; d  <=  1; d++ )
   {
@@ -904,24 +1042,30 @@
 
 
-
-
-Void TEncCavlc::codeVPS( TComVPS* pcVPS )
-{
+Void TEncCavlc::codeVPS( const TComVPS* pcVPS )
+{
+#if ENC_DEC_TRACE
+#if H_MV_ENC_DEC_TRAC
+  tracePSHeader( "VPS", getEncTop()->getLayerId() ); 
+#else
+  xTraceVPSHeader();
+#endif
+#endif
   WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
-#if H_MV
+#if NH_MV
   WRITE_FLAG( pcVPS->getVpsBaseLayerInternalFlag( ) ? 1 : 0 , "vps_base_layer_internal_flag" );
   WRITE_FLAG( pcVPS->getVpsBaseLayerAvailableFlag( ) ? 1 : 0 , "vps_base_layer_available_flag" );
 #else
-  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
-#endif
-#if H_MV
+  WRITE_FLAG(                                       1,        "vps_base_layer_internal_flag" );
+  WRITE_FLAG(                                       1,        "vps_base_layer_available_flag" );
+#endif
+#if NH_MV
   WRITE_CODE( pcVPS->getMaxLayersMinus1(),       6,        "vps_max_layers_minus1" );
 #else
-  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
+  WRITE_CODE( 0,                                    6,        "vps_max_layers_minus1" );
 #endif
   WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
   WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
   assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
-  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
+  WRITE_CODE( 0xffff,                              16,        "vps_reserved_0xffff_16bits" );
   codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
   const Bool subLayerOrderingInfoPresentFlag = 1;
@@ -930,5 +1074,5 @@
   {
     WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
-    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
+    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_max_num_reorder_pics[i]" );
     WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
     if (!subLayerOrderingInfoPresentFlag)
@@ -937,6 +1081,7 @@
     }
   }
+
   assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
-#if H_MV
+#if NH_MV
   assert( pcVPS->getVpsMaxLayerId() < MAX_VPS_NUH_LAYER_ID_PLUS1 );
   WRITE_CODE( pcVPS->getVpsMaxLayerId(), 6,                 "vps_max_layer_id" );  
@@ -949,7 +1094,6 @@
 #else
   assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
-  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_nuh_reserved_zero_layer_id" );
-  pcVPS->setMaxOpSets(1);
-  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_max_op_sets_minus1" );
+  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_layer_id" );
+  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_num_layer_sets_minus1" );
   for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
   {
@@ -958,10 +1102,10 @@
     {
       // Only applicable for version 1
-      pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
+      // pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
 #endif
       WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
     }
   }
-  TimingInfo *timingInfo = pcVPS->getTimingInfo();
+  const TimingInfo *timingInfo = pcVPS->getTimingInfo();
   WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
   if(timingInfo->getTimingInfoPresentFlag())
@@ -974,28 +1118,25 @@
       WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
     }
-    pcVPS->setNumHrdParameters( 0 );
     WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
 
     if( pcVPS->getNumHrdParameters() > 0 )
     {
-      pcVPS->createHrdParamBuffer();
-    }
-    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
-    {
-      // Only applicable for version 1
-      pcVPS->setHrdOpSetIdx( 0, i );
-      WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_op_set_idx" );
-      if( i > 0 )
-      {
-        WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
-      }
-      codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
-    }
-  }
-#if H_MV
+      for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
+      {
+        // Only applicable for version 1
+        WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_layer_set_idx" );
+        if( i > 0 )
+        {
+          WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
+        }
+        codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
+      }
+    }
+  }
+#if NH_MV
   WRITE_FLAG( pcVPS->getVpsExtensionFlag(),                     "vps_extension_flag" );
   m_pcBitIf->writeAlignOne();
   codeVPSExtension( pcVPS );                           
-#if H_3D
+#if NH_3D
   WRITE_FLAG( 1,                     "vps_extension2_flag" );  
   WRITE_FLAG( 1,                     "vps_3d_extension_flag" );
@@ -1009,13 +1150,11 @@
   WRITE_FLAG( 0,                     "vps_extension_flag" );
 #endif
+
   //future extensions here..
-
-  return;
-}
-
-
-
-#if H_MV
-Void TEncCavlc::codeVPSExtension( TComVPS *pcVPS ) 
+  xWriteRbspTrailingBits();
+}
+
+#if NH_MV
+Void TEncCavlc::codeVPSExtension( const TComVPS *pcVPS ) 
 { 
   if( pcVPS->getMaxLayersMinus1() > 0  &&  pcVPS->getVpsBaseLayerInternalFlag() )
@@ -1037,6 +1176,6 @@
 
   if ( pcVPS->getSplittingFlag() )
-  {
-    pcVPS->setDimensionIdLen( pcVPS->getNumScalabilityTypes( ) - 1 ,pcVPS->inferLastDimsionIdLenMinus1() + 1 );       
+  {   
+    assert( pcVPS->getDimensionIdLen( pcVPS->getNumScalabilityTypes( ) - 1 ) == pcVPS->inferLastDimsionIdLenMinus1() + 1 );
   }    
 
@@ -1213,9 +1352,7 @@
   for (Int i = 0; i <= pcVPS->getVpsNumRepFormatsMinus1(); i++ )
   {    
-
-    TComRepFormat* curRepFormat = pcVPS->getRepFormat(i);     
-    TComRepFormat* prevRepFormat = i > 0 ? pcVPS->getRepFormat( i - 1) : NULL; 
+    const TComRepFormat* curRepFormat = pcVPS->getRepFormat(i);     
+    const TComRepFormat* prevRepFormat = i > 0 ? pcVPS->getRepFormat( i - 1) : NULL; 
     codeRepFormat( i, curRepFormat ,  prevRepFormat); 
-
   }
 
@@ -1291,12 +1428,12 @@
   else
   {
-    TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+    const TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
     assert( pcVPSVUI ); 
-    pcVPSVUI->inferVpsVui( true ); 
-  }
-
-}
-
-Void TEncCavlc::codeVideoSignalInfo( TComVideoSignalInfo* pcVideoSignalInfo )
+    assert( !pcVPSVUI->getCrossLayerIrapAlignedFlag() );     
+  }
+
+}
+
+Void TEncCavlc::codeVideoSignalInfo( const TComVideoSignalInfo* pcVideoSignalInfo )
 {
   assert( pcVideoSignalInfo ); 
@@ -1308,8 +1445,7 @@
 }
 
-Void TEncCavlc::codeDpbSize( TComVPS* vps )
+Void TEncCavlc::codeDpbSize( const TComVPS* vps )
 { 
-  TComDpbSize* dpbSize = vps->getDpbSize(); 
-  assert ( dpbSize != 0 ); 
+  const TComDpbSize * dpbSize = vps->getDpbSize(); 
 
   for( Int i = 1; i < vps->getNumOutputLayerSets(); i++ )
@@ -1361,5 +1497,5 @@
 }
 
-Void TEncCavlc::codeRepFormat( Int i, TComRepFormat* pcRepFormat, TComRepFormat* pcPrevRepFormat )
+Void TEncCavlc::codeRepFormat( Int i, const TComRepFormat* pcRepFormat, const TComRepFormat* pcPrevRepFormat )
 {
   assert( pcRepFormat ); 
@@ -1384,5 +1520,5 @@
   else
   {
-    pcRepFormat->inferChromaAndBitDepth(pcPrevRepFormat, true ); 
+    pcRepFormat->checkInferChromaAndBitDepth(pcPrevRepFormat ); 
   }
   WRITE_FLAG( pcRepFormat->getConformanceWindowVpsFlag( ) ? 1 : 0 , "conformance_window_vps_flag" );
@@ -1396,9 +1532,9 @@
 }
 
-Void TEncCavlc::codeVPSVUI( TComVPS* pcVPS )
+Void TEncCavlc::codeVPSVUI( const TComVPS* pcVPS )
 {
   assert( pcVPS ); 
 
-  TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+  const TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
 
   assert( pcVPSVUI ); 
@@ -1457,5 +1593,5 @@
   {
     assert( pcVPSVUI->getVideoSignalInfo( i ) != NULL ); 
-    TComVideoSignalInfo* curVideoSignalInfo = pcVPSVUI->getVideoSignalInfo( i ); 
+    const TComVideoSignalInfo* curVideoSignalInfo = pcVPSVUI->getVideoSignalInfo( i ); 
     codeVideoSignalInfo( curVideoSignalInfo );     
 
@@ -1543,13 +1679,13 @@
 }
 
-Void TEncCavlc::codeVpsVuiBspHrdParameters( TComVPS* pcVPS )
+Void TEncCavlc::codeVpsVuiBspHrdParameters( const TComVPS* pcVPS )
 {
   assert( pcVPS ); 
 
-  TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+  const TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
 
   assert( pcVPSVUI ); 
 
-  TComVpsVuiBspHrdParameters*  vpsVuiBspHrdP = pcVPSVUI->getVpsVuiBspHrdParameters(); 
+  const TComVpsVuiBspHrdParameters*  vpsVuiBspHrdP = pcVPSVUI->getVpsVuiBspHrdParameters(); 
 
   assert ( vpsVuiBspHrdP );
@@ -1564,5 +1700,5 @@
     }
     WRITE_UVLC( vpsVuiBspHrdP->getNumSubLayerHrdMinus1( i ), "num_sub_layer_hrd_minus1" );
-    TComHRD* hrdParameters = vpsVuiBspHrdP->getHrdParametermeters( i ); 
+    const TComHRD* hrdParameters = vpsVuiBspHrdP->getHrdParametermeters( i ); 
     codeHrdParameters( hrdParameters, vpsVuiBspHrdP->getCprmsAddPresentFlag( i ), vpsVuiBspHrdP->getNumSubLayerHrdMinus1( i ) );     
   }
@@ -1599,10 +1735,9 @@
     }
   }  
-
 }  
 #endif
 
-#if H_3D
-Void TEncCavlc::codeVPS3dExtension( TComVPS* pcVPS )
+#if NH_3D
+Void TEncCavlc::codeVPS3dExtension( const TComVPS* pcVPS )
 { 
   WRITE_UVLC( pcVPS->getCpPrecision( ), "cp_precision" );
@@ -1634,42 +1769,39 @@
 #endif
 
+
 Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
 {
-#if H_MV
-  TComVPS* vps = pcSlice->getVPS(); 
-#endif
-#if ENC_DEC_TRACE  
-  xTraceSliceHeader (pcSlice);
-#endif
+#if NH_MV
+  const TComVPS* vps = pcSlice->getVPS(); 
+#endif
+
+#if ENC_DEC_TRACE
+#if NH_MV
+  tracePSHeader( "Slice", pcSlice->getLayerId() ); 
+#else
+  xTraceSliceHeader ();
+#endif
+#endif
+
+  const ChromaFormat format                = pcSlice->getSPS()->getChromaFormatIdc();
+  const UInt         numberValidComponents = getNumberValidComponents(format);
+  const Bool         chromaEnabled         = isChromaEnabled(format);
 
   //calculate number of bits required for slice address
-  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumCUsInFrame();
+  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumberOfCtusInFrame();
   Int bitsSliceSegmentAddress = 0;
-  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress)) 
+  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress))
   {
     bitsSliceSegmentAddress++;
   }
-  Int ctuAddress;
-  if (pcSlice->isNextSlice())
-  {
-    // Calculate slice address
-    ctuAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
-  }
-  else
-  {
-    // Calculate slice address
-    ctuAddress = (pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
-  }
+  const Int ctuTsAddress = pcSlice->getSliceSegmentCurStartCtuTsAddr();
+
   //write slice address
-  Int sliceSegmentAddress = pcSlice->getPic()->getPicSym()->getCUOrderMap(ctuAddress);
-
-  WRITE_FLAG( sliceSegmentAddress==0, "first_slice_segment_in_pic_flag" );
+  const Int sliceSegmentRsAddress = pcSlice->getPic()->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddress);
+
+  WRITE_FLAG( sliceSegmentRsAddress==0, "first_slice_segment_in_pic_flag" );
   if ( pcSlice->getRapPicFlag() )
   {
-#if SETTING_NO_OUT_PIC_PRIOR
     WRITE_FLAG( pcSlice->getNoOutputPriorPicsFlag() ? 1 : 0, "no_output_of_prior_pics_flag" );
-#else
-    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
-#endif
   }
 #if PPS_FIX_DEPTH
@@ -1680,17 +1812,18 @@
   else
 #endif
+
   WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
-  pcSlice->setDependentSliceSegmentFlag(!pcSlice->isNextSlice());
-  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentAddress!=0) )
+  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentRsAddress!=0) )
   {
     WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
   }
-  if(sliceSegmentAddress>0)
-  {
-    WRITE_CODE( sliceSegmentAddress, bitsSliceSegmentAddress, "slice_segment_address" );
+  if(sliceSegmentRsAddress>0)
+  {
+    WRITE_CODE( sliceSegmentRsAddress, bitsSliceSegmentAddress, "slice_segment_address" );
   }
   if ( !pcSlice->getDependentSliceSegmentFlag() )
   {
-#if H_MV    
+
+#if NH_MV    
     Int esb = 0;  //Don't use i, otherwise will shadow something below
 
@@ -1716,6 +1849,4 @@
     pcSlice->checkCrossLayerBlaFlag( ); 
 
-
-
     for (; esb < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); esb++)    
 #else
@@ -1723,7 +1854,8 @@
 #endif
     {
-      assert(!!"slice_reserved_undetermined_flag[]");
-      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
-    }
+      WRITE_FLAG(0, "slice_reserved_flag[]");
+    }
+
+
 
     WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
@@ -1734,14 +1866,5 @@
     }
 
-    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
-#if H_3D_DISABLE_CHROMA
-    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 || pcSlice->getIsDepth() );
-    assert (pcSlice->getSPS()->getChromaFormatIdc() == 0 || !pcSlice->getIsDepth() );
-#else
-    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
-#endif
-    // if( separate_colour_plane_flag  ==  1 )
-    //   colour_plane_id                                      u(2)
-#if H_MV
+#if NH_MV
     if ( (pcSlice->getLayerId() > 0 && !vps->getPocLsbNotPresentFlag( pcSlice->getLayerIdInVps())) || !pcSlice->getIdrPicFlag() )
     {
@@ -1752,12 +1875,13 @@
 
 #endif
+
     if( !pcSlice->getIdrPicFlag() )
     {
-#if !H_MV
+#if !NH_MV
       Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
-      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
-#endif
-      TComReferencePictureSet* rps = pcSlice->getRPS();
-      
+      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "slice_pic_order_cnt_lsb");
+#endif
+      const TComReferencePictureSet* rps = pcSlice->getRPS();
+
       // check for bitstream restriction stating that:
       // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
@@ -1765,14 +1889,14 @@
       if (pcSlice->isIRAP())
       {
-          for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
-          {
+        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
+        {
           assert (!rps->getUsed(picIdx));
-          }
-        }
+        }
+      }
 
       if(pcSlice->getRPSidx() < 0)
       {
         WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
-        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
+        codeShortTermRefPicSet( rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
       }
       else
@@ -1786,5 +1910,5 @@
         if (numBits > 0)
         {
-          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );          
+          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );
         }
       }
@@ -1796,7 +1920,13 @@
         UInt ltrpIndex;
         Int counter = 0;
-        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
-        {
-          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
+        // WARNING: The following code only works only if a matching long-term RPS is 
+        //          found in the SPS for ALL long-term pictures
+        //          The problem is that the SPS coded long-term pictures are moved to the
+        //          beginning of the list which causes a mismatch when no reference picture
+        //          list reordering is used
+        //          NB: Long-term coding is currently not supported in general by the HM encoder
+        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--)
+        {
+          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k)))
           {
             ltrpInSPS[numLtrpInSPS] = ltrpIndex;
@@ -1809,4 +1939,6 @@
         }
         numLtrpInSH -= numLtrpInSPS;
+        // check that either all long-term pictures are coded in SPS or in slice header (no mixing)
+        assert (numLtrpInSH==0 || numLtrpInSPS==0); 
 
         Int bitsForLtrpInSPS = 0;
@@ -1815,5 +1947,5 @@
           bitsForLtrpInSPS++;
         }
-        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
+        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
         {
           WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
@@ -1824,5 +1956,8 @@
         Int prevDeltaMSB = 0, prevLSB = 0;
         Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
-        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
+        counter = 0;
+        // Warning: If some pictures are moved to ltrpInSPS, i is referring to a wrong index 
+        //          (mapping would be required)
+        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--, counter++)
         {
           if (counter < numLtrpInSPS)
@@ -1830,11 +1965,11 @@
             if (bitsForLtrpInSPS > 0)
             {
-              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");              
+              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");
             }
           }
-          else 
+          else
           {
             WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
-            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
+            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag");
           }
           WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
@@ -1853,5 +1988,5 @@
             }
             else
-            {              
+            {
               Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
               assert(differenceInDeltaMSB >= 0);
@@ -1865,15 +2000,15 @@
       if (pcSlice->getSPS()->getTMVPFlagsPresent())
       {
-#if H_MV
+#if NH_MV
         WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enabled_flag" );
 #else
-        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
-#endif
-      }
-    }
-#if H_MV
+        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enabled_flag" );
+#endif
+      }
+    }
+#if NH_MV
     Bool interLayerPredLayerIdcPresentFlag = false; 
     Int layerId = pcSlice->getLayerId(); 
-#if H_3D
+#if NH_3D
     if( pcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumRefListLayers( layerId ) > 0 )
 #else
@@ -1882,5 +2017,5 @@
     {   
       WRITE_FLAG( pcSlice->getInterLayerPredEnabledFlag( ) ? 1 : 0 , "inter_layer_pred_enabled_flag" );
-#if H_3D
+#if NH_3D
       if( pcSlice->getInterLayerPredEnabledFlag() && vps->getNumRefListLayers( layerId ) > 1 )
 #else
@@ -1892,5 +2027,5 @@
           WRITE_CODE( pcSlice->getNumInterLayerRefPicsMinus1( ), pcSlice->getNumInterLayerRefPicsMinus1Len( ), "num_inter_layer_ref_pics_minus1" );
         }
-#if H_3D
+#if NH_3D
         if ( pcSlice->getNumActiveRefLayerPics() != vps->getNumRefListLayers( layerId ) )
 #else
@@ -1915,5 +2050,5 @@
 #endif
 
-#if H_3D      
+#if NH_3D      
   if( getEncTop()->decProcAnnexI() )
   {
@@ -1924,18 +2059,12 @@
   }
 #endif
+
     if(pcSlice->getSPS()->getUseSAO())
     {
-      if (pcSlice->getSPS()->getUseSAO())
-      {
-         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
-#if H_3D_DISABLE_CHROMA
-         if ( !pcSlice->getIsDepth() )
-         {
-         WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
-      }
-#else
-         WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
-#endif
-      }
+       WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA), "slice_sao_luma_flag" );
+       if (chromaEnabled)
+       {
+         WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA), "slice_sao_chroma_flag" );
+       }
     }
 
@@ -1949,5 +2078,5 @@
 #endif
       WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
-      if (overrideFlag) 
+      if (overrideFlag)
       {
         WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
@@ -1984,5 +2113,5 @@
             Int length = 1;
             numRpsCurrTempList0 --;
-            while ( numRpsCurrTempList0 >>= 1) 
+            while ( numRpsCurrTempList0 >>= 1)
             {
               length ++;
@@ -1996,5 +2125,5 @@
       }
       if(pcSlice->isInterB())
-      {    
+      {
         WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
         if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
@@ -2017,5 +2146,5 @@
       }
     }
-    
+
     if (pcSlice->isInterB())
     {
@@ -2028,5 +2157,5 @@
       {
         SliceType sliceType   = pcSlice->getSliceType();
-        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
+        SliceType  encCABACTableIdx = pcSlice->getEncCABACTableIdx();
         Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
         pcSlice->setCabacInitFlag( encCabacInitFlag );
@@ -2080,12 +2209,23 @@
     }
     Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
-    WRITE_SVLC( iCode, "slice_qp_delta" ); 
+    WRITE_SVLC( iCode, "slice_qp_delta" );
     if (pcSlice->getPPS()->getSliceChromaQpFlag())
     {
-      iCode = pcSlice->getSliceQpDeltaCb();
-      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
-      iCode = pcSlice->getSliceQpDeltaCr();
-      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
-    }
+      if (numberValidComponents > COMPONENT_Cb)
+      {
+        WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb), "slice_cb_qp_offset" );
+      }
+      if (numberValidComponents > COMPONENT_Cr)
+      {
+        WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr), "slice_cr_qp_offset" );
+      }
+      assert(numberValidComponents <= COMPONENT_Cr+1);
+    }
+
+    if (pcSlice->getPPS()->getPpsRangeExtension().getChromaQpOffsetListEnabledFlag())
+    {
+      WRITE_FLAG(pcSlice->getUseChromaQpAdj(), "cu_chroma_qp_offset_enabled_flag");
+    }
+
     if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
     {
@@ -2105,5 +2245,5 @@
     }
 
-    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
+    Bool isSAOEnabled = pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA) || (chromaEnabled && pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA)));
     Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
 
@@ -2112,5 +2252,5 @@
       WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
     }
-#if H_3D
+#if NH_3D
     if (getEncTop()->decProcAnnexI() )
     {
@@ -2129,12 +2269,10 @@
     }
 #endif
-  }
-
-
-
-#if !H_MV
+
+  }
+#if !NH_MV
   if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
   {
-    WRITE_UVLC(0,"slice_header_extension_length");
+    WRITE_UVLC(0,"slice_segment_header_extension_length");
   }
 #else
@@ -2244,28 +2382,25 @@
   }
 #endif 
-}
-
-Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
+
+}
+
+Void TEncCavlc::codePTL( const TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
 {
   if(profilePresentFlag)
   {
-    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
-  }
-  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
+    codeProfileTier(pcPTL->getGeneralPTL(), false);    // general_...
+  }
+  WRITE_CODE( Int(pcPTL->getGeneralPTL()->getLevelIdc()), 8, "general_level_idc" );
 
   for (Int i = 0; i < maxNumSubLayersMinus1; i++)
   {
-#if !H_MV
-    if(profilePresentFlag)
-    {
-#endif
-      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
-#if !H_MV
-    }
-#endif
-    
+#if !NH_MV
+#endif
+    WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
+#if !NH_MV
+#endif
     WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
   }
-  
+
   if (maxNumSubLayersMinus1 > 0)
   {
@@ -2275,33 +2410,40 @@
     }
   }
-  
+
   for(Int i = 0; i < maxNumSubLayersMinus1; i++)
   {
-    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
-    {
-      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
+    if( pcPTL->getSubLayerProfilePresentFlag(i) )
+    {
+      codeProfileTier(pcPTL->getSubLayerPTL(i), true);  // sub_layer_...
     }
     if( pcPTL->getSubLayerLevelPresentFlag(i) )
     {
-      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
-    }
-  }
-}
-Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
-{
-  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
-  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
-  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
+      WRITE_CODE( Int(pcPTL->getSubLayerPTL(i)->getLevelIdc()), 8, "sub_layer_level_idc[i]" );
+    }
+  }
+}
+
+#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TEncCavlc::codeProfileTier( const ProfileTierLevel* ptl, const Bool bIsSubLayer )
+#define PTL_TRACE_TEXT(txt) bIsSubLayer?("sub_layer_" txt) : ("general_" txt)
+#else
+Void TEncCavlc::codeProfileTier( const ProfileTierLevel* ptl, const Bool /*bIsSubLayer*/ )
+#define PTL_TRACE_TEXT(txt) txt
+#endif
+{
+  WRITE_CODE( ptl->getProfileSpace(), 2 ,      PTL_TRACE_TEXT("profile_space"                   ));
+  WRITE_FLAG( ptl->getTierFlag()==Level::HIGH, PTL_TRACE_TEXT("tier_flag"                       ));
+  WRITE_CODE( Int(ptl->getProfileIdc()), 5 ,   PTL_TRACE_TEXT("profile_idc"                     ));
   for(Int j = 0; j < 32; j++)
   {
-    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
-  }
-
-  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
-  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
-  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
-  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
-  
-#if H_MV
+    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), PTL_TRACE_TEXT("profile_compatibility_flag[][j]" ));
+  }
+
+  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   PTL_TRACE_TEXT("progressive_source_flag"         ));
+  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    PTL_TRACE_TEXT("interlaced_source_flag"          ));
+  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), PTL_TRACE_TEXT("non_packed_constraint_flag"      ));
+  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), PTL_TRACE_TEXT("frame_only_constraint_flag"      ));
+
+#if NH_MV
   if( ptl->getV2ConstraintsPresentFlag() ) 
   {
@@ -2334,14 +2476,36 @@
   }
 #else
-  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[0..15]");
-  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[16..31]");
-  WRITE_CODE(0 , 12, "XXX_reserved_zero_44bits[32..43]");
+  if (ptl->getProfileIdc() == Profile::MAINREXT || ptl->getProfileIdc() == Profile::HIGHTHROUGHPUTREXT )
+  {
+    const UInt         bitDepthConstraint=ptl->getBitDepthConstraint();
+    WRITE_FLAG(bitDepthConstraint<=12,          PTL_TRACE_TEXT("max_12bit_constraint_flag"       ));
+    WRITE_FLAG(bitDepthConstraint<=10,          PTL_TRACE_TEXT("max_10bit_constraint_flag"       ));
+    WRITE_FLAG(bitDepthConstraint<= 8,          PTL_TRACE_TEXT("max_8bit_constraint_flag"        ));
+    const ChromaFormat chromaFmtConstraint=ptl->getChromaFormatConstraint();
+    WRITE_FLAG(chromaFmtConstraint==CHROMA_422||chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400, PTL_TRACE_TEXT("max_422chroma_constraint_flag" ));
+    WRITE_FLAG(chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400,                                  PTL_TRACE_TEXT("max_420chroma_constraint_flag" ));
+    WRITE_FLAG(chromaFmtConstraint==CHROMA_400,                                                                   PTL_TRACE_TEXT("max_monochrome_constraint_flag"));
+    WRITE_FLAG(ptl->getIntraConstraintFlag(),        PTL_TRACE_TEXT("intra_constraint_flag"           ));
+    WRITE_FLAG(ptl->getOnePictureOnlyConstraintFlag(), PTL_TRACE_TEXT("one_picture_only_constraint_flag"));
+    WRITE_FLAG(ptl->getLowerBitRateConstraintFlag(), PTL_TRACE_TEXT("lower_bit_rate_constraint_flag"  ));
+    WRITE_CODE(0 , 16, PTL_TRACE_TEXT("reserved_zero_34bits[0..15]"     ));
+    WRITE_CODE(0 , 16, PTL_TRACE_TEXT("reserved_zero_34bits[16..31]"    ));
+    WRITE_CODE(0 ,  2, PTL_TRACE_TEXT("reserved_zero_34bits[32..33]"    ));
+  }
+  else
+  {
+    WRITE_CODE(0x0000 , 16, PTL_TRACE_TEXT("reserved_zero_43bits[0..15]"     ));
+    WRITE_CODE(0x0000 , 16, PTL_TRACE_TEXT("reserved_zero_43bits[16..31]"    ));
+    WRITE_CODE(0x000  , 11, PTL_TRACE_TEXT("reserved_zero_43bits[32..42]"    ));
+  }
+  WRITE_FLAG(false,   PTL_TRACE_TEXT("inbld_flag" ));
+#undef PTL_TRACE_TEXT
 #endif
 }
 
 /**
- - write wavefront substreams sizes for the slice header.
- .
- \param pcSlice Where we find the substream size information.
+ * Write tiles and wavefront substreams sizes for the slice header (entry points).
+ *
+ * \param pSlice TComSlice structure that contains the substream size information.
  */
 Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
@@ -2351,69 +2515,35 @@
     return;
   }
-  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
-  Int  numZeroSubstreamsAtStartOfSlice  = 0;
-  UInt *entryPointOffset = NULL;
-  if ( pSlice->getPPS()->getTilesEnabledFlag() )
-  {
-    numEntryPointOffsets = pSlice->getTileLocationCount();
-    entryPointOffset     = new UInt[numEntryPointOffsets];
-    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
-    {
-      if ( idx == 0 )
-      {
-        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
-      }
-      else
-      {
-        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
-      }
-
-      if ( entryPointOffset[ idx ] > maxOffset )
-      {
-        maxOffset = entryPointOffset[ idx ];
-      }
-    }
-  }
-  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
-  {
-    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
-    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
-    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceSegmentCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
-    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceSegmentCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
-    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
-    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
-    entryPointOffset           = new UInt[numEntryPointOffsets];
-    for (Int idx=0; idx<numEntryPointOffsets; idx++)
-    {
-      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
-      if ( entryPointOffset[ idx ] > maxOffset )
-      {
-        maxOffset = entryPointOffset[ idx ];
-      }
-    }
-  }
+  UInt maxOffset = 0;
+  for(Int idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
+  {
+    UInt offset=pSlice->getSubstreamSize(idx);
+    if ( offset > maxOffset )
+    {
+      maxOffset = offset;
+    }
+  }
+
   // Determine number of bits "offsetLenMinus1+1" required for entry point information
-  offsetLenMinus1 = 0;
+  UInt offsetLenMinus1 = 0;
   while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
   {
     offsetLenMinus1++;
-    assert(offsetLenMinus1 + 1 < 32);    
-  }
-
-  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
-  if (numEntryPointOffsets>0)
+    assert(offsetLenMinus1 + 1 < 32);
+  }
+
+  WRITE_UVLC(pSlice->getNumberOfSubstreamSizes(), "num_entry_point_offsets");
+  if (pSlice->getNumberOfSubstreamSizes()>0)
   {
     WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
-  }
-
-  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
-  {
-    WRITE_CODE(entryPointOffset[ idx ]-1, offsetLenMinus1+1, "entry_point_offset_minus1");
-  }
-
-  delete [] entryPointOffset;
-}
-
-Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
+
+    for (UInt idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
+    {
+      WRITE_CODE(pSlice->getSubstreamSize(idx)-1, offsetLenMinus1+1, "entry_point_offset_minus1");
+    }
+  }
+}
+
+Void TEncCavlc::codeTerminatingBit      ( UInt /*uilsLast*/ )
 {
 }
@@ -2423,25 +2553,25 @@
 }
 
-Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+Void TEncCavlc::codeMVPIdx ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, RefPicList /*eRefList*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+Void TEncCavlc::codePartSize( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codePredMode( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codeMergeFlag    ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codeMergeIndex    ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
@@ -2462,15 +2592,15 @@
 #endif
 
-Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
+Void TEncCavlc::codeInterModeFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/, UInt /*uiEncMode*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codeSkipFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
@@ -2483,34 +2613,34 @@
 #endif
 
-Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+Void TEncCavlc::codeSplitFlag   ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+Void TEncCavlc::codeTransformSubdivFlag( UInt /*uiSymbol*/, UInt /*uiCtx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+Void TEncCavlc::codeQtCbf( TComTU& /*rTu*/, const ComponentID /*compID*/, const Bool /*lowestLevel*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codeQtRootCbf( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
+Void TEncCavlc::codeQtCbfZero( TComTU& /*rTu*/, const ChannelType /*chType*/ )
 {
   assert(0);
 }
-Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
+Void TEncCavlc::codeQtRootCbfZero( )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType )
+Void TEncCavlc::codeTransformSkipFlags (TComTU& /*rTu*/, ComponentID /*component*/ )
 {
   assert(0);
@@ -2522,52 +2652,62 @@
  * \returns Void
  */
-Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codeIPCMInfo( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
+Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, Bool /*isMultiple*/)
 {
   assert(0);
 }
 
-Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codeIntraDirChroma( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+Void TEncCavlc::codeInterDir( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+Void TEncCavlc::codeRefFrmIdx( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, RefPicList /*eRefList*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+Void TEncCavlc::codeMvd( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, RefPicList /*eRefList*/ )
 {
   assert(0);
 }
 
+Void TEncCavlc::codeCrossComponentPrediction( TComTU& /*rTu*/, ComponentID /*compID*/ )
+{
+  assert(0);
+}
+
 Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
   Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
 
-  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
   iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
 
   xWriteSvlc( iDQp );
-  
+
   return;
 }
 
-Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+Void TEncCavlc::codeChromaQpAdjustment( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
 {
   assert(0);
 }
 
-Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
+Void TEncCavlc::codeCoeffNxN    ( TComTU& /*rTu*/, TCoeff* /*pcCoef*/, const ComponentID /*compID*/ )
+{
+  assert(0);
+}
+
+Void TEncCavlc::estBit( estBitsSbacStruct* /*pcEstBitsCabac*/, Int /*width*/, Int /*height*/, ChannelType /*chType*/ )
 {
   // printf("error : no VLC mode support in this version\n");
@@ -2579,81 +2719,77 @@
 // ====================================================================================================================
 
-/** code explicit wp tables
- * \param TComSlice* pcSlice
- * \returns Void
- */
+//! Code weighted prediction tables
 Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
 {
-  wpScalingParam  *wp;
-#if  H_3D_DISABLE_CHROMA
-  Bool            bChroma     = !pcSlice->getIsDepth(); // color always present in HEVC ?
-#else
-  Bool            bChroma     = true; // color always present in HEVC ?
-#endif
-  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
-  Bool            bDenomCoded  = false;
-  UInt            uiMode = 0;
-  UInt            uiTotalSignalledWeightFlags = 0;
+  WPScalingParam  *wp;
+  const ChromaFormat    format                = pcSlice->getPic()->getChromaFormat();
+  const UInt            numberValidComponents = getNumberValidComponents(format);
+  const Bool            bChroma               = isChromaEnabled(format);
+  const Int             iNbRef                = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
+        Bool            bDenomCoded           = false;
+        UInt            uiTotalSignalledWeightFlags = 0;
+
   if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
   {
-    uiMode = 1; // explicit
-  }
-  if(uiMode == 1)
-  {
-
-    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
+    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) // loop over l0 and l1 syntax elements
     {
       RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
 
-      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      // NOTE: wp[].uiLog2WeightDenom and wp[].bPresentFlag are actually per-channel-type settings.
+
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
       {
         pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
-        if ( !bDenomCoded ) 
+        if ( !bDenomCoded )
         {
           Int iDeltaDenom;
-          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+          WRITE_UVLC( wp[COMPONENT_Y].uiLog2WeightDenom, "luma_log2_weight_denom" );
 
           if( bChroma )
           {
-            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
-            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
+            assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom); // check the channel-type settings are consistent across components.
+            iDeltaDenom = (wp[COMPONENT_Cb].uiLog2WeightDenom - wp[COMPONENT_Y].uiLog2WeightDenom);
+            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );
           }
           bDenomCoded = true;
         }
-        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
-        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
-      }
-      if (bChroma) 
-      {
-        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+        WRITE_FLAG( wp[COMPONENT_Y].bPresentFlag, iNumRef==0?"luma_weight_l0_flag[i]":"luma_weight_l1_flag[i]" );
+        uiTotalSignalledWeightFlags += wp[COMPONENT_Y].bPresentFlag;
+      }
+      if (bChroma)
+      {
+        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
         {
           pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
-          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
-          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
-        }
-      }
-
-      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+          assert(wp[COMPONENT_Cb].bPresentFlag == wp[COMPONENT_Cr].bPresentFlag); // check the channel-type settings are consistent across components.
+          WRITE_FLAG( wp[COMPONENT_Cb].bPresentFlag, iNumRef==0?"chroma_weight_l0_flag[i]":"chroma_weight_l1_flag[i]" );
+          uiTotalSignalledWeightFlags += 2*wp[COMPONENT_Cb].bPresentFlag;
+        }
+      }
+
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
       {
         pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
-        if ( wp[0].bPresentFlag ) 
-        {
-          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
-          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
-          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
-        }
-
-        if ( bChroma ) 
-        {
-          if ( wp[1].bPresentFlag )
+        if ( wp[COMPONENT_Y].bPresentFlag )
+        {
+          Int iDeltaWeight = (wp[COMPONENT_Y].iWeight - (1<<wp[COMPONENT_Y].uiLog2WeightDenom));
+          WRITE_SVLC( iDeltaWeight, iNumRef==0?"delta_luma_weight_l0[i]":"delta_luma_weight_l1[i]" );
+          WRITE_SVLC( wp[COMPONENT_Y].iOffset, iNumRef==0?"luma_offset_l0[i]":"luma_offset_l1[i]" );
+        }
+
+        if ( bChroma )
+        {
+          if ( wp[COMPONENT_Cb].bPresentFlag )
           {
-            for ( Int j=1 ; j<3 ; j++ ) 
+            for ( Int j = COMPONENT_Cb ; j < numberValidComponents ; j++ )
             {
-              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
-              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
-
-              Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
+              assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom);
+              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[COMPONENT_Cb].uiLog2WeightDenom));
+              WRITE_SVLC( iDeltaWeight, iNumRef==0?"delta_chroma_weight_l0[i]":"delta_chroma_weight_l1[i]" );
+
+              Int range=pcSlice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag() ? (1<<pcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_CHROMA))/2 : 128;
+              Int pred = ( range - ( ( range*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
               Int iDeltaChroma = (wp[j].iOffset - pred);
-              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
+              WRITE_SVLC( iDeltaChroma, iNumRef==0?"delta_chroma_offset_l0[i]":"delta_chroma_offset_l1[i]" );
             }
           }
@@ -2668,40 +2804,47 @@
  *  \param scalingList quantization matrix information
  */
-Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
-{
-  UInt listId,sizeId;
-  Bool scalingListPredModeFlag;
-
-    //for each size
-    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
-    {
-      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
-      {
-        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
-        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
-        if(!scalingListPredModeFlag)// Copy Mode
-        {
-          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
-        }
-        else// DPCM Mode
-        {
-          xCodeScalingList(scalingList, sizeId, listId);
-        }
-      }
-    }
+Void TEncCavlc::codeScalingList( const TComScalingList &scalingList )
+{
+  //for each size
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    const Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
+
+    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId+=predListStep)
+    {
+      Bool scalingListPredModeFlag = scalingList.getScalingListPredModeFlag(sizeId, listId);
+      WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
+      if(!scalingListPredModeFlag)// Copy Mode
+      {
+        if (sizeId == SCALING_LIST_32x32)
+        {
+          // adjust the code, to cope with the missing chroma entries
+          WRITE_UVLC( ((Int)listId - (Int)scalingList.getRefMatrixId (sizeId,listId)) / (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES), "scaling_list_pred_matrix_id_delta");
+        }
+        else
+        {
+          WRITE_UVLC( (Int)listId - (Int)scalingList.getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
+        }
+      }
+      else// DPCM Mode
+      {
+        xCodeScalingList(&scalingList, sizeId, listId);
+      }
+    }
+  }
   return;
 }
 /** code DPCM
  * \param scalingList quantization matrix information
- * \param sizeIdc size index
- * \param listIdc list index
+ * \param sizeId      size index
+ * \param listId      list index
  */
-Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
+Void TEncCavlc::xCodeScalingList(const TComScalingList* scalingList, UInt sizeId, UInt listId)
 {
   Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
-  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
+  UInt* scan  = g_scanOrder[SCAN_UNGROUPED][SCAN_DIAG][sizeId==0 ? 2 : 3][sizeId==0 ? 2 : 3];
   Int nextCoef = SCALING_LIST_START_VALUE;
   Int data;
-  Int *src = scalingList->getScalingListAddress(sizeId, listId);
+  const Int *src = scalingList->getScalingListAddress(sizeId, listId);
     if( sizeId > SCALING_LIST_8x8 )
     {
@@ -2739,18 +2882,9 @@
   return false;
 }
-Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
-{
-  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
-  {
-    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
-      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
-     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
-    {
-      setRefMatrixId(sizeId, listId, predListIdx);
-      return false;
-    }
-  }
-  return true;
-}
+
+Void TEncCavlc::codeExplicitRdpcmMode( TComTU& /*rTu*/, const ComponentID /*compID*/ )
+ {
+   assert(0);
+ }
 
 #if H_3D_INTER_SDC
@@ -2773,3 +2907,5 @@
 }
 #endif
+
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -64,67 +64,59 @@
   TEncCavlc();
   virtual ~TEncCavlc();
-  
+
 protected:
-  TComSlice*    m_pcSlice;
-  UInt          m_uiCoeffCost;
-#if H_3D
+#if NH_3D
   TEncTop*      m_encTop; 
 #endif
-  Void codeShortTermRefPicSet              ( TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Bool calledFromSliceHeader, Int idx );
+
+  Void codeShortTermRefPicSet              ( const TComReferencePictureSet* pcRPS, Bool calledFromSliceHeader, Int idx );
   Bool findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag );
-  
+
 public:
-  
-  Void  resetEntropy          ();
-  Void  determineCabacInitIdx  () {};
+
+  Void  resetEntropy          (const TComSlice *pSlice);
+  SliceType determineCabacInitIdx  (const TComSlice* /*pSlice*/) { assert(0); return I_SLICE; };
 
   Void  setBitstream          ( TComBitIf* p )  { m_pcBitIf = p;  }
-  Void  setSlice              ( TComSlice* p )  { m_pcSlice = p;  }
   Void  resetBits             ()                { m_pcBitIf->resetBits(); }
-  Void  resetCoeffCost        ()                { m_uiCoeffCost = 0;  }
   UInt  getNumberOfWrittenBits()                { return  m_pcBitIf->getNumberOfWrittenBits();  }
-  UInt  getCoeffCost          ()                { return  m_uiCoeffCost;  }
-  Void  codeVPS                 ( TComVPS* pcVPS );
-#if H_MV
-  Void  codeVPSExtension       ( TComVPS *pcVPS );
-  Void  codeVideoSignalInfo     ( TComVideoSignalInfo* pcVideoSignalInfo ); 
+  Void  codeVPS                 ( const TComVPS* pcVPS );
+#if NH_MV
+  Void  codeVPSExtension       ( const TComVPS *pcVPS );
+  Void  codeVideoSignalInfo    ( const TComVideoSignalInfo* pcVideoSignalInfo ); 
 
-  Void  codeDpbSize   ( TComVPS* vps );
+  Void  codeDpbSize            ( const TComVPS* vps );
 
-  Void  codeRepFormat           ( Int i, TComRepFormat* curRepFormat, TComRepFormat* prevRepFormat );
-  Void  codeVPSVUI             ( TComVPS* pcVPS );
-  Void  codeVpsVuiBspHrdParameters( TComVPS* pcVPS ); 
+  Void  codeRepFormat           ( Int i, const TComRepFormat* curRepFormat, const TComRepFormat* prevRepFormat );
+  Void  codeVPSVUI              ( const TComVPS* pcVPS );
+  Void  codeVpsVuiBspHrdParameters( const TComVPS* pcVPS ); 
 #endif 
-  Void  codeVUI                 ( TComVUI *pcVUI, TComSPS* pcSPS );
-#if H_MV
-  Void  codeSPSExtension        ( TComSPS* pcSPS ); 
+
+  Void  codeVUI                 ( const TComVUI *pcVUI, const TComSPS* pcSPS );
+#if NH_MV
+  Void  codeSPSExtension        ( const TComSPS* pcSPS ); 
 #endif
-#if H_3D
-  Void  codeVPS3dExtension       ( TComVPS* pcVPS ); 
-  Void  codeSPS3dExtension      ( TComSPS* pcSPS );
-  Void  codeSPS                 ( TComSPS* pcSPS );
-#else
-  Void  codeSPS                 ( TComSPS* pcSPS );
+#if NH_3D
+  Void  codeVPS3dExtension      ( const TComVPS* pcVPS ); 
+  Void  codeSPS3dExtension      ( const TComSPS* pcSPS );
 #endif
-  Void  codePPS                 ( TComPPS* pcPPS );
-
-#if H_MV
-  Void codePPSMultilayerExtension( TComPPS* pcPPS );
+  Void  codeSPS                 ( const TComSPS* pcSPS );
+  Void  codePPS                 ( const TComPPS* pcPPS );
+#if NH_MV
+  Void  codePpsMultilayerExtension( const TComPPS* pcPPS );
 #endif
-
-#if H_3D
-  Void  codePPSExtension        ( TComPPS* pcPPS );
+#if NH_3D
+  Void  codePps3dExtension       ( const TComPPS* pcPPS );
 #endif
-
   Void  codeSliceHeader         ( TComSlice* pcSlice );
-  Void  codePTL                 ( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1);
-  Void  codeProfileTier         ( ProfileTierLevel* ptl );
-  Void  codeHrdParameters       ( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 );
+  Void  codePTL                 ( const TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1);
+  Void  codeProfileTier         ( const ProfileTierLevel* ptl, const Bool bIsSubLayer );
+  Void  codeHrdParameters       ( const TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 );
   Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
   Void  codeTerminatingBit      ( UInt uilsLast );
   Void  codeSliceFinish         ();
-  
+
   Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
-  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false){printf("only supported in CABAC"); assert(0); exit(-1);}
+  Void codeSAOBlkParam(SAOBlkParam& /*saoBlkParam*/, const BitDepths& /*bitDepths*/, Bool* /*sliceEnabled*/, Bool /*leftMergeAvail*/, Bool /*aboveMergeAvail*/, Bool /*onlyEstMergeInfo*/ = false){printf("only supported in CABAC"); assert(0); exit(-1);}
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
@@ -134,5 +126,4 @@
   Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
- 
 #if H_3D_ARP
   Void codeARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
@@ -148,18 +139,18 @@
   Void codeDBBPFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 #endif
-
+  Void codeAlfCtrlFlag   ( ComponentID /*component*/, UInt /*code*/ ) {printf("Not supported\n"); assert(0);}
   Void codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode );
   Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
   Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-  
+
   Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 
   Void codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
-  Void codeQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtCbf         ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel );
   Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-  Void codeQtCbfZero     ( TComDataCU* pcCU, TextType eType, UInt uiTrDepth );
-  Void codeQtRootCbfZero ( TComDataCU* pcCU );
+  Void codeQtCbfZero     ( TComTU &rTu, const ChannelType chType );
+  Void codeQtRootCbfZero ( );
   Void codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple);
   Void codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx );
@@ -167,24 +158,27 @@
   Void codeRefFrmIdx     ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
   Void codeMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
-  
+
+  Void codeCrossComponentPrediction( TComTU &rTu, ComponentID compID );
+
   Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-  
-  Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
-  Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType );
+  Void codeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx );
 
-  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
-  
+  Void codeCoeffNxN      ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID );
+  Void codeTransformSkipFlags ( TComTU &rTu, ComponentID component );
+
+  Void estBit            ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+
   Void xCodePredWeightTable          ( TComSlice* pcSlice );
-  Void updateContextTables           ( SliceType eSliceType, Int iQp, Bool bExecuteFinish=true ) { return;   }
-  Void updateContextTables           ( SliceType eSliceType, Int iQp  )                          { return;   }
 
-  Void codeScalingList  ( TComScalingList* scalingList );
-  Void xCodeScalingList ( TComScalingList* scalingList, UInt sizeId, UInt listId);
-  Void codeDFFlag       ( UInt uiCode, const Char *pSymbolName );
-  Void codeDFSvlc       ( Int   iCode, const Char *pSymbolName );
-#if H_3D
+  Void codeScalingList  ( const TComScalingList &scalingList );
+  Void xCodeScalingList ( const TComScalingList* scalingList, UInt sizeId, UInt listId);
+
+  Void codeExplicitRdpcmMode( TComTU &rTu, const ComponentID compID );
+
+#if NH_3D
   TEncTop* getEncTop()               { return m_encTop; };
   Void     setEncTop( TEncTop* et )  {  m_encTop = et; };
 #endif
+
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCfg.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCfg.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,5 +46,5 @@
 #include "TLibCommon/TComSlice.h"
 #include <assert.h>
-#if H_3D
+#if NH_3D
 #include "TAppCommon/TAppComCamPara.h"
 #include "TLibRenderer/TRenModSetupStrParser.h"
@@ -65,21 +65,19 @@
   Int m_referencePics[MAX_NUM_REF_PICS];
   Int m_usedByCurrPic[MAX_NUM_REF_PICS];
-#if AUTO_INTER_RPS
   Int m_interRPSPrediction;
-#else
-  Bool m_interRPSPrediction;
-#endif
   Int m_deltaRPS;
   Int m_numRefIdc;
   Int m_refIdc[MAX_NUM_REF_PICS+1];
-#if H_MV
+  Bool m_isEncoded;
+  #if NH_MV
   Int m_numActiveRefLayerPics;
   Int m_interLayerPredLayerIdc [MAX_NUM_REF_PICS];
   Int m_interViewRefPosL[2][MAX_NUM_REF_PICS];  
 #endif
-#if H_3D
+#if NH_3D
   Bool m_interCompPredFlag;
 #endif
-  GOPEntry()
+
+GOPEntry()
   : m_POC(-1)
   , m_QPOffset(0)
@@ -95,15 +93,17 @@
   , m_deltaRPS(0)
   , m_numRefIdc(0)
-#if H_MV
+  , m_isEncoded(false)
+#if NH_MV
   , m_numActiveRefLayerPics(0)
 #endif
-#if H_3D
+#if NH_3D
   , m_interCompPredFlag(false)
 #endif
+
   {
     ::memset( m_referencePics, 0, sizeof(m_referencePics) );
     ::memset( m_usedByCurrPic, 0, sizeof(m_usedByCurrPic) );
     ::memset( m_refIdc,        0, sizeof(m_refIdc) );
-#if H_MV
+#if NH_MV
     ::memset( m_interLayerPredLayerIdc,   0, sizeof(m_interLayerPredLayerIdc) );
     ::memset( m_interViewRefPosL[0], -1, sizeof(m_interViewRefPosL[0]) );
@@ -134,4 +134,9 @@
   Double    m_adLambdaModifier[ MAX_TLAYER ];
 
+  Bool      m_printMSEBasedSequencePSNR;
+  Bool      m_printFrameMSE;
+  Bool      m_printSequenceMSE;
+  Bool      m_cabacZeroWordPaddingEnabled;
+
   /* profile & level */
   Profile::Name m_profile;
@@ -142,4 +147,9 @@
   Bool m_nonPackedConstraintFlag;
   Bool m_frameOnlyConstraintFlag;
+  UInt              m_bitDepthConstraintValue;
+  ChromaFormat      m_chromaFormatConstraintValue;
+  Bool              m_intraConstraintFlag;
+  Bool              m_onePictureOnlyConstraintFlag;
+  Bool              m_lowerBitRateConstraintFlag;
 
   //====== Coding Structure ========
@@ -147,5 +157,5 @@
   UInt      m_uiDecodingRefreshType;            ///< the type of decoding refresh employed for the random access.
   Int       m_iGOPSize;
-#if H_MV
+#if NH_MV
   GOPEntry  m_GOPList[MAX_GOP+1];
 #else
@@ -155,9 +165,9 @@
   Int       m_maxDecPicBuffering[MAX_TLAYER];
   Int       m_numReorderPics[MAX_TLAYER];
-  
+
   Int       m_iQP;                              //  if (AdaptiveQP == OFF)
-  
+
   Int       m_aiPad[2];
-  
+
 
   Int       m_iMaxRefPicNum;                     ///< this is used to mimic the sliding mechanism used by the decoder
@@ -165,5 +175,10 @@
 
   Int       m_maxTempLayer;                      ///< Max temporal layer
-  Bool m_useAMP;
+  Bool      m_useAMP;
+  UInt      m_maxCUWidth;
+  UInt      m_maxCUHeight;
+  UInt      m_maxTotalCUDepth;
+  UInt      m_log2DiffMaxMinCodingBlockSize;
+
   //======= Transform =============
   UInt      m_uiQuadtreeTULog2MaxSize;
@@ -171,5 +186,5 @@
   UInt      m_uiQuadtreeTUMaxDepthInter;
   UInt      m_uiQuadtreeTUMaxDepthIntra;
-  
+
   //====== Loop/Deblock Filter ========
   Bool      m_bLoopFilterDisable;
@@ -177,14 +192,21 @@
   Int       m_loopFilterBetaOffsetDiv2;
   Int       m_loopFilterTcOffsetDiv2;
-  Bool      m_DeblockingFilterControlPresent;
   Bool      m_DeblockingFilterMetric;
   Bool      m_bUseSAO;
+  Bool      m_bTestSAODisableAtPictureLevel;
+  Double    m_saoEncodingRate;       // When non-0 SAO early picture termination is enabled for luma and chroma
+  Double    m_saoEncodingRateChroma; // The SAO early picture termination rate to use for chroma (when m_SaoEncodingRate is >0). If <=0, use results for luma.
   Int       m_maxNumOffsetsPerPic;
-  Bool      m_saoLcuBoundary;
+  Bool      m_saoCtuBoundary;
+
   //====== Motion search ========
+  Bool      m_bDisableIntraPUsInInterSlices;
   Int       m_iFastSearch;                      //  0:Full search  1:Diamond  2:PMVFAST
   Int       m_iSearchRange;                     //  0:Full frame
   Int       m_bipredSearchRange;
-#if H_MV
+  Bool      m_bClipForBiPredMeEnabled;
+  Bool      m_bFastMEAssumingSmootherMVEnabled;
+
+#if NH_MV
   Bool      m_bUseDisparitySearchRangeRestriction;
   Int       m_iVerticalDisparitySearchRange;
@@ -193,20 +215,27 @@
   Int       m_iMaxDeltaQP;                      //  Max. absolute delta QP (1:default)
   Int       m_iMaxCuDQPDepth;                   //  Max. depth for a minimum CuDQP (0:default)
+  Int       m_diffCuChromaQpOffsetDepth;        ///< If negative, then do not apply chroma qp offsets.
 
   Int       m_chromaCbQpOffset;                 //  Chroma Cb QP Offset (0:default)
   Int       m_chromaCrQpOffset;                 //  Chroma Cr Qp Offset (0:default)
+  ChromaFormat m_chromaFormatIDC;
 
 #if ADAPTIVE_QP_SELECTION
   Bool      m_bUseAdaptQpSelect;
 #endif
-
+  Bool      m_extendedPrecisionProcessingFlag;
+  Bool      m_highPrecisionOffsetsEnabledFlag;
   Bool      m_bUseAdaptiveQP;
   Int       m_iQPAdaptationRange;
-  
+
   //====== Tool list ========
+  Int       m_bitDepth[MAX_NUM_CHANNEL_TYPE];
   Bool      m_bUseASR;
   Bool      m_bUseHADME;
   Bool      m_useRDOQ;
   Bool      m_useRDOQTS;
+#if T0196_SELECTIVE_RDOQ
+  Bool      m_useSelectiveRDOQ;
+#endif
   UInt      m_rdPenalty;
   Bool      m_bUseFastEnc;
@@ -215,25 +244,37 @@
   Bool      m_bUseCbfFastMode;
   Bool      m_useEarlySkipDetection;
+  Bool      m_crossComponentPredictionEnabledFlag;
+  Bool      m_reconBasedCrossCPredictionEstimate;
+  UInt      m_log2SaoOffsetScale[MAX_NUM_CHANNEL_TYPE];
   Bool      m_useTransformSkip;
   Bool      m_useTransformSkipFast;
+  UInt      m_log2MaxTransformSkipBlockSize;
+  Bool      m_transformSkipRotationEnabledFlag;
+  Bool      m_transformSkipContextEnabledFlag;
+  Bool      m_persistentRiceAdaptationEnabledFlag;
+  Bool      m_cabacBypassAlignmentEnabledFlag;
+  Bool      m_rdpcmEnabledFlag[NUMBER_OF_RDPCM_SIGNALLING_MODES];
   Int*      m_aidQP;
   UInt      m_uiDeltaQpRD;
-  
+
   Bool      m_bUseConstrainedIntraPred;
+  Bool      m_bFastUDIUseMPMEnabled;
+  Bool      m_bFastMEForGenBLowDelayEnabled;
+  Bool      m_bUseBLambdaForNonKeyLowDelayPictures;
   Bool      m_usePCM;
+  Int       m_PCMBitDepth[MAX_NUM_CHANNEL_TYPE];
   UInt      m_pcmLog2MaxSize;
   UInt      m_uiPCMLog2MinSize;
   //====== Slice ========
-  Int       m_sliceMode;
-  Int       m_sliceArgument; 
+  SliceConstraint m_sliceMode;
+  Int       m_sliceArgument;
   //====== Dependent Slice ========
-  Int       m_sliceSegmentMode;
+  SliceConstraint m_sliceSegmentMode;
   Int       m_sliceSegmentArgument;
   Bool      m_bLFCrossSliceBoundaryFlag;
 
   Bool      m_bPCMInputBitDepthFlag;
-  UInt      m_uiPCMBitDepthLuma;
-  UInt      m_uiPCMBitDepthChroma;
   Bool      m_bPCMFilterDisableFlag;
+  Bool      m_intraSmoothingDisabledFlag;
   Bool      m_loopFilterAcrossTilesEnabledFlag;
   Bool      m_tileUniformSpacingFlag;
@@ -244,5 +285,4 @@
 
   Int       m_iWaveFrontSynchro;
-  Int       m_iWaveFrontSubstreams;
 
   Int       m_decodedPictureHashSEIEnabled;              ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
@@ -256,5 +296,5 @@
   Int       m_codedDataBitDepth;
   Int       m_targetBitDepth;
-  Int       m_modelId; 
+  Int       m_modelId;
   Int       m_minValue;
   Int       m_maxValue;
@@ -266,5 +306,5 @@
   Int       m_exposureIndexIdc;
   Int       m_exposureIndexValue;
-  Int       m_exposureCompensationValueSignFlag;
+  Bool      m_exposureCompensationValueSignFlag;
   Int       m_exposureCompensationValueNumerator;
   Int       m_exposureCompensationValueDenomIdc;
@@ -282,10 +322,31 @@
   Int       m_framePackingSEIQuincunx;
   Int       m_framePackingSEIInterpretation;
+  Int       m_segmentedRectFramePackingSEIEnabled;
+  Bool      m_segmentedRectFramePackingSEICancel;
+  Int       m_segmentedRectFramePackingSEIType;
+  Bool      m_segmentedRectFramePackingSEIPersistence;
   Int       m_displayOrientationSEIAngle;
   Int       m_temporalLevel0IndexSEIEnabled;
   Int       m_gradualDecodingRefreshInfoEnabled;
+  Int       m_noDisplaySEITLayer;
   Int       m_decodingUnitInfoSEIEnabled;
   Int       m_SOPDescriptionSEIEnabled;
   Int       m_scalableNestingSEIEnabled;
+  Bool      m_tmctsSEIEnabled;
+  Bool      m_timeCodeSEIEnabled;
+  Int       m_timeCodeSEINumTs;
+  TComSEITimeSet   m_timeSetArray[MAX_TIMECODE_SEI_SETS];
+  Bool      m_kneeSEIEnabled;
+  Int       m_kneeSEIId;
+  Bool      m_kneeSEICancelFlag;
+  Bool      m_kneeSEIPersistenceFlag;
+  Int       m_kneeSEIInputDrange;
+  Int       m_kneeSEIInputDispLuminance;
+  Int       m_kneeSEIOutputDrange;
+  Int       m_kneeSEIOutputDispLuminance;
+  Int       m_kneeSEINumKneePointsMinus1;
+  Int*      m_kneeSEIInputKneePoint;
+  Int*      m_kneeSEIOutputKneePoint;
+  TComSEIMasteringDisplay m_masteringDisplay;
   //====== Weighted Prediction ========
   Bool      m_useWeightedPred;       //< Use of Weighting Prediction (P_SLICE)
@@ -293,8 +354,8 @@
   UInt      m_log2ParallelMergeLevelMinus2;       ///< Parallel merge estimation region
   UInt      m_maxNumMergeCand;                    ///< Maximum number of merge candidates
-  Int       m_useScalingListId;            ///< Using quantization matrix i.e. 0=off, 1=default, 2=file.
+  ScalingListMode m_useScalingListId;            ///< Using quantization matrix i.e. 0=off, 1=default, 2=file.
   Char*     m_scalingListFile;          ///< quantization matrix file name
   Int       m_TMVPModeId;
-  Int       m_signHideFlag;
+  Bool      m_signHideFlag;
   Bool      m_RCEnableRateControl;
   Int       m_RCTargetBitrate;
@@ -313,8 +374,11 @@
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
   Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
-#if H_MV
+
+  CostMode  m_costMode;                                       ///< The cost function to use, primarily when considering lossless coding.
+#if NH_MV
   TComVPS*  m_cVPS;                                           ///< pointer to VPS, same for all layers
 #else
-  TComVPS                    m_cVPS;
+
+  TComVPS   m_cVPS;
 #endif
 
@@ -322,9 +386,11 @@
   TComDLT*  m_cDLT;
 #endif
-
   Bool      m_recalculateQPAccordingToLambda;                 ///< recalculate QP value according to the lambda value
-  Int       m_activeParameterSetsSEIEnabled;                  ///< enable active parameter set SEI message 
+  Int       m_activeParameterSetsSEIEnabled;                  ///< enable active parameter set SEI message
   Bool      m_vuiParametersPresentFlag;                       ///< enable generation of VUI parameters
   Bool      m_aspectRatioInfoPresentFlag;                     ///< Signals whether aspect_ratio_idc is present
+  Bool      m_chromaSamplingFilterHintEnabled;                ///< Signals whether chroma sampling filter hint data is present
+  Int       m_chromaSamplingHorFilterIdc;                     ///< Specifies the Index of filter to use
+  Int       m_chromaSamplingVerFilterIdc;                     ///< Specifies the Index of filter to use
   Int       m_aspectRatioIdc;                                 ///< aspect_ratio_idc
   Int       m_sarWidth;                                       ///< horizontal size of the sample aspect ratio
@@ -357,5 +423,12 @@
 
   Bool      m_useStrongIntraSmoothing;                        ///< enable the use of strong intra smoothing (bi_linear interpolation) for 32x32 blocks when reference samples are flat.
-#if H_MV
+  Bool      m_bEfficientFieldIRAPEnabled;                     ///< enable to code fields in a specific, potentially more efficient, order.
+  Bool      m_bHarmonizeGopFirstFieldCoupleEnabled;
+
+  std::string m_summaryOutFilename;                           ///< filename to use for producing summary output file.
+  std::string m_summaryPicFilenameBase;                       ///< Base filename to use for producing summary picture output files. The actual filenames used will have I.txt, P.txt and B.txt appended.
+  UInt        m_summaryVerboseness;                           ///< Specifies the level of the verboseness of the text output.
+
+#if NH_MV
   Bool              m_subBistreamPropSEIEnabled;
   Int               m_numAdditionalSubStreams;
@@ -367,5 +440,5 @@
 #endif
 
-#if H_MV
+#if NH_MV
   Int       m_layerId;
   Int       m_layerIdInVps;
@@ -374,5 +447,5 @@
 #endif 
 
-#if H_3D
+#if NH_3D
   Bool      m_isDepth;
 
@@ -380,5 +453,5 @@
   TAppComCamPara* m_cameraParameters; 
   
-#if H_3D_VSO
+#if NH_3D_VSO
   //====== View Synthesis Optimization ======
   TRenModSetupStrParser* m_renderModelParameters; 
@@ -397,19 +470,12 @@
   Double    m_dDispCoeff;
 #endif
-#if H_3D_IC
+
   Bool      m_bUseIC;
-  Bool      m_bUseICLowLatencyEnc;
-#endif
-  //====== Depth Intra Modes ======
-#if H_3D_DIM
+  Bool      m_bUseICLowLatencyEnc;  
   Bool      m_useDMM;
   Bool      m_useSDC;
   Bool      m_useDLT;
-#endif
-#if H_3D_QTLPC
   Bool      m_bUseQTL;
-#endif
-
-  Int m_profileIdc;
+  Int       m_profileIdc;
 
 #endif
@@ -418,20 +484,26 @@
   : m_tileColumnWidth()
   , m_tileRowHeight()
-#if H_MV
+#if NH_MV
   , m_layerId(-1)
   , m_layerIdInVps(-1)
   , m_viewId(-1)
   , m_viewIndex(-1)
-#if H_3D
+#if NH_3D
   , m_isDepth(false)
+#if NH_3D_VSO
   , m_bUseVSO(false)
+#endif
   , m_profileIdc( -1 )
 #endif
 #endif
-  {}
+
+  {
+    m_PCMBitDepth[CHANNEL_TYPE_LUMA]=8;
+    m_PCMBitDepth[CHANNEL_TYPE_CHROMA]=8;
+  }
 
   virtual ~TEncCfg()
   {}
-  
+
   Void setProfile(Profile::Name profile) { m_profile = profile; }
   Void setLevel(Level::Tier tier, Level::Name level) { m_levelTier = tier; m_level = level; }
@@ -446,6 +518,17 @@
 
   Void      setFramesToBeEncoded            ( Int   i )      { m_framesToBeEncoded = i; }
-  
-#if H_MV
+
+  Bool      getPrintMSEBasedSequencePSNR    ()         const { return m_printMSEBasedSequencePSNR;  }
+  Void      setPrintMSEBasedSequencePSNR    (Bool value)     { m_printMSEBasedSequencePSNR = value; }
+
+  Bool      getPrintFrameMSE                ()         const { return m_printFrameMSE;              }
+  Void      setPrintFrameMSE                (Bool value)     { m_printFrameMSE = value;             }
+
+  Bool      getPrintSequenceMSE             ()         const { return m_printSequenceMSE;           }
+  Void      setPrintSequenceMSE             (Bool value)     { m_printSequenceMSE = value;          }
+
+  Bool      getCabacZeroWordPaddingEnabled()           const { return m_cabacZeroWordPaddingEnabled;  }
+  Void      setCabacZeroWordPaddingEnabled(Bool value)       { m_cabacZeroWordPaddingEnabled = value; }
+#if NH_MV
   Void      setLayerId                       ( Int layerId )      { m_layerId = layerId; }
   Int       getLayerId                       ()                   { return m_layerId;    }
@@ -456,5 +539,5 @@
   Void      setViewIndex                     ( Int viewIndex  )   { m_viewIndex  = viewIndex;  }
   Int       getViewIndex                     ()                   { return m_viewIndex;    }
-#if H_3D
+#if NH_3D
   Void      setIsDepth                       ( Bool isDepth )   { m_isDepth = isDepth; }
   Bool      getIsDepth                       ()                 { return m_isDepth; }
@@ -465,5 +548,5 @@
   Void      setDecodingRefreshType          ( Int   i )      { m_uiDecodingRefreshType = (UInt)i; }
   Void      setGOPSize                      ( Int   i )      { m_iGOPSize = i; }
-#if H_MV
+#if NH_MV
   Void      setGopList                      ( GOPEntry*  GOPList ) {  for ( Int i = 0; i < MAX_GOP+1; i++ ) m_GOPList[i] = GOPList[i]; }
 #else
@@ -472,11 +555,12 @@
   Void      setExtraRPSs                    ( Int   i )      { m_extraRPSs = i; }
   GOPEntry  getGOPEntry                     ( Int   i )      { return m_GOPList[i]; }
+  Void      setEncodedFlag                  ( Int  i, Bool value )  { m_GOPList[i].m_isEncoded = value; }
   Void      setMaxDecPicBuffering           ( UInt u, UInt tlayer ) { m_maxDecPicBuffering[tlayer] = u;    }
   Void      setNumReorderPics               ( Int  i, UInt tlayer ) { m_numReorderPics[tlayer] = i;    }
-  
+
   Void      setQP                           ( Int   i )      { m_iQP = i; }
-  
+
   Void      setPad                          ( Int*  iPad                   )      { for ( Int i = 0; i < 2; i++ ) m_aiPad[i] = iPad[i]; }
-  
+
   Int       getMaxRefPicNum                 ()                              { return m_iMaxRefPicNum;           }
   Void      setMaxRefPicNum                 ( Int iMaxRefPicNum )           { m_iMaxRefPicNum = iMaxRefPicNum;  }
@@ -484,5 +568,8 @@
   Int       getMaxTempLayer                 ()                              { return m_maxTempLayer;              } 
   Void      setMaxTempLayer                 ( Int maxTempLayer )            { m_maxTempLayer = maxTempLayer;      }
-
+  Void      setMaxCUWidth                   ( UInt  u )      { m_maxCUWidth  = u; }
+  Void      setMaxCUHeight                  ( UInt  u )      { m_maxCUHeight = u; }
+  Void      setMaxTotalCUDepth              ( UInt  u )      { m_maxTotalCUDepth = u; }
+  Void      setLog2DiffMaxMinCodingBlockSize( UInt  u )      { m_log2DiffMaxMinCodingBlockSize = u; }
 #if H_3D_IC
   Void       setUseIC                       ( Bool bVal )    { m_bUseIC = bVal; }
@@ -491,4 +578,5 @@
   Bool       getUseICLowLatencyEnc          ()               { return m_bUseICLowLatencyEnc; }
 #endif
+
   //======== Transform =============
   Void      setQuadtreeTULog2MaxSize        ( UInt  u )      { m_uiQuadtreeTULog2MaxSize = u; }
@@ -496,7 +584,7 @@
   Void      setQuadtreeTUMaxDepthInter      ( UInt  u )      { m_uiQuadtreeTUMaxDepthInter = u; }
   Void      setQuadtreeTUMaxDepthIntra      ( UInt  u )      { m_uiQuadtreeTUMaxDepthIntra = u; }
-  
+
   Void setUseAMP( Bool b ) { m_useAMP = b; }
-  
+
   //====== Loop/Deblock Filter ========
   Void      setLoopFilterDisable            ( Bool  b )      { m_bLoopFilterDisable       = b; }
@@ -504,12 +592,14 @@
   Void      setLoopFilterBetaOffset         ( Int   i )      { m_loopFilterBetaOffsetDiv2  = i; }
   Void      setLoopFilterTcOffset           ( Int   i )      { m_loopFilterTcOffsetDiv2    = i; }
-  Void      setDeblockingFilterControlPresent ( Bool b ) { m_DeblockingFilterControlPresent = b; }
   Void      setDeblockingFilterMetric       ( Bool  b )      { m_DeblockingFilterMetric = b; }
 
   //====== Motion search ========
+  Void      setDisableIntraPUsInInterSlices ( Bool  b )      { m_bDisableIntraPUsInInterSlices = b; }
   Void      setFastSearch                   ( Int   i )      { m_iFastSearch = i; }
   Void      setSearchRange                  ( Int   i )      { m_iSearchRange = i; }
   Void      setBipredSearchRange            ( Int   i )      { m_bipredSearchRange = i; }
-#if H_MV
+  Void      setClipForBiPredMeEnabled       ( Bool  b )      { m_bClipForBiPredMeEnabled = b; }
+  Void      setFastMEAssumingSmootherMVEnabled ( Bool b )    { m_bFastMEAssumingSmootherMVEnabled = b; }
+#if NH_MV
   Void      setUseDisparitySearchRangeRestriction ( Bool   b )      { m_bUseDisparitySearchRangeRestriction = b; }
   Void      setVerticalDisparitySearchRange ( Int   i )      { m_iVerticalDisparitySearchRange = i; }
@@ -520,6 +610,12 @@
   Void      setMaxCuDQPDepth                ( Int   i )      { m_iMaxCuDQPDepth = i; }
 
+  Int       getDiffCuChromaQpOffsetDepth    ()         const { return m_diffCuChromaQpOffsetDepth;  }
+  Void      setDiffCuChromaQpOffsetDepth    (Int value)      { m_diffCuChromaQpOffsetDepth = value; }
+
   Void      setChromaCbQpOffset             ( Int   i )      { m_chromaCbQpOffset = i; }
   Void      setChromaCrQpOffset             ( Int   i )      { m_chromaCrQpOffset = i; }
+
+  Void      setChromaFormatIdc              ( ChromaFormat cf ) { m_chromaFormatIDC = cf; }
+  ChromaFormat  getChromaFormatIdc          ( )              { return m_chromaFormatIDC; }
 
 #if ADAPTIVE_QP_SELECTION
@@ -528,7 +624,13 @@
 #endif
 
+  Bool      getExtendedPrecisionProcessingFlag         ()         const { return m_extendedPrecisionProcessingFlag;  }
+  Void      setExtendedPrecisionProcessingFlag         (Bool value)     { m_extendedPrecisionProcessingFlag = value; }
+
+  Bool      getHighPrecisionOffsetsEnabledFlag() const { return m_highPrecisionOffsetsEnabledFlag; }
+  Void      setHighPrecisionOffsetsEnabledFlag(Bool value) { m_highPrecisionOffsetsEnabledFlag = value; }
+
   Void      setUseAdaptiveQP                ( Bool  b )      { m_bUseAdaptiveQP = b; }
   Void      setQPAdaptationRange            ( Int   i )      { m_iQPAdaptationRange = i; }
-  
+
   //====== Sequence ========
   Int       getFrameRate                    ()      { return  m_iFrameRate; }
@@ -537,5 +639,5 @@
   Int       getSourceHeight                 ()      { return  m_iSourceHeight; }
   Int       getFramesToBeEncoded            ()      { return  m_framesToBeEncoded; }
-  void setLambdaModifier                    ( UInt uiIndex, Double dValue ) { m_adLambdaModifier[ uiIndex ] = dValue; }
+  Void setLambdaModifier                    ( UInt uiIndex, Double dValue ) { m_adLambdaModifier[ uiIndex ] = dValue; }
   Double getLambdaModifier                  ( UInt uiIndex ) const { return m_adLambdaModifier[ uiIndex ]; }
 
@@ -547,7 +649,7 @@
   Int       getNumReorderPics               (UInt tlayer) { return m_numReorderPics[tlayer]; }
   Int       getQP                           ()      { return  m_iQP; }
-  
+
   Int       getPad                          ( Int i )      { assert (i < 2 );                      return  m_aiPad[i]; }
-  
+
   //======== Transform =============
   UInt      getQuadtreeTULog2MaxSize        ()      const { return m_uiQuadtreeTULog2MaxSize; }
@@ -555,5 +657,5 @@
   UInt      getQuadtreeTUMaxDepthInter      ()      const { return m_uiQuadtreeTUMaxDepthInter; }
   UInt      getQuadtreeTUMaxDepthIntra      ()      const { return m_uiQuadtreeTUMaxDepthIntra; }
-  
+
   //==== Loop/Deblock Filter ========
   Bool      getLoopFilterDisable            ()      { return  m_bLoopFilterDisable;       }
@@ -561,11 +663,13 @@
   Int       getLoopFilterBetaOffset         ()      { return m_loopFilterBetaOffsetDiv2; }
   Int       getLoopFilterTcOffset           ()      { return m_loopFilterTcOffsetDiv2; }
-  Bool      getDeblockingFilterControlPresent()  { return  m_DeblockingFilterControlPresent; }
   Bool      getDeblockingFilterMetric       ()      { return m_DeblockingFilterMetric; }
 
   //==== Motion search ========
-  Int       getFastSearch                   ()      { return  m_iFastSearch; }
-  Int       getSearchRange                  ()      { return  m_iSearchRange; }
-#if H_MV
+  Bool      getDisableIntraPUsInInterSlices () const { return m_bDisableIntraPUsInInterSlices; }
+  Int       getFastSearch                   () const { return m_iFastSearch; }
+  Int       getSearchRange                  () const { return m_iSearchRange; }
+  Bool      getClipForBiPredMeEnabled       () const { return m_bClipForBiPredMeEnabled; }
+  Bool      getFastMEAssumingSmootherMVEnabled ( ) const { return m_bFastMEAssumingSmootherMVEnabled; }
+#if NH_MV
   Bool      getUseDisparitySearchRangeRestriction ()      { return  m_bUseDisparitySearchRangeRestriction; }
   Int       getVerticalDisparitySearchRange ()            { return  m_iVerticalDisparitySearchRange; }
@@ -577,10 +681,14 @@
   Bool      getUseAdaptiveQP                ()      { return  m_bUseAdaptiveQP; }
   Int       getQPAdaptationRange            ()      { return  m_iQPAdaptationRange; }
-  
+
   //==== Tool list ========
+  Void      setBitDepth( const ChannelType chType, Int internalBitDepthForChannel ) { m_bitDepth[chType] = internalBitDepthForChannel; }
   Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
   Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
   Void      setUseRDOQ                      ( Bool  b )     { m_useRDOQ    = b; }
   Void      setUseRDOQTS                    ( Bool  b )     { m_useRDOQTS  = b; }
+#if T0196_SELECTIVE_RDOQ
+  Void      setUseSelectiveRDOQ             ( Bool b )      { m_useSelectiveRDOQ = b; }
+#endif
   Void      setRDpenalty                 ( UInt  b )     { m_rdPenalty  = b; }
   Void      setUseFastEnc                   ( Bool  b )     { m_bUseFastEnc = b; }
@@ -590,7 +698,12 @@
   Void      setUseEarlySkipDetection        ( Bool  b )     { m_useEarlySkipDetection = b; }
   Void      setUseConstrainedIntraPred      ( Bool  b )     { m_bUseConstrainedIntraPred = b; }
+  Void      setFastUDIUseMPMEnabled         ( Bool  b )     { m_bFastUDIUseMPMEnabled = b; }
+  Void      setFastMEForGenBLowDelayEnabled ( Bool  b )     { m_bFastMEForGenBLowDelayEnabled = b; }
+  Void      setUseBLambdaForNonKeyLowDelayPictures ( Bool b ) { m_bUseBLambdaForNonKeyLowDelayPictures = b; }
+
   Void      setPCMInputBitDepthFlag         ( Bool  b )     { m_bPCMInputBitDepthFlag = b; }
   Void      setPCMFilterDisableFlag         ( Bool  b )     {  m_bPCMFilterDisableFlag = b; }
   Void      setUsePCM                       ( Bool  b )     {  m_usePCM = b;               }
+  Void      setPCMBitDepth( const ChannelType chType, Int pcmBitDepthForChannel ) { m_PCMBitDepth[chType] = pcmBitDepthForChannel; }
   Void      setPCMLog2MaxSize               ( UInt u )      { m_pcmLog2MaxSize = u;      }
   Void      setPCMLog2MinSize               ( UInt u )     { m_uiPCMLog2MinSize = u;      }
@@ -601,311 +714,422 @@
   Bool      getUseRDOQ                      ()      { return m_useRDOQ;    }
   Bool      getUseRDOQTS                    ()      { return m_useRDOQTS;  }
-  Int      getRDpenalty                  ()      { return m_rdPenalty;  }
+#if T0196_SELECTIVE_RDOQ
+  Bool      getUseSelectiveRDOQ             ()      { return m_useSelectiveRDOQ; }
+#endif
+  Int       getRDpenalty                    ()      { return m_rdPenalty;  }
   Bool      getUseFastEnc                   ()      { return m_bUseFastEnc; }
   Bool      getUseEarlyCU                   ()      { return m_bUseEarlyCU; }
   Bool      getUseFastDecisionForMerge      ()      { return m_useFastDecisionForMerge; }
-  Bool      getUseCbfFastMode           ()      { return m_bUseCbfFastMode; }
+  Bool      getUseCbfFastMode               ()      { return m_bUseCbfFastMode; }
   Bool      getUseEarlySkipDetection        ()      { return m_useEarlySkipDetection; }
   Bool      getUseConstrainedIntraPred      ()      { return m_bUseConstrainedIntraPred; }
+  Bool      getFastUDIUseMPMEnabled         ()      { return m_bFastUDIUseMPMEnabled; }
+  Bool      getFastMEForGenBLowDelayEnabled ()      { return m_bFastMEForGenBLowDelayEnabled; }
+  Bool      getUseBLambdaForNonKeyLowDelayPictures () { return m_bUseBLambdaForNonKeyLowDelayPictures; }
   Bool      getPCMInputBitDepthFlag         ()      { return m_bPCMInputBitDepthFlag;   }
-  Bool      getPCMFilterDisableFlag         ()      { return m_bPCMFilterDisableFlag;   } 
+  Bool      getPCMFilterDisableFlag         ()      { return m_bPCMFilterDisableFlag;   }
   Bool      getUsePCM                       ()      { return m_usePCM;                 }
   UInt      getPCMLog2MaxSize               ()      { return m_pcmLog2MaxSize;  }
   UInt      getPCMLog2MinSize               ()      { return  m_uiPCMLog2MinSize;  }
 
+  Bool      getCrossComponentPredictionEnabledFlag     ()                const { return m_crossComponentPredictionEnabledFlag;   }
+  Void      setCrossComponentPredictionEnabledFlag     (const Bool value)      { m_crossComponentPredictionEnabledFlag = value;  }
+  Bool      getUseReconBasedCrossCPredictionEstimate ()                const { return m_reconBasedCrossCPredictionEstimate;  }
+  Void      setUseReconBasedCrossCPredictionEstimate (const Bool value)      { m_reconBasedCrossCPredictionEstimate = value; }
+  Void      setLog2SaoOffsetScale(ChannelType type, UInt uiBitShift)         { m_log2SaoOffsetScale[type] = uiBitShift; }
+
   Bool getUseTransformSkip                             ()      { return m_useTransformSkip;        }
   Void setUseTransformSkip                             ( Bool b ) { m_useTransformSkip  = b;       }
+  Bool getTransformSkipRotationEnabledFlag             ()            const { return m_transformSkipRotationEnabledFlag;  }
+  Void setTransformSkipRotationEnabledFlag             (const Bool value)  { m_transformSkipRotationEnabledFlag = value; }
+  Bool getTransformSkipContextEnabledFlag              ()            const { return m_transformSkipContextEnabledFlag;  }
+  Void setTransformSkipContextEnabledFlag              (const Bool value)  { m_transformSkipContextEnabledFlag = value; }
+  Bool getPersistentRiceAdaptationEnabledFlag          ()                 const { return m_persistentRiceAdaptationEnabledFlag;  }
+  Void setPersistentRiceAdaptationEnabledFlag          (const Bool value)       { m_persistentRiceAdaptationEnabledFlag = value; }
+  Bool getCabacBypassAlignmentEnabledFlag              ()       const      { return m_cabacBypassAlignmentEnabledFlag;  }
+  Void setCabacBypassAlignmentEnabledFlag              (const Bool value)  { m_cabacBypassAlignmentEnabledFlag = value; }
+  Bool getRdpcmEnabledFlag                             (const RDPCMSignallingMode signallingMode)        const      { return m_rdpcmEnabledFlag[signallingMode];  }
+  Void setRdpcmEnabledFlag                             (const RDPCMSignallingMode signallingMode, const Bool value) { m_rdpcmEnabledFlag[signallingMode] = value; }
   Bool getUseTransformSkipFast                         ()      { return m_useTransformSkipFast;    }
   Void setUseTransformSkipFast                         ( Bool b ) { m_useTransformSkipFast  = b;   }
+  UInt getLog2MaxTransformSkipBlockSize                () const      { return m_log2MaxTransformSkipBlockSize;     }
+  Void setLog2MaxTransformSkipBlockSize                ( UInt u )    { m_log2MaxTransformSkipBlockSize  = u;       }
+  Bool getIntraSmoothingDisabledFlag               ()      const { return m_intraSmoothingDisabledFlag; }
+  Void setIntraSmoothingDisabledFlag               (Bool bValue) { m_intraSmoothingDisabledFlag=bValue; }
+
   Int*      getdQPs                         ()      { return m_aidQP;       }
   UInt      getDeltaQpRD                    ()      { return m_uiDeltaQpRD; }
 
   //====== Slice ========
-  Void  setSliceMode                   ( Int  i )       { m_sliceMode = i;              }
-  Void  setSliceArgument               ( Int  i )       { m_sliceArgument = i;          }
-  Int   getSliceMode                   ()              { return m_sliceMode;           }
-  Int   getSliceArgument               ()              { return m_sliceArgument;       }
+  Void  setSliceMode                   ( SliceConstraint  i )        { m_sliceMode = i;              }
+  Void  setSliceArgument               ( Int  i )                    { m_sliceArgument = i;          }
+  SliceConstraint getSliceMode         () const                      { return m_sliceMode;           }
+  Int   getSliceArgument               ()                            { return m_sliceArgument;       }
   //====== Dependent Slice ========
-  Void  setSliceSegmentMode            ( Int  i )      { m_sliceSegmentMode = i;       }
-  Void  setSliceSegmentArgument        ( Int  i )      { m_sliceSegmentArgument = i;   }
-  Int   getSliceSegmentMode            ()              { return m_sliceSegmentMode;    }
-  Int   getSliceSegmentArgument        ()              { return m_sliceSegmentArgument;}
-  Void      setLFCrossSliceBoundaryFlag     ( Bool   bValue  )    { m_bLFCrossSliceBoundaryFlag = bValue; }
-  Bool      getLFCrossSliceBoundaryFlag     ()                    { return m_bLFCrossSliceBoundaryFlag;   }
-
-  Void      setUseSAO                  (Bool bVal)     {m_bUseSAO = bVal;}
-  Bool      getUseSAO                  ()              {return m_bUseSAO;}
-  Void  setMaxNumOffsetsPerPic                   (Int iVal)            { m_maxNumOffsetsPerPic = iVal; }
-  Int   getMaxNumOffsetsPerPic                   ()                    { return m_maxNumOffsetsPerPic; }
-  Void  setSaoLcuBoundary              (Bool val)      { m_saoLcuBoundary = val; }
-  Bool  getSaoLcuBoundary              ()              { return m_saoLcuBoundary; }
-  Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
-  Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
-  Void  setTileUniformSpacingFlag      ( Bool b )          { m_tileUniformSpacingFlag = b; }
-  Bool  getTileUniformSpacingFlag      ()                  { return m_tileUniformSpacingFlag; }
-  Void  setNumColumnsMinus1            ( Int i )           { m_iNumColumnsMinus1 = i; }
-  Int   getNumColumnsMinus1            ()                  { return m_iNumColumnsMinus1; }
-  Void  setColumnWidth ( const std::vector<Int>& columnWidth ) { m_tileColumnWidth = columnWidth; }
-  UInt  getColumnWidth                 ( UInt columnIdx )      { return m_tileColumnWidth[columnIdx]; }
-  Void  setNumRowsMinus1               ( Int i )           { m_iNumRowsMinus1 = i; }
-  Int   getNumRowsMinus1               ()                  { return m_iNumRowsMinus1; }
-  Void  setRowHeight ( const std::vector<Int>& rowHeight)      { m_tileRowHeight = rowHeight; }
-  UInt  getRowHeight                   ( UInt rowIdx )         { return m_tileRowHeight[rowIdx]; }
+  Void  setSliceSegmentMode            ( SliceConstraint  i )        { m_sliceSegmentMode = i;       }
+  Void  setSliceSegmentArgument        ( Int  i )                    { m_sliceSegmentArgument = i;   }
+  SliceConstraint getSliceSegmentMode  () const                      { return m_sliceSegmentMode;    }
+  Int   getSliceSegmentArgument        ()                            { return m_sliceSegmentArgument;}
+  Void      setLFCrossSliceBoundaryFlag     ( Bool   bValue  )       { m_bLFCrossSliceBoundaryFlag = bValue; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                       { return m_bLFCrossSliceBoundaryFlag;   }
+
+  Void      setUseSAO                  (Bool bVal)                   { m_bUseSAO = bVal; }
+  Bool      getUseSAO                  ()                            { return m_bUseSAO; }
+  Void  setTestSAODisableAtPictureLevel (Bool bVal)                  { m_bTestSAODisableAtPictureLevel = bVal; }
+  Bool  getTestSAODisableAtPictureLevel ( ) const                    { return m_bTestSAODisableAtPictureLevel; }
+
+  Void   setSaoEncodingRate(Double v)                                { m_saoEncodingRate = v; }
+  Double getSaoEncodingRate() const                                  { return m_saoEncodingRate; }
+  Void   setSaoEncodingRateChroma(Double v)                          { m_saoEncodingRateChroma = v; }
+  Double getSaoEncodingRateChroma() const                            { return m_saoEncodingRateChroma; }
+  Void  setMaxNumOffsetsPerPic                   (Int iVal)          { m_maxNumOffsetsPerPic = iVal; }
+  Int   getMaxNumOffsetsPerPic                   ()                  { return m_maxNumOffsetsPerPic; }
+  Void  setSaoCtuBoundary              (Bool val)                    { m_saoCtuBoundary = val; }
+  Bool  getSaoCtuBoundary              ()                            { return m_saoCtuBoundary; }
+  Void  setLFCrossTileBoundaryFlag               ( Bool   val  )     { m_loopFilterAcrossTilesEnabledFlag = val; }
+  Bool  getLFCrossTileBoundaryFlag               ()                  { return m_loopFilterAcrossTilesEnabledFlag;   }
+  Void  setTileUniformSpacingFlag      ( Bool b )                    { m_tileUniformSpacingFlag = b; }
+  Bool  getTileUniformSpacingFlag      ()                            { return m_tileUniformSpacingFlag; }
+  Void  setNumColumnsMinus1            ( Int i )                     { m_iNumColumnsMinus1 = i; }
+  Int   getNumColumnsMinus1            ()                            { return m_iNumColumnsMinus1; }
+  Void  setColumnWidth ( const std::vector<Int>& columnWidth )       { m_tileColumnWidth = columnWidth; }
+  UInt  getColumnWidth                 ( UInt columnIdx )            { return m_tileColumnWidth[columnIdx]; }
+  Void  setNumRowsMinus1               ( Int i )                     { m_iNumRowsMinus1 = i; }
+  Int   getNumRowsMinus1               ()                            { return m_iNumRowsMinus1; }
+  Void  setRowHeight ( const std::vector<Int>& rowHeight)            { m_tileRowHeight = rowHeight; }
+  UInt  getRowHeight                   ( UInt rowIdx )               { return m_tileRowHeight[rowIdx]; }
   Void  xCheckGSParameters();
-  Void  setWaveFrontSynchro(Int iWaveFrontSynchro)       { m_iWaveFrontSynchro = iWaveFrontSynchro; }
-  Int   getWaveFrontsynchro()                            { return m_iWaveFrontSynchro; }
-  Void  setWaveFrontSubstreams(Int iWaveFrontSubstreams) { m_iWaveFrontSubstreams = iWaveFrontSubstreams; }
-  Int   getWaveFrontSubstreams()                         { return m_iWaveFrontSubstreams; }
-  Void  setDecodedPictureHashSEIEnabled(Int b)           { m_decodedPictureHashSEIEnabled = b; }
-  Int   getDecodedPictureHashSEIEnabled()                { return m_decodedPictureHashSEIEnabled; }
-  Void  setBufferingPeriodSEIEnabled(Int b)              { m_bufferingPeriodSEIEnabled = b; }
-  Int   getBufferingPeriodSEIEnabled()                   { return m_bufferingPeriodSEIEnabled; }
-  Void  setPictureTimingSEIEnabled(Int b)                { m_pictureTimingSEIEnabled = b; }
-  Int   getPictureTimingSEIEnabled()                     { return m_pictureTimingSEIEnabled; }
-  Void  setRecoveryPointSEIEnabled(Int b)                { m_recoveryPointSEIEnabled = b; }
-  Int   getRecoveryPointSEIEnabled()                     { return m_recoveryPointSEIEnabled; }
-  Void  setToneMappingInfoSEIEnabled(Bool b)                 {  m_toneMappingInfoSEIEnabled = b;  }
-  Bool  getToneMappingInfoSEIEnabled()                       {  return m_toneMappingInfoSEIEnabled;  }
-  Void  setTMISEIToneMapId(Int b)                            {  m_toneMapId = b;  }
-  Int   getTMISEIToneMapId()                                 {  return m_toneMapId;  }
-  Void  setTMISEIToneMapCancelFlag(Bool b)                   {  m_toneMapCancelFlag=b;  }
-  Bool  getTMISEIToneMapCancelFlag()                         {  return m_toneMapCancelFlag;  }
-  Void  setTMISEIToneMapPersistenceFlag(Bool b)              {  m_toneMapPersistenceFlag = b;  }
-  Bool   getTMISEIToneMapPersistenceFlag()                   {  return m_toneMapPersistenceFlag;  }
-  Void  setTMISEICodedDataBitDepth(Int b)                    {  m_codedDataBitDepth = b;  }
-  Int   getTMISEICodedDataBitDepth()                         {  return m_codedDataBitDepth;  }
-  Void  setTMISEITargetBitDepth(Int b)                       {  m_targetBitDepth = b;  }
-  Int   getTMISEITargetBitDepth()                            {  return m_targetBitDepth;  }
-  Void  setTMISEIModelID(Int b)                              {  m_modelId = b;  }
-  Int   getTMISEIModelID()                                   {  return m_modelId;  }
-  Void  setTMISEIMinValue(Int b)                             {  m_minValue = b;  }
-  Int   getTMISEIMinValue()                                  {  return m_minValue;  }
-  Void  setTMISEIMaxValue(Int b)                             {  m_maxValue = b;  }
-  Int   getTMISEIMaxValue()                                  {  return m_maxValue;  }
-  Void  setTMISEISigmoidMidpoint(Int b)                      {  m_sigmoidMidpoint = b;  }
-  Int   getTMISEISigmoidMidpoint()                           {  return m_sigmoidMidpoint;  }
-  Void  setTMISEISigmoidWidth(Int b)                         {  m_sigmoidWidth = b;  }
-  Int   getTMISEISigmoidWidth()                              {  return m_sigmoidWidth;  }
-  Void  setTMISEIStartOfCodedInterva( Int*  p )              {  m_startOfCodedInterval = p;  }
-  Int*  getTMISEIStartOfCodedInterva()                       {  return m_startOfCodedInterval;  }
-  Void  setTMISEINumPivots(Int b)                            {  m_numPivots = b;  }
-  Int   getTMISEINumPivots()                                 {  return m_numPivots;  }
-  Void  setTMISEICodedPivotValue( Int*  p )                  {  m_codedPivotValue = p;  }
-  Int*  getTMISEICodedPivotValue()                           {  return m_codedPivotValue;  }
-  Void  setTMISEITargetPivotValue( Int*  p )                 {  m_targetPivotValue = p;  }
-  Int*  getTMISEITargetPivotValue()                          {  return m_targetPivotValue;  }
-  Void  setTMISEICameraIsoSpeedIdc(Int b)                    {  m_cameraIsoSpeedIdc = b;  }
-  Int   getTMISEICameraIsoSpeedIdc()                         {  return m_cameraIsoSpeedIdc;  }
-  Void  setTMISEICameraIsoSpeedValue(Int b)                  {  m_cameraIsoSpeedValue = b;  }
-  Int   getTMISEICameraIsoSpeedValue()                       {  return m_cameraIsoSpeedValue;  }
-  Void  setTMISEIExposureIndexIdc(Int b)                     {  m_exposureIndexIdc = b;  }
-  Int   getTMISEIExposurIndexIdc()                           {  return m_exposureIndexIdc;  }
-  Void  setTMISEIExposureIndexValue(Int b)                   {  m_exposureIndexValue = b;  }
-  Int   getTMISEIExposurIndexValue()                         {  return m_exposureIndexValue;  }
-  Void  setTMISEIExposureCompensationValueSignFlag(Int b)    {  m_exposureCompensationValueSignFlag = b;  }
-  Int   getTMISEIExposureCompensationValueSignFlag()         {  return m_exposureCompensationValueSignFlag;  }
-  Void  setTMISEIExposureCompensationValueNumerator(Int b)   {  m_exposureCompensationValueNumerator = b;  }
-  Int   getTMISEIExposureCompensationValueNumerator()        {  return m_exposureCompensationValueNumerator;  }
-  Void  setTMISEIExposureCompensationValueDenomIdc(Int b)    {  m_exposureCompensationValueDenomIdc =b;  }
-  Int   getTMISEIExposureCompensationValueDenomIdc()         {  return m_exposureCompensationValueDenomIdc;  }
-  Void  setTMISEIRefScreenLuminanceWhite(Int b)              {  m_refScreenLuminanceWhite = b;  }
-  Int   getTMISEIRefScreenLuminanceWhite()                   {  return m_refScreenLuminanceWhite;  }
-  Void  setTMISEIExtendedRangeWhiteLevel(Int b)              {  m_extendedRangeWhiteLevel = b;  }
-  Int   getTMISEIExtendedRangeWhiteLevel()                   {  return m_extendedRangeWhiteLevel;  }
-  Void  setTMISEINominalBlackLevelLumaCodeValue(Int b)       {  m_nominalBlackLevelLumaCodeValue = b;  }
-  Int   getTMISEINominalBlackLevelLumaCodeValue()            {  return m_nominalBlackLevelLumaCodeValue;  }
-  Void  setTMISEINominalWhiteLevelLumaCodeValue(Int b)       {  m_nominalWhiteLevelLumaCodeValue = b;  }
-  Int   getTMISEINominalWhiteLevelLumaCodeValue()            {  return m_nominalWhiteLevelLumaCodeValue;  }
-  Void  setTMISEIExtendedWhiteLevelLumaCodeValue(Int b)      {  m_extendedWhiteLevelLumaCodeValue =b;  }
-  Int   getTMISEIExtendedWhiteLevelLumaCodeValue()           {  return m_extendedWhiteLevelLumaCodeValue;  }
-  Void  setFramePackingArrangementSEIEnabled(Int b)      { m_framePackingSEIEnabled = b; }
-  Int   getFramePackingArrangementSEIEnabled()           { return m_framePackingSEIEnabled; }
-  Void  setFramePackingArrangementSEIType(Int b)         { m_framePackingSEIType = b; }
-  Int   getFramePackingArrangementSEIType()              { return m_framePackingSEIType; }
-  Void  setFramePackingArrangementSEIId(Int b)           { m_framePackingSEIId = b; }
-  Int   getFramePackingArrangementSEIId()                { return m_framePackingSEIId; }
-  Void  setFramePackingArrangementSEIQuincunx(Int b)     { m_framePackingSEIQuincunx = b; }
-  Int   getFramePackingArrangementSEIQuincunx()          { return m_framePackingSEIQuincunx; }
-  Void  setFramePackingArrangementSEIInterpretation(Int b)  { m_framePackingSEIInterpretation = b; }
-  Int   getFramePackingArrangementSEIInterpretation()    { return m_framePackingSEIInterpretation; }
-  Void  setDisplayOrientationSEIAngle(Int b)             { m_displayOrientationSEIAngle = b; }
-  Int   getDisplayOrientationSEIAngle()                  { return m_displayOrientationSEIAngle; }
-  Void  setTemporalLevel0IndexSEIEnabled(Int b)          { m_temporalLevel0IndexSEIEnabled = b; }
-  Int   getTemporalLevel0IndexSEIEnabled()               { return m_temporalLevel0IndexSEIEnabled; }
-  Void  setGradualDecodingRefreshInfoEnabled(Int b)      { m_gradualDecodingRefreshInfoEnabled = b;    }
-  Int   getGradualDecodingRefreshInfoEnabled()           { return m_gradualDecodingRefreshInfoEnabled; }
-  Void  setDecodingUnitInfoSEIEnabled(Int b)                { m_decodingUnitInfoSEIEnabled = b;    }
-  Int   getDecodingUnitInfoSEIEnabled()                     { return m_decodingUnitInfoSEIEnabled; }
-  Void  setSOPDescriptionSEIEnabled(Int b)                { m_SOPDescriptionSEIEnabled = b; }
-  Int   getSOPDescriptionSEIEnabled()                     { return m_SOPDescriptionSEIEnabled; }
-  Void  setScalableNestingSEIEnabled(Int b)                { m_scalableNestingSEIEnabled = b; }
-  Int   getScalableNestingSEIEnabled()                     { return m_scalableNestingSEIEnabled; }
-
-#if H_MV
-  Bool   getSubBitstreamPropSEIEnabled()        { return m_subBistreamPropSEIEnabled;}
-  Void   setSubBitstreamPropSEIEnabled(Bool x)  { m_subBistreamPropSEIEnabled = x;}
-
-  Int    getNumAdditionalSubStreams()           { return m_numAdditionalSubStreams;}
-  Void   setNumAdditionalSubStreams(Int x)      { m_numAdditionalSubStreams = x;}
-
-  std::vector<Int> const &getSubBitstreamMode()  { return m_subBitstreamMode;}
-  Int   getSubBitstreamMode(Int idx)  { return m_subBitstreamMode[idx];}
-  Void  setSubBitstreamMode(std::vector<Int> &x)  { m_subBitstreamMode = x;}
-
-  std::vector<Int> const &getOutputLayerSetIdxToVps()  { return m_outputLayerSetIdxToVps;}
-  Int   getOutputLayerSetIdxToVps(Int idx)  { return m_outputLayerSetIdxToVps[idx];}
-  Void  setOutputLayerSetIdxToVps(std::vector<Int> &x)  { m_outputLayerSetIdxToVps = x;}
-
-  std::vector<Int> const &getHighestSublayerId()  { return m_highestSublayerId;}
-  Int   getHighestSublayerId(Int idx)  { return m_highestSublayerId[idx];}
-  Void  setHighestSublayerId(std::vector<Int> &x)  { m_highestSublayerId = x;}
-
-  std::vector<Int> const &getAvgBitRate()  { return m_avgBitRate;}
-  Int   getAvgBitRate(Int idx)  { return m_avgBitRate[idx];}
-  Void  setAvgBitRate(std::vector<Int> &x)  { m_avgBitRate = x;}
-
-  std::vector<Int> const &getMaxBitRate()  { return m_maxBitRate;}
-  Int   getMaxBitRate(Int idx)  { return m_maxBitRate[idx];}
-  Void  setMaxBitRate(std::vector<Int> &x)  { m_maxBitRate = x;}
-
-#endif
-  Void      setUseWP               ( Bool b )    { m_useWeightedPred   = b;    }
-  Void      setWPBiPred            ( Bool b )    { m_useWeightedBiPred = b;    }
-  Bool      getUseWP               ()            { return m_useWeightedPred;   }
-  Bool      getWPBiPred            ()            { return m_useWeightedBiPred; }
-  Void      setLog2ParallelMergeLevelMinus2   ( UInt u )    { m_log2ParallelMergeLevelMinus2       = u;    }
-  UInt      getLog2ParallelMergeLevelMinus2   ()            { return m_log2ParallelMergeLevelMinus2;       }
-  Void      setMaxNumMergeCand                ( UInt u )    { m_maxNumMergeCand = u;      }
-  UInt      getMaxNumMergeCand                ()            { return m_maxNumMergeCand;   }
-  Void      setUseScalingListId    ( Int  u )    { m_useScalingListId       = u;   }
-  Int       getUseScalingListId    ()            { return m_useScalingListId;      }
-  Void      setScalingListFile     ( Char*  pch ){ m_scalingListFile     = pch; }
-  Char*     getScalingListFile     ()            { return m_scalingListFile;    }
-  Void      setTMVPModeId ( Int  u ) { m_TMVPModeId = u;    }
-  Int       getTMVPModeId ()         { return m_TMVPModeId; }
-  Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
-  Int       getSignHideFlag()                    { return m_signHideFlag; }
-  Bool      getUseRateCtrl         ()              { return m_RCEnableRateControl;   }
-  Void      setUseRateCtrl         ( Bool b )      { m_RCEnableRateControl = b;      }
-  Int       getTargetBitrate       ()              { return m_RCTargetBitrate;       }
-  Void      setTargetBitrate       ( Int bitrate ) { m_RCTargetBitrate  = bitrate;   }
-  Int       getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
-  Void      setKeepHierBit         ( Int i )       { m_RCKeepHierarchicalBit = i;    }
-  Bool      getLCULevelRC          ()              { return m_RCLCULevelRC; }
-  Void      setLCULevelRC          ( Bool b )      { m_RCLCULevelRC = b; }
-  Bool      getUseLCUSeparateModel ()              { return m_RCUseLCUSeparateModel; }
-  Void      setUseLCUSeparateModel ( Bool b )      { m_RCUseLCUSeparateModel = b;    }
-  Int       getInitialQP           ()              { return m_RCInitialQP;           }
-  Void      setInitialQP           ( Int QP )      { m_RCInitialQP = QP;             }
-  Bool      getForceIntraQP        ()              { return m_RCForceIntraQP;        }
-  Void      setForceIntraQP        ( Bool b )      { m_RCForceIntraQP = b;           }
+  Void  setWaveFrontSynchro(Int iWaveFrontSynchro)                   { m_iWaveFrontSynchro = iWaveFrontSynchro; }
+  Int   getWaveFrontsynchro()                                        { return m_iWaveFrontSynchro; }
+  Void  setDecodedPictureHashSEIEnabled(Int b)                       { m_decodedPictureHashSEIEnabled = b; }
+  Int   getDecodedPictureHashSEIEnabled()                            { return m_decodedPictureHashSEIEnabled; }
+  Void  setBufferingPeriodSEIEnabled(Int b)                          { m_bufferingPeriodSEIEnabled = b; }
+  Int   getBufferingPeriodSEIEnabled()                               { return m_bufferingPeriodSEIEnabled; }
+  Void  setPictureTimingSEIEnabled(Int b)                            { m_pictureTimingSEIEnabled = b; }
+  Int   getPictureTimingSEIEnabled()                                 { return m_pictureTimingSEIEnabled; }
+  Void  setRecoveryPointSEIEnabled(Int b)                            { m_recoveryPointSEIEnabled = b; }
+  Int   getRecoveryPointSEIEnabled()                                 { return m_recoveryPointSEIEnabled; }
+  Void  setToneMappingInfoSEIEnabled(Bool b)                         { m_toneMappingInfoSEIEnabled = b;  }
+  Bool  getToneMappingInfoSEIEnabled()                               { return m_toneMappingInfoSEIEnabled;  }
+  Void  setTMISEIToneMapId(Int b)                                    { m_toneMapId = b;  }
+  Int   getTMISEIToneMapId()                                         { return m_toneMapId;  }
+  Void  setTMISEIToneMapCancelFlag(Bool b)                           { m_toneMapCancelFlag=b;  }
+  Bool  getTMISEIToneMapCancelFlag()                                 { return m_toneMapCancelFlag;  }
+  Void  setTMISEIToneMapPersistenceFlag(Bool b)                      { m_toneMapPersistenceFlag = b;  }
+  Bool   getTMISEIToneMapPersistenceFlag()                           { return m_toneMapPersistenceFlag;  }
+  Void  setTMISEICodedDataBitDepth(Int b)                            { m_codedDataBitDepth = b;  }
+  Int   getTMISEICodedDataBitDepth()                                 { return m_codedDataBitDepth;  }
+  Void  setTMISEITargetBitDepth(Int b)                               { m_targetBitDepth = b;  }
+  Int   getTMISEITargetBitDepth()                                    { return m_targetBitDepth;  }
+  Void  setTMISEIModelID(Int b)                                      { m_modelId = b;  }
+  Int   getTMISEIModelID()                                           { return m_modelId;  }
+  Void  setTMISEIMinValue(Int b)                                     { m_minValue = b;  }
+  Int   getTMISEIMinValue()                                          { return m_minValue;  }
+  Void  setTMISEIMaxValue(Int b)                                     { m_maxValue = b;  }
+  Int   getTMISEIMaxValue()                                          { return m_maxValue;  }
+  Void  setTMISEISigmoidMidpoint(Int b)                              { m_sigmoidMidpoint = b;  }
+  Int   getTMISEISigmoidMidpoint()                                   { return m_sigmoidMidpoint;  }
+  Void  setTMISEISigmoidWidth(Int b)                                 { m_sigmoidWidth = b;  }
+  Int   getTMISEISigmoidWidth()                                      { return m_sigmoidWidth;  }
+  Void  setTMISEIStartOfCodedInterva( Int*  p )                      { m_startOfCodedInterval = p;  }
+  Int*  getTMISEIStartOfCodedInterva()                               { return m_startOfCodedInterval;  }
+  Void  setTMISEINumPivots(Int b)                                    { m_numPivots = b;  }
+  Int   getTMISEINumPivots()                                         { return m_numPivots;  }
+  Void  setTMISEICodedPivotValue( Int*  p )                          { m_codedPivotValue = p;  }
+  Int*  getTMISEICodedPivotValue()                                   { return m_codedPivotValue;  }
+  Void  setTMISEITargetPivotValue( Int*  p )                         { m_targetPivotValue = p;  }
+  Int*  getTMISEITargetPivotValue()                                  { return m_targetPivotValue;  }
+  Void  setTMISEICameraIsoSpeedIdc(Int b)                            { m_cameraIsoSpeedIdc = b;  }
+  Int   getTMISEICameraIsoSpeedIdc()                                 { return m_cameraIsoSpeedIdc;  }
+  Void  setTMISEICameraIsoSpeedValue(Int b)                          { m_cameraIsoSpeedValue = b;  }
+  Int   getTMISEICameraIsoSpeedValue()                               { return m_cameraIsoSpeedValue;  }
+  Void  setTMISEIExposureIndexIdc(Int b)                             { m_exposureIndexIdc = b;  }
+  Int   getTMISEIExposurIndexIdc()                                   { return m_exposureIndexIdc;  }
+  Void  setTMISEIExposureIndexValue(Int b)                           { m_exposureIndexValue = b;  }
+  Int   getTMISEIExposurIndexValue()                                 { return m_exposureIndexValue;  }
+  Void  setTMISEIExposureCompensationValueSignFlag(Bool b)           { m_exposureCompensationValueSignFlag = b;  }
+  Bool  getTMISEIExposureCompensationValueSignFlag()                 { return m_exposureCompensationValueSignFlag;  }
+  Void  setTMISEIExposureCompensationValueNumerator(Int b)           { m_exposureCompensationValueNumerator = b;  }
+  Int   getTMISEIExposureCompensationValueNumerator()                { return m_exposureCompensationValueNumerator;  }
+  Void  setTMISEIExposureCompensationValueDenomIdc(Int b)            { m_exposureCompensationValueDenomIdc =b;  }
+  Int   getTMISEIExposureCompensationValueDenomIdc()                 { return m_exposureCompensationValueDenomIdc;  }
+  Void  setTMISEIRefScreenLuminanceWhite(Int b)                      { m_refScreenLuminanceWhite = b;  }
+  Int   getTMISEIRefScreenLuminanceWhite()                           { return m_refScreenLuminanceWhite;  }
+  Void  setTMISEIExtendedRangeWhiteLevel(Int b)                      { m_extendedRangeWhiteLevel = b;  }
+  Int   getTMISEIExtendedRangeWhiteLevel()                           { return m_extendedRangeWhiteLevel;  }
+  Void  setTMISEINominalBlackLevelLumaCodeValue(Int b)               { m_nominalBlackLevelLumaCodeValue = b;  }
+  Int   getTMISEINominalBlackLevelLumaCodeValue()                    { return m_nominalBlackLevelLumaCodeValue;  }
+  Void  setTMISEINominalWhiteLevelLumaCodeValue(Int b)               { m_nominalWhiteLevelLumaCodeValue = b;  }
+  Int   getTMISEINominalWhiteLevelLumaCodeValue()                    { return m_nominalWhiteLevelLumaCodeValue;  }
+  Void  setTMISEIExtendedWhiteLevelLumaCodeValue(Int b)              { m_extendedWhiteLevelLumaCodeValue =b;  }
+  Int   getTMISEIExtendedWhiteLevelLumaCodeValue()                   { return m_extendedWhiteLevelLumaCodeValue;  }
+  Void  setFramePackingArrangementSEIEnabled(Int b)                  { m_framePackingSEIEnabled = b; }
+  Int   getFramePackingArrangementSEIEnabled()                       { return m_framePackingSEIEnabled; }
+  Void  setFramePackingArrangementSEIType(Int b)                     { m_framePackingSEIType = b; }
+  Int   getFramePackingArrangementSEIType()                          { return m_framePackingSEIType; }
+  Void  setFramePackingArrangementSEIId(Int b)                       { m_framePackingSEIId = b; }
+  Int   getFramePackingArrangementSEIId()                            { return m_framePackingSEIId; }
+  Void  setFramePackingArrangementSEIQuincunx(Int b)                 { m_framePackingSEIQuincunx = b; }
+  Int   getFramePackingArrangementSEIQuincunx()                      { return m_framePackingSEIQuincunx; }
+  Void  setFramePackingArrangementSEIInterpretation(Int b)           { m_framePackingSEIInterpretation = b; }
+  Int   getFramePackingArrangementSEIInterpretation()                { return m_framePackingSEIInterpretation; }
+  Void  setSegmentedRectFramePackingArrangementSEIEnabled(Int b)     { m_segmentedRectFramePackingSEIEnabled = b; }
+  Int   getSegmentedRectFramePackingArrangementSEIEnabled()          { return m_segmentedRectFramePackingSEIEnabled; }
+  Void  setSegmentedRectFramePackingArrangementSEICancel(Int b)      { m_segmentedRectFramePackingSEICancel = b; }
+  Int   getSegmentedRectFramePackingArrangementSEICancel()           { return m_segmentedRectFramePackingSEICancel; }
+  Void  setSegmentedRectFramePackingArrangementSEIType(Int b)        { m_segmentedRectFramePackingSEIType = b; }
+  Int   getSegmentedRectFramePackingArrangementSEIType()             { return m_segmentedRectFramePackingSEIType; }
+  Void  setSegmentedRectFramePackingArrangementSEIPersistence(Int b) { m_segmentedRectFramePackingSEIPersistence = b; }
+  Int   getSegmentedRectFramePackingArrangementSEIPersistence()      { return m_segmentedRectFramePackingSEIPersistence; }
+  Void  setDisplayOrientationSEIAngle(Int b)                         { m_displayOrientationSEIAngle = b; }
+  Int   getDisplayOrientationSEIAngle()                              { return m_displayOrientationSEIAngle; }
+  Void  setTemporalLevel0IndexSEIEnabled(Int b)                      { m_temporalLevel0IndexSEIEnabled = b; }
+  Int   getTemporalLevel0IndexSEIEnabled()                           { return m_temporalLevel0IndexSEIEnabled; }
+  Void  setGradualDecodingRefreshInfoEnabled(Int b)                  { m_gradualDecodingRefreshInfoEnabled = b;    }
+  Int   getGradualDecodingRefreshInfoEnabled()                       { return m_gradualDecodingRefreshInfoEnabled; }
+  Void  setNoDisplaySEITLayer(Int b)                                 { m_noDisplaySEITLayer = b;    }
+  Int   getNoDisplaySEITLayer()                                      { return m_noDisplaySEITLayer; }
+  Void  setDecodingUnitInfoSEIEnabled(Int b)                         { m_decodingUnitInfoSEIEnabled = b;    }
+  Int   getDecodingUnitInfoSEIEnabled()                              { return m_decodingUnitInfoSEIEnabled; }
+  Void  setSOPDescriptionSEIEnabled(Int b)                           { m_SOPDescriptionSEIEnabled = b; }
+  Int   getSOPDescriptionSEIEnabled()                                { return m_SOPDescriptionSEIEnabled; }
+  Void  setScalableNestingSEIEnabled(Int b)                          { m_scalableNestingSEIEnabled = b; }
+  Int   getScalableNestingSEIEnabled()                               { return m_scalableNestingSEIEnabled; }
+  Void  setTMCTSSEIEnabled(Bool b)                                   { m_tmctsSEIEnabled = b; }
+  Bool  getTMCTSSEIEnabled()                                         { return m_tmctsSEIEnabled; }
+  Void  setTimeCodeSEIEnabled(Bool b)                                { m_timeCodeSEIEnabled = b; }
+  Bool  getTimeCodeSEIEnabled()                                      { return m_timeCodeSEIEnabled; }
+  Void  setNumberOfTimeSets(Int value)                               { m_timeCodeSEINumTs = value; }
+  Int   getNumberOfTimesets()                                        { return m_timeCodeSEINumTs; }
+  Void  setTimeSet(TComSEITimeSet element, Int index)                { m_timeSetArray[index] = element; }
+  TComSEITimeSet &getTimeSet(Int index)                              { return m_timeSetArray[index]; }
+  const TComSEITimeSet &getTimeSet(Int index) const                  { return m_timeSetArray[index]; }
+  Void  setKneeSEIEnabled(Int b)                                     { m_kneeSEIEnabled = b; }
+  Bool  getKneeSEIEnabled()                                          { return m_kneeSEIEnabled; }
+  Void  setKneeSEIId(Int b)                                          { m_kneeSEIId = b; }
+  Int   getKneeSEIId()                                               { return m_kneeSEIId; }
+  Void  setKneeSEICancelFlag(Bool b)                                 { m_kneeSEICancelFlag=b; }
+  Bool  getKneeSEICancelFlag()                                       { return m_kneeSEICancelFlag; }
+  Void  setKneeSEIPersistenceFlag(Bool b)                            { m_kneeSEIPersistenceFlag = b; }
+  Bool  getKneeSEIPersistenceFlag()                                  { return m_kneeSEIPersistenceFlag; }
+  Void  setKneeSEIInputDrange(Int b)                                 { m_kneeSEIInputDrange = b; }
+  Int   getKneeSEIInputDrange()                                      { return m_kneeSEIInputDrange; }
+  Void  setKneeSEIInputDispLuminance(Int b)                          { m_kneeSEIInputDispLuminance = b; }
+  Int   getKneeSEIInputDispLuminance()                               { return m_kneeSEIInputDispLuminance; }
+  Void  setKneeSEIOutputDrange(Int b)                                { m_kneeSEIOutputDrange = b; }
+  Int   getKneeSEIOutputDrange()                                     { return m_kneeSEIOutputDrange; }
+  Void  setKneeSEIOutputDispLuminance(Int b)                         { m_kneeSEIOutputDispLuminance = b; }
+  Int   getKneeSEIOutputDispLuminance()                              { return m_kneeSEIOutputDispLuminance; }
+  Void  setKneeSEINumKneePointsMinus1(Int b)                         { m_kneeSEINumKneePointsMinus1 = b; }
+  Int   getKneeSEINumKneePointsMinus1()                              { return m_kneeSEINumKneePointsMinus1; }
+  Void  setKneeSEIInputKneePoint(Int *p)                             { m_kneeSEIInputKneePoint = p; }
+  Int*  getKneeSEIInputKneePoint()                                   { return m_kneeSEIInputKneePoint; }
+  Void  setKneeSEIOutputKneePoint(Int *p)                            { m_kneeSEIOutputKneePoint = p; }
+  Int*  getKneeSEIOutputKneePoint()                                  { return m_kneeSEIOutputKneePoint; }
+  Void  setMasteringDisplaySEI(const TComSEIMasteringDisplay &src)   { m_masteringDisplay = src; }
+  const TComSEIMasteringDisplay &getMasteringDisplaySEI() const      { return m_masteringDisplay; }
+#if NH_MV
+  Bool   getSubBitstreamPropSEIEnabled()                             { return m_subBistreamPropSEIEnabled;}
+  Void   setSubBitstreamPropSEIEnabled(Bool x)                       { m_subBistreamPropSEIEnabled = x;}
+                                                                     
+  Int    getNumAdditionalSubStreams()                                { return m_numAdditionalSubStreams;}
+  Void   setNumAdditionalSubStreams(Int x)                           { m_numAdditionalSubStreams = x;}
+
+  std::vector<Int> const &getSubBitstreamMode()                      { return m_subBitstreamMode;}
+  Int   getSubBitstreamMode(Int idx)                                 { return m_subBitstreamMode[idx];}
+  Void  setSubBitstreamMode(std::vector<Int> &x)                     { m_subBitstreamMode = x;}
+
+  std::vector<Int> const &getOutputLayerSetIdxToVps()                { return m_outputLayerSetIdxToVps;}
+  Int   getOutputLayerSetIdxToVps(Int idx)                           { return m_outputLayerSetIdxToVps[idx];}
+  Void  setOutputLayerSetIdxToVps(std::vector<Int> &x)               { m_outputLayerSetIdxToVps = x;}
+                                                                     
+  std::vector<Int> const &getHighestSublayerId()                     { return m_highestSublayerId;}
+  Int   getHighestSublayerId(Int idx)                                { return m_highestSublayerId[idx];}
+  Void  setHighestSublayerId(std::vector<Int> &x)                    { m_highestSublayerId = x;}
+                                                                     
+  std::vector<Int> const &getAvgBitRate()                            { return m_avgBitRate;}
+  Int   getAvgBitRate(Int idx)                                       { return m_avgBitRate[idx];}
+  Void  setAvgBitRate(std::vector<Int> &x)                           { m_avgBitRate = x;}
+                                                                     
+  std::vector<Int> const &getMaxBitRate()                            { return m_maxBitRate;}
+  Int   getMaxBitRate(Int idx)                                       { return m_maxBitRate[idx];}
+  Void  setMaxBitRate(std::vector<Int> &x)                           { m_maxBitRate = x;}
+
+#endif
+
+  Void         setUseWP               ( Bool b )                     { m_useWeightedPred   = b;    }
+  Void         setWPBiPred            ( Bool b )                     { m_useWeightedBiPred = b;    }
+  Bool         getUseWP               ()                             { return m_useWeightedPred;   }
+  Bool         getWPBiPred            ()                             { return m_useWeightedBiPred; }
+  Void         setLog2ParallelMergeLevelMinus2   ( UInt u )          { m_log2ParallelMergeLevelMinus2       = u;    }
+  UInt         getLog2ParallelMergeLevelMinus2   ()                  { return m_log2ParallelMergeLevelMinus2;       }
+  Void         setMaxNumMergeCand                ( UInt u )          { m_maxNumMergeCand = u;      }
+  UInt         getMaxNumMergeCand                ()                  { return m_maxNumMergeCand;   }
+  Void         setUseScalingListId    ( ScalingListMode u )          { m_useScalingListId       = u;   }
+  ScalingListMode getUseScalingListId    ()                          { return m_useScalingListId;      }
+  Void         setScalingListFile     ( Char*  pch )                 { m_scalingListFile     = pch; }
+  Char*        getScalingListFile     ()                             { return m_scalingListFile;    }
+  Void         setTMVPModeId ( Int  u )                              { m_TMVPModeId = u;    }
+  Int          getTMVPModeId ()                                      { return m_TMVPModeId; }
+  Void         setSignHideFlag( Bool signHideFlag )                  { m_signHideFlag = signHideFlag; }
+  Bool         getSignHideFlag()                                     { return m_signHideFlag; }
+  Bool         getUseRateCtrl         ()                             { return m_RCEnableRateControl;   }
+  Void         setUseRateCtrl         ( Bool b )                     { m_RCEnableRateControl = b;      }
+  Int          getTargetBitrate       ()                             { return m_RCTargetBitrate;       }
+  Void         setTargetBitrate       ( Int bitrate )                { m_RCTargetBitrate  = bitrate;   }
+  Int          getKeepHierBit         ()                             { return m_RCKeepHierarchicalBit; }
+  Void         setKeepHierBit         ( Int i )                      { m_RCKeepHierarchicalBit = i;    }
+  Bool         getLCULevelRC          ()                             { return m_RCLCULevelRC; }
+  Void         setLCULevelRC          ( Bool b )                     { m_RCLCULevelRC = b; }
+  Bool         getUseLCUSeparateModel ()                             { return m_RCUseLCUSeparateModel; }
+  Void         setUseLCUSeparateModel ( Bool b )                     { m_RCUseLCUSeparateModel = b;    }
+  Int          getInitialQP           ()                             { return m_RCInitialQP;           }
+  Void         setInitialQP           ( Int QP )                     { m_RCInitialQP = QP;             }
+  Bool         getForceIntraQP        ()                             { return m_RCForceIntraQP;        }
+  Void         setForceIntraQP        ( Bool b )                     { m_RCForceIntraQP = b;           }
 
 #if KWU_RC_MADPRED_E0227
-  UInt      getUseDepthMADPred    ()                { return m_depthMADPred;        }
-  Void      setUseDepthMADPred    (UInt b)          { m_depthMADPred    = b;        }
-#endif
-#if KWU_RC_VIEWRC_E0227
-  Bool      getUseViewWiseRateCtrl    ()                { return m_bViewWiseRateCtrl;        }
-  Void      setUseViewWiseRateCtrl    (Bool b)          { m_bViewWiseRateCtrl    = b;        }
-#endif
-  Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
-  Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
-  Bool      getCUTransquantBypassFlagForceValue()          { return m_CUTransquantBypassFlagForce; }
-  Void      setCUTransquantBypassFlagForceValue(Bool flag) { m_CUTransquantBypassFlagForce = flag; }
-#if H_MV
-  Void      setVPS           ( TComVPS *p ) { m_cVPS = p;    }
-  TComVPS*  getVPS           ()             { return m_cVPS; }
+  UInt         getUseDepthMADPred     ()                             { return m_depthMADPred;        }
+  Void         setUseDepthMADPred     (UInt b)                       { m_depthMADPred    = b;        }
+#endif                                                             
+#if KWU_RC_VIEWRC_E0227                                            
+  Bool         getUseViewWiseRateCtrl ()                             { return m_bViewWiseRateCtrl;        }
+  Void         setUseViewWiseRateCtrl (Bool b)                       { m_bViewWiseRateCtrl    = b;        }
+#endif
+  Bool         getTransquantBypassEnableFlag()                       { return m_TransquantBypassEnableFlag; }
+  Void         setTransquantBypassEnableFlag(Bool flag)              { m_TransquantBypassEnableFlag = flag; }
+  Bool         getCUTransquantBypassFlagForceValue()                 { return m_CUTransquantBypassFlagForce; }
+  Void         setCUTransquantBypassFlagForceValue(Bool flag)        { m_CUTransquantBypassFlagForce = flag; }
+  CostMode     getCostMode( )                                        { return m_costMode; }
+  Void         setCostMode(CostMode m )                              { m_costMode = m; }
+#if NH_MV
+  Void         setVPS( TComVPS *p )                                  { m_cVPS = p;    }
+  TComVPS*     getVPS()                                              { return m_cVPS; }
 #else
-  Void setVPS(TComVPS *p) { m_cVPS = *p; }
-  TComVPS *getVPS() { return &m_cVPS; }
+  Void         setVPS(TComVPS *p)                                    { m_cVPS = *p; }
+  TComVPS *    getVPS()                                              { return &m_cVPS; }
 #endif
 
 #if H_3D
-  Void      setDLT           ( TComDLT *p ) { m_cDLT = p; }
-  TComDLT*  getDLT           ()             { return m_cDLT; }
-#endif
-
-  Void      setUseRecalculateQPAccordingToLambda ( Bool b ) { m_recalculateQPAccordingToLambda = b;    }
-  Bool      getUseRecalculateQPAccordingToLambda ()         { return m_recalculateQPAccordingToLambda; }
-
-  Void      setUseStrongIntraSmoothing ( Bool b ) { m_useStrongIntraSmoothing = b;    }
-  Bool      getUseStrongIntraSmoothing ()         { return m_useStrongIntraSmoothing; }
-
-  Void      setActiveParameterSetsSEIEnabled ( Int b )  { m_activeParameterSetsSEIEnabled = b; }  
-  Int       getActiveParameterSetsSEIEnabled ()         { return m_activeParameterSetsSEIEnabled; }
-  Bool      getVuiParametersPresentFlag()                 { return m_vuiParametersPresentFlag; }
-  Void      setVuiParametersPresentFlag(Bool i)           { m_vuiParametersPresentFlag = i; }
-  Bool      getAspectRatioInfoPresentFlag()               { return m_aspectRatioInfoPresentFlag; }
-  Void      setAspectRatioInfoPresentFlag(Bool i)         { m_aspectRatioInfoPresentFlag = i; }
-  Int       getAspectRatioIdc()                           { return m_aspectRatioIdc; }
-  Void      setAspectRatioIdc(Int i)                      { m_aspectRatioIdc = i; }
-  Int       getSarWidth()                                 { return m_sarWidth; }
-  Void      setSarWidth(Int i)                            { m_sarWidth = i; }
-  Int       getSarHeight()                                { return m_sarHeight; }
-  Void      setSarHeight(Int i)                           { m_sarHeight = i; }
-  Bool      getOverscanInfoPresentFlag()                  { return m_overscanInfoPresentFlag; }
-  Void      setOverscanInfoPresentFlag(Bool i)            { m_overscanInfoPresentFlag = i; }
-  Bool      getOverscanAppropriateFlag()                  { return m_overscanAppropriateFlag; }
-  Void      setOverscanAppropriateFlag(Bool i)            { m_overscanAppropriateFlag = i; }
-  Bool      getVideoSignalTypePresentFlag()               { return m_videoSignalTypePresentFlag; }
-  Void      setVideoSignalTypePresentFlag(Bool i)         { m_videoSignalTypePresentFlag = i; }
-  Int       getVideoFormat()                              { return m_videoFormat; }
-  Void      setVideoFormat(Int i)                         { m_videoFormat = i; }
-  Bool      getVideoFullRangeFlag()                       { return m_videoFullRangeFlag; }
-  Void      setVideoFullRangeFlag(Bool i)                 { m_videoFullRangeFlag = i; }
-  Bool      getColourDescriptionPresentFlag()             { return m_colourDescriptionPresentFlag; }
-  Void      setColourDescriptionPresentFlag(Bool i)       { m_colourDescriptionPresentFlag = i; }
-  Int       getColourPrimaries()                          { return m_colourPrimaries; }
-  Void      setColourPrimaries(Int i)                     { m_colourPrimaries = i; }
-  Int       getTransferCharacteristics()                  { return m_transferCharacteristics; }
-  Void      setTransferCharacteristics(Int i)             { m_transferCharacteristics = i; }
-  Int       getMatrixCoefficients()                       { return m_matrixCoefficients; }
-  Void      setMatrixCoefficients(Int i)                  { m_matrixCoefficients = i; }
-  Bool      getChromaLocInfoPresentFlag()                 { return m_chromaLocInfoPresentFlag; }
-  Void      setChromaLocInfoPresentFlag(Bool i)           { m_chromaLocInfoPresentFlag = i; }
-  Int       getChromaSampleLocTypeTopField()              { return m_chromaSampleLocTypeTopField; }
-  Void      setChromaSampleLocTypeTopField(Int i)         { m_chromaSampleLocTypeTopField = i; }
-  Int       getChromaSampleLocTypeBottomField()           { return m_chromaSampleLocTypeBottomField; }
-  Void      setChromaSampleLocTypeBottomField(Int i)      { m_chromaSampleLocTypeBottomField = i; }
-  Bool      getNeutralChromaIndicationFlag()              { return m_neutralChromaIndicationFlag; }
-  Void      setNeutralChromaIndicationFlag(Bool i)        { m_neutralChromaIndicationFlag = i; }
-  Window   &getDefaultDisplayWindow()                     { return m_defaultDisplayWindow; }
-  Void      setDefaultDisplayWindow (Int offsetLeft, Int offsetRight, Int offsetTop, Int offsetBottom ) { m_defaultDisplayWindow.setWindow (offsetLeft, offsetRight, offsetTop, offsetBottom); }
-  Bool      getFrameFieldInfoPresentFlag()                { return m_frameFieldInfoPresentFlag; }
-  Void      setFrameFieldInfoPresentFlag(Bool i)          { m_frameFieldInfoPresentFlag = i; }  
-  Bool      getPocProportionalToTimingFlag()              { return m_pocProportionalToTimingFlag; }
-  Void      setPocProportionalToTimingFlag(Bool x)        { m_pocProportionalToTimingFlag = x;    }
-  Int       getNumTicksPocDiffOneMinus1()                 { return m_numTicksPocDiffOneMinus1;    }
-  Void      setNumTicksPocDiffOneMinus1(Int x)            { m_numTicksPocDiffOneMinus1 = x;       }
-  Bool      getBitstreamRestrictionFlag()                 { return m_bitstreamRestrictionFlag; }
-  Void      setBitstreamRestrictionFlag(Bool i)           { m_bitstreamRestrictionFlag = i; }
-  Bool      getTilesFixedStructureFlag()                  { return m_tilesFixedStructureFlag; }
-  Void      setTilesFixedStructureFlag(Bool i)            { m_tilesFixedStructureFlag = i; }
-  Bool      getMotionVectorsOverPicBoundariesFlag()       { return m_motionVectorsOverPicBoundariesFlag; }
-  Void      setMotionVectorsOverPicBoundariesFlag(Bool i) { m_motionVectorsOverPicBoundariesFlag = i; }
-  Int       getMinSpatialSegmentationIdc()                { return m_minSpatialSegmentationIdc; }
-  Void      setMinSpatialSegmentationIdc(Int i)           { m_minSpatialSegmentationIdc = i; }
-  Int       getMaxBytesPerPicDenom()                      { return m_maxBytesPerPicDenom; }
-  Void      setMaxBytesPerPicDenom(Int i)                 { m_maxBytesPerPicDenom = i; }
-  Int       getMaxBitsPerMinCuDenom()                     { return m_maxBitsPerMinCuDenom; }
-  Void      setMaxBitsPerMinCuDenom(Int i)                { m_maxBitsPerMinCuDenom = i; }
-  Int       getLog2MaxMvLengthHorizontal()                { return m_log2MaxMvLengthHorizontal; }
-  Void      setLog2MaxMvLengthHorizontal(Int i)           { m_log2MaxMvLengthHorizontal = i; }
-  Int       getLog2MaxMvLengthVertical()                  { return m_log2MaxMvLengthVertical; }
-  Void      setLog2MaxMvLengthVertical(Int i)             { m_log2MaxMvLengthVertical = i; }
-  
-  Bool getProgressiveSourceFlag() const { return m_progressiveSourceFlag; }
-  Void setProgressiveSourceFlag(Bool b) { m_progressiveSourceFlag = b; }
-  
-  Bool getInterlacedSourceFlag() const { return m_interlacedSourceFlag; }
-  Void setInterlacedSourceFlag(Bool b) { m_interlacedSourceFlag = b; }
-  
-  Bool getNonPackedConstraintFlag() const { return m_nonPackedConstraintFlag; }
-  Void setNonPackedConstraintFlag(Bool b) { m_nonPackedConstraintFlag = b; }
-  
-  Bool getFrameOnlyConstraintFlag() const { return m_frameOnlyConstraintFlag; }
-  Void setFrameOnlyConstraintFlag(Bool b) { m_frameOnlyConstraintFlag = b; }
-#if H_3D
-
+  Void         setDLT( TComDLT *p )                                  s{ m_cDLT = p; }
+  TComDLT*     getDLT()                                              s{ return m_cDLT; }
+#endif
+  Void         setUseRecalculateQPAccordingToLambda (Bool b)         { m_recalculateQPAccordingToLambda = b;    }
+  Bool         getUseRecalculateQPAccordingToLambda ()               { return m_recalculateQPAccordingToLambda; }
+
+  Void         setUseStrongIntraSmoothing ( Bool b )                 { m_useStrongIntraSmoothing = b;    }
+  Bool         getUseStrongIntraSmoothing ()                         { return m_useStrongIntraSmoothing; }
+
+  Void         setEfficientFieldIRAPEnabled( Bool b )                { m_bEfficientFieldIRAPEnabled = b; }
+  Bool         getEfficientFieldIRAPEnabled( ) const                 { return m_bEfficientFieldIRAPEnabled; }
+
+  Void         setHarmonizeGopFirstFieldCoupleEnabled( Bool b )      { m_bHarmonizeGopFirstFieldCoupleEnabled = b; }
+  Bool         getHarmonizeGopFirstFieldCoupleEnabled( ) const       { return m_bHarmonizeGopFirstFieldCoupleEnabled; }
+
+  Void         setActiveParameterSetsSEIEnabled ( Int b )            { m_activeParameterSetsSEIEnabled = b; }
+  Int          getActiveParameterSetsSEIEnabled ()                   { return m_activeParameterSetsSEIEnabled; }
+  Bool         getVuiParametersPresentFlag()                         { return m_vuiParametersPresentFlag; }
+  Void         setVuiParametersPresentFlag(Bool i)                   { m_vuiParametersPresentFlag = i; }
+  Bool         getAspectRatioInfoPresentFlag()                       { return m_aspectRatioInfoPresentFlag; }
+  Void         setAspectRatioInfoPresentFlag(Bool i)                 { m_aspectRatioInfoPresentFlag = i; }
+  Int          getAspectRatioIdc()                                   { return m_aspectRatioIdc; }
+  Void         setAspectRatioIdc(Int i)                              { m_aspectRatioIdc = i; }
+  Int          getSarWidth()                                         { return m_sarWidth; }
+  Void         setSarWidth(Int i)                                    { m_sarWidth = i; }
+  Int          getSarHeight()                                        { return m_sarHeight; }
+  Void         setSarHeight(Int i)                                   { m_sarHeight = i; }
+  Bool         getOverscanInfoPresentFlag()                          { return m_overscanInfoPresentFlag; }
+  Void         setOverscanInfoPresentFlag(Bool i)                    { m_overscanInfoPresentFlag = i; }
+  Bool         getOverscanAppropriateFlag()                          { return m_overscanAppropriateFlag; }
+  Void         setOverscanAppropriateFlag(Bool i)                    { m_overscanAppropriateFlag = i; }
+  Bool         getVideoSignalTypePresentFlag()                       { return m_videoSignalTypePresentFlag; }
+  Void         setVideoSignalTypePresentFlag(Bool i)                 { m_videoSignalTypePresentFlag = i; }
+  Int          getVideoFormat()                                      { return m_videoFormat; }
+  Void         setVideoFormat(Int i)                                 { m_videoFormat = i; }
+  Bool         getVideoFullRangeFlag()                               { return m_videoFullRangeFlag; }
+  Void         setVideoFullRangeFlag(Bool i)                         { m_videoFullRangeFlag = i; }
+  Bool         getColourDescriptionPresentFlag()                     { return m_colourDescriptionPresentFlag; }
+  Void         setColourDescriptionPresentFlag(Bool i)               { m_colourDescriptionPresentFlag = i; }
+  Int          getColourPrimaries()                                  { return m_colourPrimaries; }
+  Void         setColourPrimaries(Int i)                             { m_colourPrimaries = i; }
+  Int          getTransferCharacteristics()                          { return m_transferCharacteristics; }
+  Void         setTransferCharacteristics(Int i)                     { m_transferCharacteristics = i; }
+  Int          getMatrixCoefficients()                               { return m_matrixCoefficients; }
+  Void         setMatrixCoefficients(Int i)                          { m_matrixCoefficients = i; }
+  Bool         getChromaLocInfoPresentFlag()                         { return m_chromaLocInfoPresentFlag; }
+  Void         setChromaLocInfoPresentFlag(Bool i)                   { m_chromaLocInfoPresentFlag = i; }
+  Int          getChromaSampleLocTypeTopField()                      { return m_chromaSampleLocTypeTopField; }
+  Void         setChromaSampleLocTypeTopField(Int i)                 { m_chromaSampleLocTypeTopField = i; }
+  Int          getChromaSampleLocTypeBottomField()                   { return m_chromaSampleLocTypeBottomField; }
+  Void         setChromaSampleLocTypeBottomField(Int i)              { m_chromaSampleLocTypeBottomField = i; }
+  Bool         getNeutralChromaIndicationFlag()                      { return m_neutralChromaIndicationFlag; }
+  Void         setNeutralChromaIndicationFlag(Bool i)                { m_neutralChromaIndicationFlag = i; }
+  Window      &getDefaultDisplayWindow()                             { return m_defaultDisplayWindow; }
+  Void         setDefaultDisplayWindow (Int offsetLeft, Int offsetRight, Int offsetTop, Int offsetBottom ) { m_defaultDisplayWindow.setWindow (offsetLeft, offsetRight, offsetTop, offsetBottom); }
+  Bool         getFrameFieldInfoPresentFlag()                        { return m_frameFieldInfoPresentFlag; }
+  Void         setFrameFieldInfoPresentFlag(Bool i)                  { m_frameFieldInfoPresentFlag = i; }
+  Bool         getPocProportionalToTimingFlag()                      { return m_pocProportionalToTimingFlag; }
+  Void         setPocProportionalToTimingFlag(Bool x)                { m_pocProportionalToTimingFlag = x;    }
+  Int          getNumTicksPocDiffOneMinus1()                         { return m_numTicksPocDiffOneMinus1;    }
+  Void         setNumTicksPocDiffOneMinus1(Int x)                    { m_numTicksPocDiffOneMinus1 = x;       }
+  Bool         getBitstreamRestrictionFlag()                         { return m_bitstreamRestrictionFlag; }
+  Void         setBitstreamRestrictionFlag(Bool i)                   { m_bitstreamRestrictionFlag = i; }
+  Bool         getTilesFixedStructureFlag()                          { return m_tilesFixedStructureFlag; }
+  Void         setTilesFixedStructureFlag(Bool i)                    { m_tilesFixedStructureFlag = i; }
+  Bool         getMotionVectorsOverPicBoundariesFlag()               { return m_motionVectorsOverPicBoundariesFlag; }
+  Void         setMotionVectorsOverPicBoundariesFlag(Bool i)         { m_motionVectorsOverPicBoundariesFlag = i; }
+  Int          getMinSpatialSegmentationIdc()                        { return m_minSpatialSegmentationIdc; }
+  Void         setMinSpatialSegmentationIdc(Int i)                   { m_minSpatialSegmentationIdc = i; }
+  Int          getMaxBytesPerPicDenom()                              { return m_maxBytesPerPicDenom; }
+  Void         setMaxBytesPerPicDenom(Int i)                         { m_maxBytesPerPicDenom = i; }
+  Int          getMaxBitsPerMinCuDenom()                             { return m_maxBitsPerMinCuDenom; }
+  Void         setMaxBitsPerMinCuDenom(Int i)                        { m_maxBitsPerMinCuDenom = i; }
+  Int          getLog2MaxMvLengthHorizontal()                        { return m_log2MaxMvLengthHorizontal; }
+  Void         setLog2MaxMvLengthHorizontal(Int i)                   { m_log2MaxMvLengthHorizontal = i; }
+  Int          getLog2MaxMvLengthVertical()                          { return m_log2MaxMvLengthVertical; }
+  Void         setLog2MaxMvLengthVertical(Int i)                     { m_log2MaxMvLengthVertical = i; }
+
+  Bool         getProgressiveSourceFlag() const                      { return m_progressiveSourceFlag; }
+  Void         setProgressiveSourceFlag(Bool b)                      { m_progressiveSourceFlag = b; }
+
+  Bool         getInterlacedSourceFlag() const                       { return m_interlacedSourceFlag; }
+  Void         setInterlacedSourceFlag(Bool b)                       { m_interlacedSourceFlag = b; }
+
+  Bool         getNonPackedConstraintFlag() const                    { return m_nonPackedConstraintFlag; }
+  Void         setNonPackedConstraintFlag(Bool b)                    { m_nonPackedConstraintFlag = b; }
+
+  Bool         getFrameOnlyConstraintFlag() const                    { return m_frameOnlyConstraintFlag; }
+  Void         setFrameOnlyConstraintFlag(Bool b)                    { m_frameOnlyConstraintFlag = b; }
+
+  UInt         getBitDepthConstraintValue() const                    { return m_bitDepthConstraintValue; }
+  Void         setBitDepthConstraintValue(UInt v)                    { m_bitDepthConstraintValue=v; }
+
+  ChromaFormat getChromaFormatConstraintValue() const                { return m_chromaFormatConstraintValue; }
+  Void         setChromaFormatConstraintValue(ChromaFormat v)        { m_chromaFormatConstraintValue=v; }
+
+  Bool         getIntraConstraintFlag() const                        { return m_intraConstraintFlag; }
+  Void         setIntraConstraintFlag(Bool b)                        { m_intraConstraintFlag=b; }
+
+  Bool         getOnePictureOnlyConstraintFlag() const               { return m_onePictureOnlyConstraintFlag; }
+  Void         setOnePictureOnlyConstraintFlag(Bool b)               { m_onePictureOnlyConstraintFlag=b; }
+
+  Bool         getLowerBitRateConstraintFlag() const                 { return m_lowerBitRateConstraintFlag; }
+  Void         setLowerBitRateConstraintFlag(Bool b)                 { m_lowerBitRateConstraintFlag=b; }
+  Bool      getChromaSamplingFilterHintEnabled()                     { return m_chromaSamplingFilterHintEnabled;}
+  Void      setChromaSamplingFilterHintEnabled(Bool i)               { m_chromaSamplingFilterHintEnabled = i;}
+  Int       getChromaSamplingHorFilterIdc()                          { return m_chromaSamplingHorFilterIdc;}
+  Void      setChromaSamplingHorFilterIdc(Int i)                     { m_chromaSamplingHorFilterIdc = i;}
+  Int       getChromaSamplingVerFilterIdc()                          { return m_chromaSamplingVerFilterIdc;}
+  Void      setChromaSamplingVerFilterIdc(Int i)                     { m_chromaSamplingVerFilterIdc = i;}
+
+  Void      setSummaryOutFilename(const std::string &s)              { m_summaryOutFilename = s; }
+  const std::string& getSummaryOutFilename() const                   { return m_summaryOutFilename; }
+  Void      setSummaryPicFilenameBase(const std::string &s)          { m_summaryPicFilenameBase = s; }
+  const std::string& getSummaryPicFilenameBase() const               { return m_summaryPicFilenameBase; }
+
+  Void      setSummaryVerboseness(UInt v)                            { m_summaryVerboseness = v; }
+  UInt      getSummaryVerboseness( ) const                           { return m_summaryVerboseness; }
+
+#if NH_3D
   // Only flags that are not in the SPS3dExtension should go here. 
   /// 3D Tools 
@@ -914,5 +1138,5 @@
   Void      setCameraParameters             ( TAppComCamPara* c) { m_cameraParameters   = c; }
 
-#if H_3D_VSO
+#if NH_3D_VSO
  //==== VSO  ==========
   Void      setRenderModelParameters ( TRenModSetupStrParser* c ) { m_renderModelParameters = c; }
@@ -943,8 +1167,6 @@
   Double    getDispCoeff                    ()              { return m_dDispCoeff;    }
   Void      setDispCoeff                    ( Double  d )   { m_dDispCoeff  = d; }
-#endif // H_3D_VSO
-
- //==== DIM  ==========
-#if H_3D_DIM
+#endif // NH_3D_VSO
+
   Bool      getUseDMM                       ()        { return m_useDMM; }
   Void      setUseDMM                       ( Bool b) { m_useDMM = b;    }
@@ -954,13 +1176,11 @@
   Bool      getUseDLT                       ()        { return m_useDLT; }
   Void      setUseDLT                       ( Bool b) { m_useDLT = b;    }
-#endif
-#if H_3D_QTLPC
+
   Void      setUseQTL                       ( Bool b ) { m_bUseQTL = b;    }
   Bool      getUseQTL                       ()         { return m_bUseQTL; }
-#endif
-  Void                    setProfileIdc( Int a )    { assert( a == 1 || a == 6 || a == 8 ); m_profileIdc = a;  }
-  Bool                    decProcAnnexI()           { assert( m_profileIdc != -1 ); return ( m_profileIdc == 8); }    
-
-#endif // H_3D
+
+  Void      setProfileIdc( Int a )    { assert( a == 1 || a == 6 || a == 8 ); m_profileIdc = a;  }
+  Bool      decProcAnnexI()           { assert( m_profileIdc != -1 ); return ( m_profileIdc == Profile::MAIN3D ); }    
+#endif // NH_3D
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -40,4 +40,5 @@
 #include "TEncCu.h"
 #include "TEncAnalyze.h"
+#include "TLibCommon/Debug.h"
 
 #include <cmath>
@@ -45,4 +46,5 @@
 using namespace std;
 
+
 //! \ingroup TLibEncoder
 //! \{
@@ -53,16 +55,17 @@
 
 /**
- \param    uiTotalDepth  total number of allowable depth
+ \param    uhTotalDepth  total number of allowable depth
  \param    uiMaxWidth    largest CU width
  \param    uiMaxHeight   largest CU height
+ \param    chromaFormat  chroma format
  */
-Void TEncCu::create(UChar uhTotalDepth, UInt uiMaxWidth, UInt uiMaxHeight)
+Void TEncCu::create(UChar uhTotalDepth, UInt uiMaxWidth, UInt uiMaxHeight, ChromaFormat chromaFormat)
 {
   Int i;
-  
+
   m_uhTotalDepth   = uhTotalDepth + 1;
   m_ppcBestCU      = new TComDataCU*[m_uhTotalDepth-1];
   m_ppcTempCU      = new TComDataCU*[m_uhTotalDepth-1];
-    
+
 #if H_3D_ARP
   m_ppcWeightedTempCU = new TComDataCU*[m_uhTotalDepth-1];
@@ -79,5 +82,5 @@
   m_ppcOrigYuvDBBP = new TComYuv*[m_uhTotalDepth-1];
 #endif
-  
+
   UInt uiNumPartitions;
   for( i=0 ; i<m_uhTotalDepth-1 ; i++)
@@ -86,27 +89,28 @@
     UInt uiWidth  = uiMaxWidth  >> i;
     UInt uiHeight = uiMaxHeight >> i;
-    
-    m_ppcBestCU[i] = new TComDataCU; m_ppcBestCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
-    m_ppcTempCU[i] = new TComDataCU; m_ppcTempCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
-    
+
+    m_ppcBestCU[i] = new TComDataCU; m_ppcBestCU[i]->create( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
+    m_ppcTempCU[i] = new TComDataCU; m_ppcTempCU[i]->create( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
 #if H_3D_ARP
     m_ppcWeightedTempCU[i] = new TComDataCU; m_ppcWeightedTempCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
 #endif  
 
-    m_ppcPredYuvBest[i] = new TComYuv; m_ppcPredYuvBest[i]->create(uiWidth, uiHeight);
-    m_ppcResiYuvBest[i] = new TComYuv; m_ppcResiYuvBest[i]->create(uiWidth, uiHeight);
-    m_ppcRecoYuvBest[i] = new TComYuv; m_ppcRecoYuvBest[i]->create(uiWidth, uiHeight);
-    
-    m_ppcPredYuvTemp[i] = new TComYuv; m_ppcPredYuvTemp[i]->create(uiWidth, uiHeight);
-    m_ppcResiYuvTemp[i] = new TComYuv; m_ppcResiYuvTemp[i]->create(uiWidth, uiHeight);
-    m_ppcRecoYuvTemp[i] = new TComYuv; m_ppcRecoYuvTemp[i]->create(uiWidth, uiHeight);
-    
-    m_ppcOrigYuv    [i] = new TComYuv; m_ppcOrigYuv    [i]->create(uiWidth, uiHeight);
+    m_ppcPredYuvBest[i] = new TComYuv; m_ppcPredYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
+    m_ppcResiYuvBest[i] = new TComYuv; m_ppcResiYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
+    m_ppcRecoYuvBest[i] = new TComYuv; m_ppcRecoYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
+
+    m_ppcPredYuvTemp[i] = new TComYuv; m_ppcPredYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
+    m_ppcResiYuvTemp[i] = new TComYuv; m_ppcResiYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
+    m_ppcRecoYuvTemp[i] = new TComYuv; m_ppcRecoYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
+
+    m_ppcOrigYuv    [i] = new TComYuv; m_ppcOrigYuv    [i]->create(uiWidth, uiHeight, chromaFormat);
 #if H_3D_DBBP
     m_ppcOrigYuvDBBP[i] = new TComYuv; m_ppcOrigYuvDBBP[i]->create(uiWidth, uiHeight);
 #endif
-  }
-  
-  m_bEncodeDQP = false;
+
+  }
+
+  m_bEncodeDQP          = false;
+
 #if KWU_RC_MADPRED_E0227
   m_LCUPredictionSAD = 0;
@@ -116,9 +120,12 @@
 #endif
 
+  m_stillToCodeChromaQpOffsetFlag  = false;
+  m_cuChromaQpOffsetIdxPlus1       = 0;
+
   // initialize partition order.
   UInt* piTmp = &g_auiZscanToRaster[0];
   initZscanToRaster( m_uhTotalDepth, 1, 0, piTmp);
   initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
-  
+
   // initialize conversion matrix from partition index to pel
   initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
@@ -128,5 +135,5 @@
 {
   Int i;
-  
+
   for( i=0 ; i<m_uhTotalDepth-1 ; i++)
   {
@@ -249,16 +256,13 @@
   m_pcPredSearch       = pcEncTop->getPredSearch();
   m_pcTrQuant          = pcEncTop->getTrQuant();
-  m_pcBitCounter       = pcEncTop->getBitCounter();
   m_pcRdCost           = pcEncTop->getRdCost();
-  
+
   m_pcEntropyCoder     = pcEncTop->getEntropyCoder();
-  m_pcCavlcCoder       = pcEncTop->getCavlcCoder();
-  m_pcSbacCoder       = pcEncTop->getSbacCoder();
   m_pcBinCABAC         = pcEncTop->getBinCABAC();
-  
-  m_pppcRDSbacCoder   = pcEncTop->getRDSbacCoder();
-  m_pcRDGoOnSbacCoder = pcEncTop->getRDGoOnSbacCoder();
-  
-  m_pcRateCtrl        = pcEncTop->getRateCtrl();
+
+  m_pppcRDSbacCoder    = pcEncTop->getRDSbacCoder();
+  m_pcRDGoOnSbacCoder  = pcEncTop->getRDGoOnSbacCoder();
+
+  m_pcRateCtrl         = pcEncTop->getRateCtrl();
 }
 
@@ -267,15 +271,12 @@
 // ====================================================================================================================
 
-/** \param  rpcCU pointer of CU data class
+/** 
+ \param  pCtu pointer of CU data class
  */
-Void TEncCu::compressCU( TComDataCU*& rpcCU )
+Void TEncCu::compressCtu( TComDataCU* pCtu )
 {
   // initialize CU data
-  m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
-  m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
-
-#if H_3D_DISABLE_CHROMA
-  m_ppcWeightedTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
-#endif
+  m_ppcBestCU[0]->initCtu( pCtu->getPic(), pCtu->getCtuRsAddr() );
+  m_ppcTempCU[0]->initCtu( pCtu->getPic(), pCtu->getCtuRsAddr() );
 
 #if KWU_RC_MADPRED_E0227
@@ -287,27 +288,35 @@
 
   // analysis of CU
-  xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 );
+  DEBUG_STRING_NEW(sDebug)
+
+  xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 DEBUG_STRING_PASS_INTO(sDebug) );
+  DEBUG_STRING_OUTPUT(std::cout, sDebug)
 
 #if ADAPTIVE_QP_SELECTION
   if( m_pcEncCfg->getUseAdaptQpSelect() )
   {
-    if(rpcCU->getSlice()->getSliceType()!=I_SLICE) //IIII
-    {
-      xLcuCollectARLStats( rpcCU);
+    if(pCtu->getSlice()->getSliceType()!=I_SLICE) //IIII
+    {
+      xCtuCollectARLStats( pCtu );
     }
   }
 #endif
 }
-/** \param  pcCU  pointer of CU data class
+/** \param  pCtu  pointer of CU data class
  */
-Void TEncCu::encodeCU ( TComDataCU* pcCU )
+Void TEncCu::encodeCtu ( TComDataCU* pCtu )
 {
-  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  if ( pCtu->getSlice()->getPPS()->getUseDQP() )
   {
     setdQPFlag(true);
   }
 
+  if ( pCtu->getSlice()->getUseChromaQpAdj() )
+  {
+    setCodeChromaQpAdjFlag(true);
+  }
+
   // Encode CU data
-  xEncodeCU( pcCU, 0, 0 );
+  xEncodeCU( pCtu, 0, 0 );
 }
 
@@ -315,49 +324,41 @@
 // Protected member functions
 // ====================================================================================================================
-/** Derive small set of test modes for AMP encoder speed-up
- *\param   rpcBestCU
- *\param   eParentPartSize
- *\param   bTestAMP_Hor
- *\param   bTestAMP_Ver
- *\param   bTestMergeAMP_Hor
- *\param   bTestMergeAMP_Ver
- *\returns Void 
-*/
+//! Derive small set of test modes for AMP encoder speed-up
 #if AMP_ENC_SPEEDUP
 #if AMP_MRG
-Void TEncCu::deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver)
-#else
-Void TEncCu::deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver)
+Void TEncCu::deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver)
+#else
+Void TEncCu::deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver)
 #endif
 {
-  if ( rpcBestCU->getPartitionSize(0) == SIZE_2NxN )
+  if ( pcBestCU->getPartitionSize(0) == SIZE_2NxN )
   {
     bTestAMP_Hor = true;
   }
-  else if ( rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+  else if ( pcBestCU->getPartitionSize(0) == SIZE_Nx2N )
   {
     bTestAMP_Ver = true;
   }
-  else if ( rpcBestCU->getPartitionSize(0) == SIZE_2Nx2N && rpcBestCU->getMergeFlag(0) == false && rpcBestCU->isSkipped(0) == false )
-  {
-    bTestAMP_Hor = true;          
-    bTestAMP_Ver = true;          
+  else if ( pcBestCU->getPartitionSize(0) == SIZE_2Nx2N && pcBestCU->getMergeFlag(0) == false && pcBestCU->isSkipped(0) == false )
+  {
+    bTestAMP_Hor = true;
+    bTestAMP_Ver = true;
   }
 
 #if AMP_MRG
-  //! Utilizing the partition size of parent PU    
+  //! Utilizing the partition size of parent PU
   if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
-  { 
+  {
     bTestMergeAMP_Hor = true;
     bTestMergeAMP_Ver = true;
   }
 
-  if ( eParentPartSize == SIZE_NONE ) //! if parent is intra
-  {
-    if ( rpcBestCU->getPartitionSize(0) == SIZE_2NxN )
+  if ( eParentPartSize == NUMBER_OF_PART_SIZES ) //! if parent is intra
+  {
+    if ( pcBestCU->getPartitionSize(0) == SIZE_2NxN )
     {
       bTestMergeAMP_Hor = true;
     }
-    else if ( rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+    else if ( pcBestCU->getPartitionSize(0) == SIZE_Nx2N )
     {
       bTestMergeAMP_Ver = true;
@@ -365,19 +366,19 @@
   }
 
-  if ( rpcBestCU->getPartitionSize(0) == SIZE_2Nx2N && rpcBestCU->isSkipped(0) == false )
-  {
-    bTestMergeAMP_Hor = true;          
-    bTestMergeAMP_Ver = true;          
-  }
-
-  if ( rpcBestCU->getWidth(0) == 64 )
-  { 
+  if ( pcBestCU->getPartitionSize(0) == SIZE_2Nx2N && pcBestCU->isSkipped(0) == false )
+  {
+    bTestMergeAMP_Hor = true;
+    bTestMergeAMP_Ver = true;
+  }
+
+  if ( pcBestCU->getWidth(0) == 64 )
+  {
     bTestAMP_Hor = false;
     bTestAMP_Ver = false;
-  }    
-#else
-  //! Utilizing the partition size of parent PU        
+  }
+#else
+  //! Utilizing the partition size of parent PU
   if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
-  { 
+  {
     bTestAMP_Hor = true;
     bTestAMP_Ver = true;
@@ -385,25 +386,21 @@
 
   if ( eParentPartSize == SIZE_2Nx2N )
-  { 
+  {
     bTestAMP_Hor = false;
     bTestAMP_Ver = false;
-  }      
+  }
 #endif
 }
 #endif
+
 
 // ====================================================================================================================
 // Protected member functions
 // ====================================================================================================================
-/** Compress a CU block recursively with enabling sub-LCU-level delta QP
- *\param   rpcBestCU
- *\param   rpcTempCU
- *\param   uiDepth
- *\returns Void
- *
- *- for loop of QP value to compress the current CU with all possible QP
+/** Compress a CU block recursively with enabling sub-CTU-level delta QP
+ *  - for loop of QP value to compress the current CU with all possible QP
 */
 #if AMP_ENC_SPEEDUP
-Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth, PartSize eParentPartSize )
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth DEBUG_STRING_FN_DECLARE(sDebug_), PartSize eParentPartSize )
 #else
 Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
@@ -411,4 +408,8 @@
 {
   TComPic* pcPic = rpcBestCU->getPic();
+  DEBUG_STRING_NEW(sDebug)
+  const TComPPS &pps=*(rpcTempCU->getSlice()->getPPS());
+  const TComSPS &sps=*(rpcTempCU->getSlice()->getSPS());
+
 
 #if H_3D_QTLPC
@@ -424,6 +425,7 @@
   Bool bTryNx2N           = true;
 #endif
+
   // get Original YUV data from picture
-  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu() );
 
 #if H_3D_QTLPC  
@@ -432,10 +434,10 @@
 #endif
 
-  // variable for Early CU determination
+    // variable for Early CU determination
   Bool    bSubBranch = true;
 
   // variable for Cbf fast mode PU decision
   Bool    doNotBlockPu = true;
-  Bool earlyDetectionSkipMode = false;
+  Bool    earlyDetectionSkipMode = false;
 
 #if H_3D_VSP
@@ -469,9 +471,11 @@
   Bool isAddLowestQP = false;
 
-  if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  const UInt numberValidComponents = rpcBestCU->getPic()->getNumberValidComponents();
+
+  if( uiDepth <= pps.getMaxCuDQPDepth() )
   {
     Int idQP = m_pcEncCfg->getMaxDeltaQP();
-    iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
-    iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
+    iMinQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP+idQP );
   }
   else
@@ -486,9 +490,10 @@
     iMaxQP = m_pcRateCtrl->getRCQP();
   }
+
   // transquant-bypass (TQB) processing loop variable initialisation ---
 
   const Int lowestQP = iMinQP; // For TQB, use this QP which is the lowest non TQB QP tested (rather than QP'=0) - that way delta QPs are smaller, and TQB can be tested at all CU levels.
 
-  if ( (rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag()) )
+  if ( (pps.getTransquantBypassEnableFlag()) )
   {
     isAddLowestQP = true; // mark that the first iteration is to cost TQB mode.
@@ -504,11 +509,9 @@
   bICEnabled = bICEnabled && rpcTempCU->getSlice()->getApplyIC();
 #endif
-  // If slice start or slice end is within this cu...
+
   TComSlice * pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
-  Bool bSliceStart = pcSlice->getSliceSegmentCurStartCUAddr()>rpcTempCU->getSCUAddr()&&pcSlice->getSliceSegmentCurStartCUAddr()<rpcTempCU->getSCUAddr()+rpcTempCU->getTotalNumPart();
-  Bool bSliceEnd = (pcSlice->getSliceSegmentCurEndCUAddr()>rpcTempCU->getSCUAddr()&&pcSlice->getSliceSegmentCurEndCUAddr()<rpcTempCU->getSCUAddr()+rpcTempCU->getTotalNumPart());
-  Bool bInsidePicture = ( uiRPelX < rpcBestCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < rpcBestCU->getSlice()->getSPS()->getPicHeightInLumaSamples() );
   // We need to split, so don't try these modes.
-  if(!bSliceEnd && !bSliceStart && bInsidePicture )
+  if ( ( uiRPelX < sps.getPicWidthInLumaSamples() ) &&
+       ( uiBPelY < sps.getPicHeightInLumaSamples() ) )
   {
 #if  H_3D_FAST_TEXTURE_ENCODING
@@ -529,4 +532,17 @@
       bTrySplit    = true;
 #endif
+
+      m_cuChromaQpOffsetIdxPlus1 = 0;
+      if (pcSlice->getUseChromaQpAdj())
+      {
+        /* Pre-estimation of chroma QP based on input block activity may be performed
+         * here, using for example m_ppcOrigYuv[uiDepth] */
+        /* To exercise the current code, the index used for adjustment is based on
+         * block position
+         */
+        Int lgMinCuSize = sps.getLog2MinCodingBlockSize() +
+                          std::max<Int>(0, sps.getLog2DiffMaxMinCodingBlockSize()-Int(pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth()));
+        m_cuChromaQpOffsetIdxPlus1 = ((uiLPelX >> lgMinCuSize) + (uiTPelY >> lgMinCuSize)) % (pps.getPpsRangeExtension().getChromaQpOffsetListLen() + 1);
+      }
 
       rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
@@ -631,36 +647,37 @@
           Bool bICFlag = uiICId ? true : false;
 #endif
-          // 2Nx2N
-          if(m_pcEncCfg->getUseEarlySkipDetection())
-          {
+        // 2Nx2N
+        if(m_pcEncCfg->getUseEarlySkipDetection())
+        {
 #if H_3D_IC
             rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
 #endif
 #if  H_3D_FAST_TEXTURE_ENCODING
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode  );//by Competition for inter_2Nx2N
-#else
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
-            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );//by Competition for inter_2Nx2N
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode  );//by Competition for inter_2Nx2N
+#else
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );//by Competition for inter_2Nx2N
 #endif
 #if H_3D_VSP
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-          }
-          // SKIP
+        }
+        // SKIP
 #if H_3D_IC
           rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
 #endif
-          xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
+        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU DEBUG_STRING_PASS_INTO(sDebug), &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
 #if  H_3D_FAST_TEXTURE_ENCODING
           bFMD = bIVFMerge && rpcBestCU->isSkipped(0);
 #endif
-          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
           rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
 
-          if(!m_pcEncCfg->getUseEarlySkipDetection())
-          {
-            // 2Nx2N, NxN
+        if(!m_pcEncCfg->getUseEarlySkipDetection())
+        {
+          // 2Nx2N, NxN
 #if H_3D_IC
             rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
@@ -669,11 +686,11 @@
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #else
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
-            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #endif
 #if H_3D_VSP
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-
 #if H_3D_DBBP
             if( rpcTempCU->getSlice()->getDepthBasedBlkPartFlag() && rpcTempCU->getSlice()->getDefaultRefViewIdxAvailableFlag() )
@@ -686,14 +703,14 @@
             }
 #endif
-            if(m_pcEncCfg->getUseCbfFastMode())
-            {
-              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
-            }
-          }
+
+          if(m_pcEncCfg->getUseCbfFastMode())
+          {
+            doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+          }
+        }
 #if H_3D_IC
         }
 #endif
       }
-
 #if H_3D_QTLPC      
       if(depthMapDetect && !bIntraSliceDetect && !rapPic && ( m_pcEncCfg->getUseQTL() || bLimQtPredFalg ))
@@ -702,5 +719,6 @@
       }
 #endif
-      if ( bIsLosslessMode )
+
+      if (bIsLosslessMode) // Restore loop variable if lossless mode was searched.
       {
         iQP = iMinQP;
@@ -733,5 +751,5 @@
       for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
       {
-        const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+        const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP); // If lossless, then iQP is irrelevant for subsequent modules.
 
         if (bIsLosslessMode)
@@ -739,4 +757,5 @@
           iQP = lowestQP;
         }
+
         rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
@@ -745,35 +764,37 @@
         {
           // 2Nx2N, NxN
-            if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
-            {
-              if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && doNotBlockPu
+
+          if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
+          {
+            if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() && doNotBlockPu
 #if H_3D_QTLPC
                 && bTrySplit
 #endif
-                )
-              {
+)
+            {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN, bFMD  );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
-#endif
-                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
+#endif
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-              }
+
             }
-
-          // 2NxN, Nx2N
+          }
+
           if(doNotBlockPu
 #if H_3D_QTLPC
             && bTryNx2N
 #endif
-            )
+)
           {
 #if  H_3D_FAST_TEXTURE_ENCODING
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N, bFMD  );
 #else
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N  );
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N DEBUG_STRING_PASS_INTO(sDebug)  );
 #endif
             rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
@@ -781,4 +802,5 @@
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
+
             if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
             {
@@ -790,15 +812,18 @@
             && bTry2NxN
 #endif
-            )
+)
           {
 #if  H_3D_FAST_TEXTURE_ENCODING
             xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN, bFMD  );
 #else
-            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN  );
-#endif
+
+            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN DEBUG_STRING_PASS_INTO(sDebug)  );
+#endif
+
             rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
+
             if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxN)
             {
@@ -807,9 +832,8 @@
           }
 
-#if 1
           //! Try AMP (SIZE_2NxnU, SIZE_2NxnD, SIZE_nLx2N, SIZE_nRx2N)
-          if( pcPic->getSlice(0)->getSPS()->getAMPAcc(uiDepth) )
+          if(sps.getUseAMP() && uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() )
           {
-#if AMP_ENC_SPEEDUP        
+#if AMP_ENC_SPEEDUP
             Bool bTestAMP_Hor = false, bTestAMP_Ver = false;
 
@@ -829,10 +853,10 @@
                 && bTry2NxN
 #endif
-                )
+)
               {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFMD );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU DEBUG_STRING_PASS_INTO(sDebug) );
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
@@ -849,15 +873,17 @@
                 && bTry2NxN
 #endif
-                )
+)
               {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFMD );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
-#endif
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD DEBUG_STRING_PASS_INTO(sDebug) );
+#endif
+
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
+
                 if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
                 {
@@ -867,5 +893,5 @@
             }
 #if AMP_MRG
-            else if ( bTestMergeAMP_Hor ) 
+            else if ( bTestMergeAMP_Hor )
             {
               if(doNotBlockPu
@@ -873,11 +899,13 @@
                 && bTry2NxN
 #endif
-                )
+)
               {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFMD, true );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, true );
-#endif
+
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU DEBUG_STRING_PASS_INTO(sDebug), true );
+#endif
+
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
@@ -893,10 +921,10 @@
                 && bTry2NxN
 #endif
-                )
+)
               {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFMD, true );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, true );
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD DEBUG_STRING_PASS_INTO(sDebug), true );
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
@@ -904,4 +932,5 @@
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
+
                 if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
                 {
@@ -919,11 +948,12 @@
                 && bTryNx2N
 #endif
-                )
+)
               {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFMD );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
-#endif
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N DEBUG_STRING_PASS_INTO(sDebug) );
+#endif
+
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
@@ -939,10 +969,10 @@
                 && bTryNx2N
 #endif
-                )
+)
               {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFMD );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N DEBUG_STRING_PASS_INTO(sDebug) );
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
@@ -959,10 +989,10 @@
                 && bTryNx2N
 #endif
-                )
+)
               {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFMD, true );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, true );
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N DEBUG_STRING_PASS_INTO(sDebug), true );
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
@@ -979,10 +1009,11 @@
                 && bTryNx2N
 #endif
-                )
+)
               {
 #if  H_3D_FAST_TEXTURE_ENCODING
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFMD, true );
 #else
-                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, true );
+
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N DEBUG_STRING_PASS_INTO(sDebug), true );
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
@@ -990,4 +1021,5 @@
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
+
               }
             }
@@ -999,11 +1031,12 @@
             {
 #endif
-              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
-              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
-              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -1014,11 +1047,11 @@
             {
 #endif
-              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
-              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
-              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
-              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D_VSP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -1028,7 +1061,7 @@
 #endif
 
-#endif
-          }    
-#endif
+
+#endif
+          }
         }
 #if  H_3D_FAST_TEXTURE_ENCODING
@@ -1036,16 +1069,20 @@
         {
 #endif
+
         // do normal intra modes
-       
-          // speedup for inter frames
-          if( rpcBestCU->getSlice()->getSliceType() == I_SLICE || 
-            rpcBestCU->getCbf( 0, TEXT_LUMA     ) != 0   ||
-            rpcBestCU->getCbf( 0, TEXT_CHROMA_U ) != 0   ||
-            rpcBestCU->getCbf( 0, TEXT_CHROMA_V ) != 0     
+        // speedup for inter frames
+        Double intraCost = 0.0;
+
+        if((rpcBestCU->getSlice()->getSliceType() == I_SLICE)                                     ||
+            ((!m_pcEncCfg->getDisableIntraPUsInInterSlices()) && (
+           (rpcBestCU->getCbf( 0, COMPONENT_Y  ) != 0)                                            ||
+          ((rpcBestCU->getCbf( 0, COMPONENT_Cb ) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
+          ((rpcBestCU->getCbf( 0, COMPONENT_Cr ) != 0) && (numberValidComponents > COMPONENT_Cr))) 
+ // avoid very complex intra if it is unlikely
 #if H_3D_DIM_ENC
             || rpcBestCU->getSlice()->getIsDepth()
 #endif
-            ) // avoid very complex intra if it is unlikely
-          {
+            ))
+        {
 #if H_3D_DIM
             Bool bOnlyIVP = false;
@@ -1065,7 +1102,6 @@
               xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bOnlyIVP );
 #else
-            xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
-#endif
-
+          xCheckRDCostIntra( rpcBestCU, rpcTempCU, intraCost, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
+#endif
 #if KWU_RC_MADPRED_E0227
             if ( uiDepth <= m_addSADDepth )
@@ -1076,41 +1112,46 @@
 #endif
 
-            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-            if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
-            {
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+          if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() )
+          {
 #if H_3D_QTLPC //Try IntraNxN
               if(bTrySplit)
               {
 #endif
-                if( rpcTempCU->getWidth(0) > ( 1 << rpcTempCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() ) )
-                {
+            if( rpcTempCU->getWidth(0) > ( 1 << sps.getQuadtreeTULog2MinSize() ) )
+            {
+              Double tmpIntraCost;
 #if H_3D_DIM
-                  xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN, bOnlyIVP );
-#else
-                  xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN   );
-#endif
-                  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-                }
+              xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN, bOnlyIVP );
+#else
+              xCheckRDCostIntra( rpcBestCU, rpcTempCU, tmpIntraCost, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
+#endif
+
+              intraCost = std::min(intraCost, tmpIntraCost);
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            }
 #if H_3D_QTLPC
               }
 #endif
-            }
+          }
 #if H_3D
           }
 #endif
         }
+
         // test PCM
-        if(pcPic->getSlice(0)->getSPS()->getUsePCM()
-          && rpcTempCU->getWidth(0) <= (1<<pcPic->getSlice(0)->getSPS()->getPCMLog2MaxSize())
-          && rpcTempCU->getWidth(0) >= (1<<pcPic->getSlice(0)->getSPS()->getPCMLog2MinSize()) )
+        if(sps.getUsePCM()
+          && rpcTempCU->getWidth(0) <= (1<<sps.getPCMLog2MaxSize())
+          && rpcTempCU->getWidth(0) >= (1<<sps.getPCMLog2MinSize()) )
         {
-          UInt uiRawBits = (2 * g_bitDepthY + g_bitDepthC) * rpcBestCU->getWidth(0) * rpcBestCU->getHeight(0) / 2;
+          UInt uiRawBits = getTotalBits(rpcBestCU->getWidth(0), rpcBestCU->getHeight(0), rpcBestCU->getPic()->getChromaFormat(), sps.getBitDepths().recon);
           UInt uiBestBits = rpcBestCU->getTotalBits();
-#if H_3D_VSO // M7
-          Double dRDCostTemp = m_pcRdCost->getUseVSO() ? m_pcRdCost->calcRdCostVSO(uiRawBits, 0) : m_pcRdCost->calcRdCost(uiRawBits, 0);
+#if NH_3D_VSO // M7
+          Double dRDCostTemp = m_pcRdCost->getUseLambdaScaleVSO() ? m_pcRdCost->calcRdCostVSO(uiRawBits, 0) : m_pcRdCost->calcRdCost(uiRawBits, 0);
           if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > dRDCostTemp ))
 #else
           if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > m_pcRdCost->calcRdCost(uiRawBits, 0)))
 #endif
+
           {
             xCheckIntraPCM (rpcBestCU, rpcTempCU);
@@ -1121,5 +1162,5 @@
         }
 #endif
-        if (bIsLosslessMode)
+        if (bIsLosslessMode) // Restore loop variable if lossless mode was searched.
         {
           iQP = iMinQP;
@@ -1128,14 +1169,18 @@
     }
 
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
     m_pcEntropyCoder->resetBits();
     m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
     rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
-      rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-    #if H_3D_VSO // M8
+    rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+#if NH_3D_VSO // M8
     if ( m_pcRdCost->getUseVSO() )    
+    {
       rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );    
+    }
     else
 #endif
-    rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
+      rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
 
     // Early CU determination
@@ -1155,5 +1200,5 @@
 #endif
   }
-  else if(!(bSliceEnd && bInsidePicture))
+  else
   {
     bBoundary = true;
@@ -1165,11 +1210,12 @@
     xFillPCMBuffer(rpcBestCU, m_ppcOrigYuv[uiDepth]);
   }
-  if( (g_uiMaxCUWidth>>uiDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+
+  if( uiDepth == pps.getMaxCuDQPDepth() )
   {
     Int idQP = m_pcEncCfg->getMaxDeltaQP();
-    iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
-    iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
-  }
-  else if( (g_uiMaxCUWidth>>uiDepth) > rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+    iMinQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP+idQP );
+  }
+  else if( uiDepth < pps.getMaxCuDQPDepth() )
   {
     iMinQP = iBaseQP;
@@ -1178,17 +1224,9 @@
   else
   {
-    Int iStartQP;
-    if( pcPic->getCU( rpcTempCU->getAddr() )->getSliceSegmentStartCU(rpcTempCU->getZorderIdxInCU()) == pcSlice->getSliceSegmentCurStartCUAddr())
-    {
-      iStartQP = rpcTempCU->getQP(0);
-    }
-    else
-    {
-      UInt uiCurSliceStartPartIdx = pcSlice->getSliceSegmentCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
-      iStartQP = rpcTempCU->getQP(uiCurSliceStartPartIdx);
-    }
+    const Int iStartQP = rpcTempCU->getQP(0);
     iMinQP = iStartQP;
     iMaxQP = iStartQP;
   }
+
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -1199,9 +1237,11 @@
   if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
   {
-    iMaxQP = iMinQP; // If all blocks are forced into using transquant bypass, do not loop here.
-  }
+    iMaxQP = iMinQP; // If all TUs are forced into using transquant bypass, do not loop here.
+  }
+
   for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
   {
     const Bool bIsLosslessMode = false; // False at this level. Next level down may set it to true.
+
     rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
@@ -1210,26 +1250,23 @@
     if( bSubBranch && bTrySplitDQP && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
 #else
-    if( bSubBranch && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
-#endif
-    {
-#if H_3D_VSO // M9
+    if( bSubBranch && uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() )
+#endif
+    {
+#if NH_3D_VSO // M9
       // reset Model
       if( m_pcRdCost->getUseRenModel() )
       {
-        UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth ( );
-        UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight( );
-        Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getLumaAddr( 0 );
-        UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride();
+        UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth ( COMPONENT_Y );
+        UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight( COMPONENT_Y );
+        Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getAddr  ( COMPONENT_Y, 0 );
+        UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride( COMPONENT_Y  );
         m_pcRdCost->setRenModelData( m_ppcBestCU[uiDepth], 0, piSrc, uiSrcStride, uiWidth, uiHeight );
       }
 #endif
-
       UChar       uhNextDepth         = uiDepth+1;
       TComDataCU* pcSubBestPartCU     = m_ppcBestCU[uhNextDepth];
       TComDataCU* pcSubTempPartCU     = m_ppcTempCU[uhNextDepth];
-
-#if H_3D_DISABLE_CHROMA
-      m_ppcWeightedTempCU[uhNextDepth]->setSlice( m_ppcWeightedTempCU[ uiDepth]->getSlice()); 
-#endif
+      DEBUG_STRING_NEW(sTempDebug)
+
       for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
       {
@@ -1237,25 +1274,27 @@
         pcSubTempPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
 
-        Bool bInSlice = pcSubBestPartCU->getSCUAddr()+pcSubBestPartCU->getTotalNumPart()>pcSlice->getSliceSegmentCurStartCUAddr()&&pcSubBestPartCU->getSCUAddr()<pcSlice->getSliceSegmentCurEndCUAddr();
-        if(bInSlice && ( pcSubBestPartCU->getCUPelX() < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+        if( ( pcSubBestPartCU->getCUPelX() < sps.getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < sps.getPicHeightInLumaSamples() ) )
         {
-            if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
-            {
-              m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-            }
-            else
-            {
-              m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
-            }
-
-#if AMP_ENC_SPEEDUP
-          if ( rpcBestCU->isIntra(0) )
+          if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
           {
-            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth, SIZE_NONE );
+            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
           }
           else
           {
-            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth, rpcBestCU->getPartitionSize(0) );
-          }
+            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+          }
+
+#if AMP_ENC_SPEEDUP
+          DEBUG_STRING_NEW(sChild)
+          if ( !rpcBestCU->isInter(0) )
+          {
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth DEBUG_STRING_PASS_INTO(sChild), NUMBER_OF_PART_SIZES );
+          }
+          else
+          {
+
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth DEBUG_STRING_PASS_INTO(sChild), rpcBestCU->getPartitionSize(0) );
+          }
+          DEBUG_STRING_APPEND(sTempDebug, sChild)
 #else
           xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth );
@@ -1265,5 +1304,5 @@
           xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
         }
-        else if (bInSlice)
+        else
         {
           pcSubBestPartCU->copyToPic( uhNextDepth );
@@ -1272,4 +1311,5 @@
       }
 
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
       if( !bBoundary )
       {
@@ -1278,20 +1318,23 @@
 
         rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
-          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-        }
-#if H_3D_VSO // M10
+        rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+      }
+#if NH_3D_VSO // M10
       if ( m_pcRdCost->getUseVSO() )
+      {
         rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+      }
       else
 #endif
-      rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
-
-      if( (g_uiMaxCUWidth>>uiDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() && rpcTempCU->getSlice()->getPPS()->getUseDQP())
+        rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+      if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
       {
         Bool hasResidual = false;
         for( UInt uiBlkIdx = 0; uiBlkIdx < rpcTempCU->getTotalNumPart(); uiBlkIdx ++)
         {
-          if( ( pcPic->getCU( rpcTempCU->getAddr() )->getSliceSegmentStartCU(uiBlkIdx+rpcTempCU->getZorderIdxInCU()) == rpcTempCU->getSlice()->getSliceSegmentCurStartCUAddr() ) && 
-              ( rpcTempCU->getCbf( uiBlkIdx, TEXT_LUMA ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_U ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_V ) ) )
+          if( (     rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Y)
+                || (rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Cb) && (numberValidComponents > COMPONENT_Cb))
+                || (rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Cr) && (numberValidComponents > COMPONENT_Cr)) ) )
           {
             hasResidual = true;
@@ -1300,30 +1343,22 @@
         }
 
-        UInt uiTargetPartIdx;
-        if ( pcPic->getCU( rpcTempCU->getAddr() )->getSliceSegmentStartCU(rpcTempCU->getZorderIdxInCU()) != pcSlice->getSliceSegmentCurStartCUAddr() )
-        {
-          uiTargetPartIdx = pcSlice->getSliceSegmentCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
-        }
-        else
-        {
-          uiTargetPartIdx = 0;
-        }
+        UInt uiTargetPartIdx = 0;
         if ( hasResidual )
         {
-#if !RDO_WITHOUT_DQP_BITS
           m_pcEntropyCoder->resetBits();
           m_pcEntropyCoder->encodeQP( rpcTempCU, uiTargetPartIdx, false );
           rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
-            rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-#if H_3D_VSO // M11
+          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+#if NH_3D_VSO // M11
           if ( m_pcRdCost->getUseLambdaScaleVSO())          
+          {
             rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );          
+          }
           else
 #endif
-          rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
-#endif
+            rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
 
           Bool foundNonZeroCbf = false;
-          rpcTempCU->setQPSubCUs( rpcTempCU->getRefQP( uiTargetPartIdx ), rpcTempCU, 0, uiDepth, foundNonZeroCbf );
+          rpcTempCU->setQPSubCUs( rpcTempCU->getRefQP( uiTargetPartIdx ), 0, uiDepth, foundNonZeroCbf );
           assert( foundNonZeroCbf );
         }
@@ -1334,31 +1369,45 @@
       }
 
-        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
-      Bool isEndOfSlice        = rpcBestCU->getSlice()->getSliceMode()==FIXED_NUMBER_OF_BYTES
-                                 && (rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getSliceArgument()<<3);
-      Bool isEndOfSliceSegment = rpcBestCU->getSlice()->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES
-                                 && (rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getSliceSegmentArgument()<<3);
+      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+      // If the configuration being tested exceeds the maximum number of bytes for a slice / slice-segment, then
+      // a proper RD evaluation cannot be performed. Therefore, termination of the
+      // slice/slice-segment must be made prior to this CTU.
+      // This can be achieved by forcing the decision to be that of the rpcTempCU.
+      // The exception is each slice / slice-segment must have at least one CTU.
+      const Bool isEndOfSlice        =    pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES
+                                       && ((pcSlice->getSliceBits()+rpcBestCU->getTotalBits())>pcSlice->getSliceArgument()<<3)
+                                       && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceCurStartCtuTsAddr())
+                                       && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceSegmentCurStartCtuTsAddr());
+      const Bool isEndOfSliceSegment =    pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES
+                                       && ((pcSlice->getSliceSegmentBits()+rpcBestCU->getTotalBits()) > pcSlice->getSliceSegmentArgument()<<3)
+                                       && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceSegmentCurStartCtuTsAddr());
+                                           // Do not need to check slice condition for slice-segment since a slice-segment is a subset of a slice.
       if(isEndOfSlice||isEndOfSliceSegment)
       {
-        rpcBestCU->getTotalCost()=rpcTempCU->getTotalCost()+1;
+        rpcBestCU->getTotalCost()=MAX_DOUBLE;
       }
-      xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth);                                  // RD compare current larger prediction
-    }                                                                                  // with sub partitioned prediction.
-    }
-
-#if H_3D_VSO // M12 
+
+      xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTempDebug) DEBUG_STRING_PASS_INTO(false) ); // RD compare current larger prediction
+                                                                                       // with sub partitioned prediction.
+    }
+  }
+#if NH_3D_VSO // M12 
   if( m_pcRdCost->getUseRenModel() )
   {
-    UInt  uiWidth     = m_ppcRecoYuvBest[uiDepth]->getWidth   ( );
-    UInt  uiHeight    = m_ppcRecoYuvBest[uiDepth]->getHeight  ( );
-    Pel*  piSrc       = m_ppcRecoYuvBest[uiDepth]->getLumaAddr( 0 );
-    UInt  uiSrcStride = m_ppcRecoYuvBest[uiDepth]->getStride  ( );
+    UInt  uiWidth     = m_ppcRecoYuvBest[uiDepth]->getWidth   ( COMPONENT_Y );
+    UInt  uiHeight    = m_ppcRecoYuvBest[uiDepth]->getHeight  ( COMPONENT_Y );
+    Pel*  piSrc       = m_ppcRecoYuvBest[uiDepth]->getAddr    ( COMPONENT_Y,  0 );
+    UInt  uiSrcStride = m_ppcRecoYuvBest[uiDepth]->getStride  ( COMPONENT_Y );
     m_pcRdCost->setRenModelData( rpcBestCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
   }
 #endif
+
+  DEBUG_STRING_APPEND(sDebug_, sDebug);
+
   rpcBestCU->copyToPic(uiDepth);                                                     // Copy Best data to Picture for next partition prediction.
 
-  xCopyYuv2Pic( rpcBestCU->getPic(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU(), uiDepth, uiDepth, rpcBestCU, uiLPelX, uiTPelY );   // Copy Yuv data to picture Yuv
-  if( bBoundary ||(bSliceEnd && bInsidePicture))
+  xCopyYuv2Pic( rpcBestCU->getPic(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu(), uiDepth, uiDepth );   // Copy Yuv data to picture Yuv
+  if (bBoundary)
   {
     return;
@@ -1367,7 +1416,7 @@
   // Assert if Best prediction mode is NONE
   // Selected mode's RD-cost must be not MAX_DOUBLE.
-  assert( rpcBestCU->getPartitionSize ( 0 ) != SIZE_NONE  );
-  assert( rpcBestCU->getPredictionMode( 0 ) != MODE_NONE  );
-  assert( rpcBestCU->getTotalCost     (   ) != MAX_DOUBLE );
+  assert( rpcBestCU->getPartitionSize ( 0 ) != NUMBER_OF_PART_SIZES       );
+  assert( rpcBestCU->getPredictionMode( 0 ) != NUMBER_OF_PREDICTION_MODES );
+  assert( rpcBestCU->getTotalCost     (   ) != MAX_DOUBLE                 );
 }
 
@@ -1375,8 +1424,8 @@
  * \param pcCU
  * \param uiAbsPartIdx
- * \param uiDepth 
+ * \param uiDepth
  * \returns Void
  */
-Void TEncCu::finishCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+Void TEncCu::finishCU( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
   TComPic* pcPic = pcCU->getPic();
@@ -1384,78 +1433,13 @@
 
   //Calculate end address
-  UInt uiCUAddr = pcCU->getSCUAddr()+uiAbsPartIdx;
-
-  UInt uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
-  UInt uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
-  UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-  UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
-  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
-  while(uiPosX>=uiWidth||uiPosY>=uiHeight)
-  {
-    uiInternalAddress--;
-    uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-    uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-  }
-  uiInternalAddress++;
-  if(uiInternalAddress==pcCU->getPic()->getNumPartInCU())
-  {
-    uiInternalAddress = 0;
-    uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
-  }
-  UInt uiRealEndAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
-
-  // Encode slice finish
-  Bool bTerminateSlice = false;
-  if (uiCUAddr+(pcCU->getPic()->getNumPartInCU()>>(uiDepth<<1)) == uiRealEndAddress)
-  {
-    bTerminateSlice = true;
-  }
-  UInt uiGranularityWidth = g_uiMaxCUWidth;
-  uiPosX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  uiPosY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  Bool granularityBoundary=((uiPosX+pcCU->getWidth(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosX+pcCU->getWidth(uiAbsPartIdx)==uiWidth))
-    &&((uiPosY+pcCU->getHeight(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosY+pcCU->getHeight(uiAbsPartIdx)==uiHeight));
-  
-  if(granularityBoundary)
+  const Int  currentCTUTsAddr = pcPic->getPicSym()->getCtuRsToTsAddrMap(pcCU->getCtuRsAddr());
+  const Bool isLastSubCUOfCtu = pcCU->isLastSubCUOfCtu(uiAbsPartIdx);
+  if ( isLastSubCUOfCtu )
   {
     // The 1-terminating bit is added to all streams, so don't add it here when it's 1.
-    if (!bTerminateSlice)
-      m_pcEntropyCoder->encodeTerminatingBit( bTerminateSlice ? 1 : 0 );
-  }
-  
-  Int numberOfWrittenBits = 0;
-  if (m_pcBitCounter)
-  {
-    numberOfWrittenBits = m_pcEntropyCoder->getNumberOfWrittenBits();
-  }
-  
-  // Calculate slice end IF this CU puts us over slice bit size.
-  UInt iGranularitySize = pcCU->getPic()->getNumPartInCU();
-  Int iGranularityEnd = ((pcCU->getSCUAddr()+uiAbsPartIdx)/iGranularitySize)*iGranularitySize;
-  if(iGranularityEnd<=pcSlice->getSliceSegmentCurStartCUAddr()) 
-  {
-    iGranularityEnd+=max(iGranularitySize,(pcCU->getPic()->getNumPartInCU()>>(uiDepth<<1)));
-  }
-  // Set slice end parameter
-  if(pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES&&!pcSlice->getFinalized()&&pcSlice->getSliceBits()+numberOfWrittenBits>pcSlice->getSliceArgument()<<3) 
-  {
-    pcSlice->setSliceSegmentCurEndCUAddr(iGranularityEnd);
-    pcSlice->setSliceCurEndCUAddr(iGranularityEnd);
-    return;
-  }
-  // Set dependent slice end parameter
-  if(pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES&&!pcSlice->getFinalized()&&pcSlice->getSliceSegmentBits()+numberOfWrittenBits > pcSlice->getSliceSegmentArgument()<<3) 
-  {
-    pcSlice->setSliceSegmentCurEndCUAddr(iGranularityEnd);
-    return;
-  }
-  if(granularityBoundary)
-  {
-    pcSlice->setSliceBits( (UInt)(pcSlice->getSliceBits() + numberOfWrittenBits) );
-    pcSlice->setSliceSegmentBits(pcSlice->getSliceSegmentBits()+numberOfWrittenBits);
-    if (m_pcBitCounter)
-    {
-      m_pcEntropyCoder->resetBits();      
+    // i.e. when the slice segment CurEnd CTU address is the current CTU address+1.
+    if (pcSlice->getSliceSegmentCurEndCtuTsAddr() != currentCTUTsAddr+1)
+    {
+      m_pcEntropyCoder->encodeTerminatingBit( 0 );
     }
   }
@@ -1488,5 +1472,6 @@
     iQpOffset = Int(floor( dQpOffset + 0.49999 ));
   }
-  return Clip3(-pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQp+iQpOffset );
+
+  return Clip3(-pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQp+iQpOffset );
 }
 
@@ -1494,31 +1479,32 @@
  * \param pcCU
  * \param uiAbsPartIdx
- * \param uiDepth 
+ * \param uiDepth
  * \returns Void
  */
 Void TEncCu::xEncodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
-  TComPic* pcPic = pcCU->getPic();
-  
-  Bool bBoundary = false;
-  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
-  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
-  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
-  
+        TComPic   *const pcPic   = pcCU->getPic();
+        TComSlice *const pcSlice = pcCU->getSlice();
+  const TComSPS   &sps =*(pcSlice->getSPS());
+  const TComPPS   &pps =*(pcSlice->getPPS());
+
+  const UInt maxCUWidth  = sps.getMaxCUWidth();
+  const UInt maxCUHeight = sps.getMaxCUHeight();
+
+        Bool bBoundary = false;
+        UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  const UInt uiRPelX   = uiLPelX + (maxCUWidth>>uiDepth)  - 1;
+        UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  const UInt uiBPelY   = uiTPelY + (maxCUHeight>>uiDepth) - 1;
+
 #if H_MV_ENC_DEC_TRAC
   DTRACE_CU_S("=========== coding_quadtree ===========\n")
   DTRACE_CU("x0", uiLPelX)
   DTRACE_CU("x1", uiTPelY)
-  DTRACE_CU("log2CbSize", g_uiMaxCUWidth>>uiDepth)
+  DTRACE_CU("log2CbSize", maxCUWidth>>uiDepth )
   DTRACE_CU("cqtDepth"  , uiDepth)
 #endif
 
-  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
-  // If slice start is within this cu...
-  Bool bSliceStart = pcSlice->getSliceSegmentCurStartCUAddr() > pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
-    pcSlice->getSliceSegmentCurStartCUAddr() < pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcPic->getNumPartInCU() >> (uiDepth<<1) );
-  // We need to split, so don't try these modes.
-  if(!bSliceStart&&( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  if( ( uiRPelX < sps.getPicWidthInLumaSamples() ) && ( uiBPelY < sps.getPicHeightInLumaSamples() ) )
   {
     m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
@@ -1528,18 +1514,23 @@
     bBoundary = true;
   }
-  
-  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
-  {
-    UInt uiQNumParts = ( pcPic->getNumPartInCU() >> (uiDepth<<1) )>>2;
-    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( pcPic->getNumPartitionsInCtu() >> (uiDepth<<1) )>>2;
+    if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
     {
       setdQPFlag(true);
     }
+
+    if( uiDepth == pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth() && pcSlice->getUseChromaQpAdj())
+    {
+      setCodeChromaQpAdjFlag(true);
+    }
+
     for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++, uiAbsPartIdx+=uiQNumParts )
     {
       uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
       uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
-      Bool bInSlice = pcCU->getSCUAddr()+uiAbsPartIdx+uiQNumParts>pcSlice->getSliceSegmentCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getSliceSegmentCurEndCUAddr();
-      if(bInSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      if( ( uiLPelX < sps.getPicWidthInLumaSamples() ) && ( uiTPelY < sps.getPicHeightInLumaSamples() ) )
       {
         xEncodeCU( pcCU, uiAbsPartIdx, uiDepth+1 );
@@ -1548,22 +1539,30 @@
     return;
   }
-  
+
 #if H_MV_ENC_DEC_TRAC
   DTRACE_CU_S("=========== coding_unit ===========\n")
 #endif
 
-  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+
+  if( uiDepth <= pps.getMaxCuDQPDepth() && pps.getUseDQP())
   {
     setdQPFlag(true);
   }
-  if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+
+  if( uiDepth <= pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth() && pcSlice->getUseChromaQpAdj())
+  {
+    setCodeChromaQpAdjFlag(true);
+  }
+
+  if (pps.getTransquantBypassEnableFlag())
   {
     m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
   }
-  if( !pcCU->getSlice()->isIntra() )
+
+  if( !pcSlice->isIntra() )
   {
     m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
   }
-  
+
   if( pcCU->isSkipped( uiAbsPartIdx ) )
   {
@@ -1573,4 +1572,5 @@
     DTRACE_PU("x1", uiTPelY)
 #endif
+
     m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx );
 #if H_3D_ARP
@@ -1580,7 +1580,9 @@
     m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
 #endif
-    finishCU(pcCU,uiAbsPartIdx,uiDepth);
+
+    finishCU(pcCU,uiAbsPartIdx);
     return;
   }
+
 #if H_3D
   m_pcEntropyCoder->encodeDIS( pcCU, uiAbsPartIdx );
@@ -1588,12 +1590,11 @@
   {
 #endif
-
   m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
-  
   m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
-  
+
   if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
   {
     m_pcEntropyCoder->encodeIPCMInfo( pcCU, uiAbsPartIdx );
+
     if(pcCU->getIPCMFlag(uiAbsPartIdx))
     {
@@ -1601,6 +1602,7 @@
       m_pcEntropyCoder->encodeSDCFlag( pcCU, uiAbsPartIdx, false );
 #endif  
+
       // Encode slice finish
-      finishCU(pcCU,uiAbsPartIdx,uiDepth);
+      finishCU(pcCU,uiAbsPartIdx);
       return;
     }
@@ -1621,20 +1623,21 @@
   m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
 #endif
+
   // Encode Coefficients
   Bool bCodeDQP = getdQPFlag();
-#if H_3D_DISABLE_CHROMA
-  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, pcCU->getWidth (uiAbsPartIdx), pcCU->getHeight(uiAbsPartIdx), bCodeDQP, false );
-#else
-  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, pcCU->getWidth (uiAbsPartIdx), pcCU->getHeight(uiAbsPartIdx), bCodeDQP );
-#endif
+  Bool codeChromaQpAdj = getCodeChromaQpAdjFlag();
+  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, codeChromaQpAdj );
+  setCodeChromaQpAdjFlag( codeChromaQpAdj );
   setdQPFlag( bCodeDQP );
 #if H_3D
   }
 #endif
+
+
   // --- write terminating bit ---
-  finishCU(pcCU,uiAbsPartIdx,uiDepth);
+  finishCU(pcCU,uiAbsPartIdx);
 }
 
-Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg) 
+Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg)
 {
   Int k, i, j, jj;
@@ -1651,8 +1654,8 @@
     diff[k+6] = piOrg[6] ;
     diff[k+7] = piOrg[7] ;
- 
+
     piOrg += iStrideOrg;
   }
-  
+
   //horizontal
   for (j=0; j < 8; j++)
@@ -1667,5 +1670,5 @@
     m2[j][6] = diff[jj+2] - diff[jj+6];
     m2[j][7] = diff[jj+3] - diff[jj+7];
-    
+
     m1[j][0] = m2[j][0] + m2[j][2];
     m1[j][1] = m2[j][1] + m2[j][3];
@@ -1676,5 +1679,5 @@
     m1[j][6] = m2[j][4] - m2[j][6];
     m1[j][7] = m2[j][5] - m2[j][7];
-    
+
     m2[j][0] = m1[j][0] + m1[j][1];
     m2[j][1] = m1[j][0] - m1[j][1];
@@ -1686,5 +1689,5 @@
     m2[j][7] = m1[j][6] - m1[j][7];
   }
-  
+
   //vertical
   for (i=0; i < 8; i++)
@@ -1698,5 +1701,5 @@
     m3[6][i] = m2[2][i] - m2[6][i];
     m3[7][i] = m2[3][i] - m2[7][i];
-    
+
     m1[0][i] = m3[0][i] + m3[2][i];
     m1[1][i] = m3[1][i] + m3[3][i];
@@ -1707,5 +1710,5 @@
     m1[6][i] = m3[4][i] - m3[6][i];
     m1[7][i] = m3[5][i] - m3[7][i];
-    
+
     m2[0][i] = m1[0][i] + m1[1][i];
     m2[1][i] = m1[0][i] - m1[1][i];
@@ -1717,5 +1720,5 @@
     m2[7][i] = m1[6][i] - m1[7][i];
   }
-  
+
   for (i = 0; i < 8; i++)
   {
@@ -1730,11 +1733,11 @@
 }
 
-Int  TEncCu::updateLCUDataISlice(TComDataCU* pcCU, Int LCUIdx, Int width, Int height)
+Int  TEncCu::updateCtuDataISlice(TComDataCU* pCtu, Int width, Int height)
 {
-  Int  xBl, yBl; 
+  Int  xBl, yBl;
   const Int iBlkSize = 8;
 
-  Pel* pOrgInit   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
-  Int  iStrideOrig = pcCU->getPic()->getPicYuvOrg()->getStride();
+  Pel* pOrgInit   = pCtu->getPic()->getPicYuvOrg()->getAddr(COMPONENT_Y, pCtu->getCtuRsAddr(), 0);
+  Int  iStrideOrig = pCtu->getPic()->getPicYuvOrg()->getStride(COMPONENT_Y);
   Pel  *pOrg;
 
@@ -1744,5 +1747,5 @@
     for ( xBl=0; (xBl+iBlkSize)<=width; xBl+= iBlkSize)
     {
-      pOrg = pOrgInit + iStrideOrig*yBl + xBl; 
+      pOrg = pOrgInit + iStrideOrig*yBl + xBl;
       iSumHad += xCalcHADs8x8_ISlice(pOrg, iStrideOrig);
     }
@@ -1754,7 +1757,7 @@
  * \param rpcBestCU
  * \param rpcTempCU
- * \returns Void
+ * \param earlyDetectionSkipMode
  */
-Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode )
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU DEBUG_STRING_FN_DECLARE(sDebug), Bool *earlyDetectionSkipMode )
 {
   assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
@@ -1777,11 +1780,11 @@
   Bool bICFlag = rpcTempCU->getICFlag( 0 );
 #endif
-#if H_3D_VSO // M1  //necessary here?
+#if NH_3D_VSO // M1  //necessary here?
   if( m_pcRdCost->getUseRenModel() )
   {
-    UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( );
-    UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( );
-    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
-    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+    UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( COMPONENT_Y );
+    UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( COMPONENT_Y );
+    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getAddr  ( COMPONENT_Y );
+    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride( COMPONENT_Y );
     m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
   }
@@ -1791,7 +1794,7 @@
   DisInfo cOrigDisInfo = rpcTempCU->getDvInfo(0);
 #else
-  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
-#endif
-
+#endif
+
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
 #if H_3D_VSP
 #if !H_3D_ARP
@@ -1820,5 +1823,4 @@
 #endif
 #endif
-
 #if H_3D_IV_MERGE
   Int mergeCandBuffer[MRG_MAX_NUM_CANDS_MEM];
@@ -1829,6 +1831,7 @@
 for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
 #else
-for( UInt ui = 0; ui < numValidMergeCand; ++ui )
-#endif
+  for( UInt ui = 0; ui < numValidMergeCand; ++ui )
+#endif
+
   {
     mergeCandBuffer[ui] = 0;
@@ -1842,8 +1845,9 @@
     iteration = 1;
   }
-  else 
+  else
   {
     iteration = 2;
   }
+  DEBUG_STRING_NEW(bestStr)
 
 #if H_3D_ARP
@@ -1900,5 +1904,5 @@
   {
     for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
-    {      
+    {
 #if H_3D_IC
       if( rpcTempCU->getSlice()->getApplyIC() && rpcTempCU->getSlice()->getIcSkipParseFlag() )
@@ -1910,12 +1914,12 @@
       }
 #endif
+
       if(!(uiNoResidual==1 && mergeCandBuffer[uiMergeCand]==1))
       {
         if( !(bestIsSkip && uiNoResidual == 0) )
         {
+          DEBUG_STRING_NEW(tmpStr)
           // set MC parameters
-          rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to LCU level
-          rpcTempCU->setCUTransquantBypassSubParts( bTransquantBypassFlag,     0, uhDepth );
-          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to CTU level
 #if H_3D_IC
           rpcTempCU->setICFlagSubParts( bICFlag, 0, 0, uhDepth );
@@ -1924,6 +1928,9 @@
           rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
 #endif
-          rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to LCU level
-          rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setCUTransquantBypassSubParts( bTransquantBypassFlag, 0, uhDepth );
+          rpcTempCU->setChromaQpAdjSubParts( bTransquantBypassFlag ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uhDepth );
+          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
+          rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to CTU level
+          rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to CTU level
 #if H_3D_VSP
           rpcTempCU->setVSPFlagSubParts( vspFlag[uiMergeCand], 0, 0, uhDepth );
@@ -1979,7 +1986,7 @@
             {
 #endif
-              rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to LCU level
-              rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
-              rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+          rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to CTU level
+          rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+          rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
 #if H_3D_VSP
             }
@@ -1989,30 +1996,31 @@
           m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
           // estimate residual and encode everything
-#if H_3D_VSO //M2
+#if NH_3D_VSO //M2
           if( m_pcRdCost->getUseRenModel() )
           { //Reset
-            UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth    ();
-            UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight   ();
-            Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr ();
-            UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride   ();
+            UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth    ( COMPONENT_Y );
+            UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight   ( COMPONENT_Y );
+            Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getAddr     ( COMPONENT_Y );
+            UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride   ( COMPONENT_Y );
             m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
           }
 #endif
           m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
-            m_ppcOrigYuv    [uhDepth],
-            m_ppcPredYuvTemp[uhDepth],
-            m_ppcResiYuvTemp[uhDepth],
-            m_ppcResiYuvBest[uhDepth],
-            m_ppcRecoYuvTemp[uhDepth],
-            (uiNoResidual? true:false));
-
-
-          if ( uiNoResidual == 0 && rpcTempCU->getQtRootCbf(0) == 0 )
+                                                     m_ppcOrigYuv    [uhDepth],
+                                                     m_ppcPredYuvTemp[uhDepth],
+                                                     m_ppcResiYuvTemp[uhDepth],
+                                                     m_ppcResiYuvBest[uhDepth],
+                                                     m_ppcRecoYuvTemp[uhDepth],
+                                                     (uiNoResidual != 0) DEBUG_STRING_PASS_INTO(tmpStr) );
+
+#if DEBUG_STRING
+          DebugInterPredResiReco(tmpStr, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
+#endif
+
+          if ((uiNoResidual == 0) && (rpcTempCU->getQtRootCbf(0) == 0))
           {
             // If no residual when allowing for one, then set mark to not try case where residual is forced to 0
             mergeCandBuffer[uiMergeCand] = 1;
           }
-
-          rpcTempCU->setSkipFlagSubParts( rpcTempCU->getQtRootCbf(0) == 0, 0, uhDepth );
 #if H_3D
           rpcTempCU->setDISFlagSubParts( false, 0, uhDepth );
@@ -2029,5 +2037,5 @@
           Int orgQP = rpcTempCU->getQP( 0 );
           xCheckDQP( rpcTempCU );
-          xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+          xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(bestStr) DEBUG_STRING_PASS_INTO(tmpStr));
 #if H_3D_INTER_SDC
           if( rpcTempCU->getSlice()->getInterSdcFlag() && !uiNoResidual )
@@ -2062,11 +2070,11 @@
               rpcTempCU->setTrIdxSubParts( 0, 0, uhDepth );
               rpcTempCU->setCbfSubParts( 1, 1, 1, 0, uhDepth );
-#if H_3D_VSO //M2
+#if NH_3D_VSO //M2
               if( m_pcRdCost->getUseRenModel() )
               { //Reset
-                UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth    ();
-                UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight   ();
-                Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr ();
-                UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride   ();
+                UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth    ( COMPONENT_Y );
+                UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight   ( COMPONENT_Y );
+                Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getAddr     ( COMPONENT_Y );
+                UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride   ( COMPONENT_Y );
                 m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
               }
@@ -2098,4 +2106,5 @@
           }
 #endif
+
           rpcTempCU->initEstData( uhDepth, orgQP, bTransquantBypassFlag );
 
@@ -2110,5 +2119,5 @@
             {
 #endif
-              bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
+            bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
 #if H_3D_INTER_SDC
             }
@@ -2127,5 +2136,5 @@
           *earlyDetectionSkipMode = true;
         }
-        else
+        else if(m_pcEncCfg->getFastSearch() != SELECTIVE)
         {
           Int absoulte_MV=0;
@@ -2149,4 +2158,5 @@
     }
   }
+  DEBUG_STRING_APPEND(sDebug, bestStr)
 #if H_3D_SPIVMP
  delete[] pcMvFieldSP;
@@ -2156,4 +2166,5 @@
  }
 #endif
+
 }
 
@@ -2163,5 +2174,5 @@
 Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bFMD, Bool bUseMRG)
 #else
-Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG)
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseMRG)
 #endif
 #else
@@ -2169,4 +2180,7 @@
 #endif
 {
+  DEBUG_STRING_NEW(sTest)
+
+  // prior to this, rpcTempCU will have just been reset using rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #if H_3D
   const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
@@ -2176,5 +2190,5 @@
   {
 #endif
-    UChar uhDepth = rpcTempCU->getDepth( 0 );
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
 #if H_3D_ARP
     Bool bFirstTime = true;
@@ -2192,23 +2206,20 @@
       }
 #endif
-#if H_3D_VSO // M3
+#if NH_3D_VSO // M3
       if( m_pcRdCost->getUseRenModel() )
       {
-        UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( );
-        UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( );
-        Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
-        UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+        UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( COMPONENT_Y );
+        UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( COMPONENT_Y );
+        Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getAddr  ( COMPONENT_Y );
+        UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride( COMPONENT_Y );
         m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
       }
 #endif
-
-      rpcTempCU->setDepthSubParts( uhDepth, 0 );
-
-      rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
 #if H_3D
       rpcTempCU->setDISFlagSubParts( false, 0, uhDepth );
 #endif
-      rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
-      rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+  rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
+  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uhDepth );
 #if H_3D_ARP
       rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
@@ -2227,12 +2238,13 @@
 #endif
 #if AMP_MRG
-        rpcTempCU->setMergeAMP (true);
+  rpcTempCU->setMergeAMP (true);
 #if  H_3D_FAST_TEXTURE_ENCODING
         m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], bFMD, false, bUseMRG );
 #else
-        m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], false, bUseMRG );
-#endif
-#else  
-        m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] DEBUG_STRING_PASS_INTO(sTest), false, bUseMRG );
+#endif
+
+#else
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
 #endif
 #if H_3D_ARP
@@ -2245,6 +2257,6 @@
 
 #if AMP_MRG
-      if ( !rpcTempCU->getMergeAMP() )
-      {
+  if ( !rpcTempCU->getMergeAMP() )
+  {
 #if H_3D_ARP
         if( nARPWMax )
@@ -2254,8 +2266,7 @@
         else
 #endif
-          return;
-      }
-#endif
-
+    return;
+  }
+#endif
 #if KWU_RC_MADPRED_E0227
       if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
@@ -2267,5 +2278,6 @@
       }
 #endif
-      m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
+
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false DEBUG_STRING_PASS_INTO(sTest) );
 #if H_3D_VSP // possible bug fix
       if( rpcTempCU->getQtRootCbf(0)==0 )
@@ -2274,15 +2286,22 @@
       }
 #endif
-#if H_3D_VSO // M4
-      if( m_pcRdCost->getUseLambdaScaleVSO() )
-        rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
-      else
-#endif
-        rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+#if NH_3D_VSO // M4
+  if( m_pcRdCost->getUseLambdaScaleVSO() )
+  {
+    rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  }
+  else            
+#endif
+    rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+#if DEBUG_STRING
+  DebugInterPredResiReco(sTest, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
+#endif
 #if H_3D_INTER_SDC
       TComDataCU *rpcTempCUPre = rpcTempCU;
 #endif
-      xCheckDQP( rpcTempCU );
-      xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
 #if H_3D_INTER_SDC
       if( rpcTempCU->getSlice()->getInterSdcFlag() && ePartSize == SIZE_2Nx2N)
@@ -2319,11 +2338,11 @@
           rpcTempCU->setTrIdxSubParts( 0, 0, uhDepth );
           rpcTempCU->setCbfSubParts( 1, 1, 1, 0, uhDepth );
-#if H_3D_VSO // M3
+#if NH_3D_VSO // M3
           if( m_pcRdCost->getUseRenModel() )
           {
-            UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( );
-            UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( );
-            Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
-            UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+            UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( COMPONENT_Y );
+            UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( COMPONENT_Y  );
+            Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getAddr  ( COMPONENT_Y  );
+            UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride( COMPONENT_Y  );
             m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
           }
@@ -2433,11 +2452,11 @@
   }
 
-#if H_3D_VSO // M5
+#if NH_3D_VSO // M5
   if( m_pcRdCost->getUseRenModel() )
   {
-    UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth   ();
-    UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight  ();
-    Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getLumaAddr();
-    UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride  ();
+    UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth   ( COMPONENT_Y );
+    UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight  ( COMPONENT_Y );
+    Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getAddr    ( COMPONENT_Y );
+    UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride  ( COMPONENT_Y );
     m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
   }
@@ -2485,7 +2504,9 @@
 
 
-#if H_3D_VSO // M6
-  if( m_pcRdCost->getUseLambdaScaleVSO())  
+#if NH_3D_VSO // M6
+  if( m_pcRdCost->getUseLambdaScaleVSO())
+  {
     rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );  
+  }
   else
 #endif
@@ -2503,11 +2524,11 @@
   UChar uhDepth = rpcTempCU->getDepth( 0 );
   
-#if H_3D_VSO
+#if NH_3D_VSO
   if( m_pcRdCost->getUseRenModel() )
   {
-    UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( );
-    UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( );
-    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
-    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+    UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( COMPONENT_Y );
+    UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( COMPONENT_Y );
+    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getAddr  ( COMPONENT_Y );
+    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride( COMPONENT_Y );
     m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
   }
@@ -2636,15 +2657,21 @@
 Void TEncCu::xCheckRDCostIntra( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize, Bool bOnlyIVP )
 #else
-Void TEncCu::xCheckRDCostIntra( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize )
+Void TEncCu::xCheckRDCostIntra( TComDataCU *&rpcBestCU,
+                                TComDataCU *&rpcTempCU,
+                                Double      &cost,
+                                PartSize     eSize
+                                DEBUG_STRING_FN_DECLARE(sDebug) )
 #endif
 {
-  UInt uiDepth = rpcTempCU->getDepth( 0 );  
-#if H_3D_VSO // M5
+  DEBUG_STRING_NEW(sTest)
+
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+#if NH_3D_VSO // M5
   if( m_pcRdCost->getUseRenModel() )
   {
-    UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth   ();
-    UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight  ();
-    Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getLumaAddr();
-    UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride  ();
+    UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth   ( COMPONENT_Y );
+    UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight  ( COMPONENT_Y );
+    Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getAddr    ( COMPONENT_Y );
+    UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride  ( COMPONENT_Y );
     m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
   }
@@ -2655,31 +2682,34 @@
   rpcTempCU->setDISFlagSubParts( false, 0, uiDepth );
 #endif
+
+
   rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
   rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
-  
-  Bool bSeparateLumaChroma = true; // choose estimation mode
-  UInt uiPreCalcDistC      = 0;
-  if( !bSeparateLumaChroma )
-  {
-    m_pcPredSearch->preestChromaPredMode( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth] );
-  }
+  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uiDepth );
+
+  Pel resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
+
+  m_pcPredSearch->estIntraPredLumaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], resiLuma DEBUG_STRING_PASS_INTO(sTest) );
+
+  m_ppcRecoYuvTemp[uiDepth]->copyToPicComponent(COMPONENT_Y, rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getCtuRsAddr(), rpcTempCU->getZorderIdxInCtu() );
+
+  if (rpcBestCU->getPic()->getChromaFormat()!=CHROMA_400)
+  {
 #if H_3D_DIM
-  m_pcPredSearch  ->estIntraPredQT      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, bSeparateLumaChroma, bOnlyIVP );
-#else
-  m_pcPredSearch  ->estIntraPredQT      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, bSeparateLumaChroma );
-#endif
-  m_ppcRecoYuvTemp[uiDepth]->copyToPicLuma(rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getAddr(), rpcTempCU->getZorderIdxInCU() );
-  
+    m_pcPredSearch->estIntraPredQT      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, bSeparateLumaChroma, bOnlyIVP );
+#else
+    m_pcPredSearch->estIntraPredChromaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], resiLuma DEBUG_STRING_PASS_INTO(sTest) );
+#endif
+  }
 #if H_3D_DIM_SDC
   if( !rpcTempCU->getSDCFlag( 0 ) )
 #endif
-    m_pcPredSearch  ->estIntraPredChromaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC );
-  
+
   m_pcEntropyCoder->resetBits();
+
   if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
   {
     m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
   }
-  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
 #if H_3D
   m_pcEntropyCoder->encodeDIS( rpcTempCU, 0,          true );
@@ -2687,43 +2717,48 @@
   {
 #endif
-    m_pcEntropyCoder->encodePredMode( rpcTempCU, 0,          true );
-    m_pcEntropyCoder->encodePartSize( rpcTempCU, 0, uiDepth, true );
-    m_pcEntropyCoder->encodePredInfo( rpcTempCU, 0,          true );
-    m_pcEntropyCoder->encodeIPCMInfo(rpcTempCU, 0, true );
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePredMode( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize( rpcTempCU, 0, uiDepth, true );
+  m_pcEntropyCoder->encodePredInfo( rpcTempCU, 0 );
+  m_pcEntropyCoder->encodeIPCMInfo(rpcTempCU, 0, true );
 #if H_3D_DIM_SDC
     m_pcEntropyCoder->encodeSDCFlag( rpcTempCU, 0, true );
 #endif
 
-    // Encode Coefficients
-    Bool bCodeDQP = getdQPFlag();
-#if H_3D_DISABLE_CHROMA
-    m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, rpcTempCU->getWidth (0), rpcTempCU->getHeight(0), bCodeDQP, true );
-#else
-    m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, rpcTempCU->getWidth (0), rpcTempCU->getHeight(0), bCodeDQP );
-#endif
-    setdQPFlag( bCodeDQP );
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  Bool codeChromaQpAdjFlag = getCodeChromaQpAdjFlag();
+  m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, bCodeDQP, codeChromaQpAdjFlag );
+  setCodeChromaQpAdjFlag( codeChromaQpAdjFlag );
+  setdQPFlag( bCodeDQP );
 #if H_3D
   }
 #endif
   m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
-  
+
   rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
   rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-#if H_3D_VSO // M6
+#if NH_3D_VSO // M6
   if( m_pcRdCost->getUseLambdaScaleVSO())  
+  {
     rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );  
+  }
   else
 #endif
-  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
-  
+    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
   xCheckDQP( rpcTempCU );
-  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth);
+
+  cost = rpcTempCU->getTotalCost();
+
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
 }
 
-/** Check R-D costs for a CU with PCM mode. 
+
+/** Check R-D costs for a CU with PCM mode.
  * \param rpcBestCU pointer to best mode CU data structure
  * \param rpcTempCU pointer to testing mode CU data structure
  * \returns Void
- * 
+ *
  * \note Current PCM implementation encodes sample values in a lossless way. The distortion of PCM mode CUs are zero. PCM mode is selected if the best mode yields bits greater than that of PCM mode.
  */
@@ -2732,4 +2767,15 @@
   UInt uiDepth = rpcTempCU->getDepth( 0 );
 
+#if NH_3D_VSO // VERY NEW
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth   ( COMPONENT_Y );
+    UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight  ( COMPONENT_Y );
+    Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getAddr    ( COMPONENT_Y );
+    UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride  ( COMPONENT_Y );
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
   rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
 #if H_3D
@@ -2741,4 +2787,5 @@
   rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
   rpcTempCU->setTrIdxSubParts ( 0, 0, uiDepth );
+  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uiDepth );
 
   m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
@@ -2747,8 +2794,10 @@
 
   m_pcEntropyCoder->resetBits();
+
   if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
   {
     m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
   }
+
   m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
 #if H_3D
@@ -2764,14 +2813,18 @@
 
   rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
-    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-#if H_3D_VSO // M44
+  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+#if NH_3D_VSO // M44
   if ( m_pcRdCost->getUseVSO() )
+  {
     rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  }
   else
 #endif
-  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
 
   xCheckDQP( rpcTempCU );
-  xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth );
+  DEBUG_STRING_NEW(a)
+  DEBUG_STRING_NEW(b)
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(a) DEBUG_STRING_PASS_INTO(b));
 }
 
@@ -2779,7 +2832,7 @@
  * \param rpcBestCU
  * \param rpcTempCU
- * \returns Void
+ * \param uiDepth
  */
-Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth DEBUG_STRING_FN_DECLARE(sParent) DEBUG_STRING_FN_DECLARE(sTest) DEBUG_STRING_PASS_INTO(Bool bAddSizeInfo) )
 {
   if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
@@ -2805,5 +2858,17 @@
 
     // store temp best CI for next CU coding
-      m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
+    m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
+
+
+#if DEBUG_STRING
+    DEBUG_STRING_SWAP(sParent, sTest)
+    const PredMode predMode=rpcBestCU->getPredictionMode(0);
+    if ((DebugOptionList::DebugString_Structure.getInt()&DebugStringGetPredModeMask(predMode)) && bAddSizeInfo)
+    {
+      std::stringstream ss(stringstream::out);
+      ss <<"###: " << (predMode==MODE_INTRA?"Intra   ":"Inter   ") << partSizeToString[rpcBestCU->getPartitionSize(0)] << " CU at " << rpcBestCU->getCUPelX() << ", " << rpcBestCU->getCUPelY() << " width=" << UInt(rpcBestCU->getWidth(0)) << std::endl;
+      sParent+=ss.str();
+    }
+#endif
   }
 }
@@ -2813,20 +2878,21 @@
   UInt uiDepth = pcCU->getDepth( 0 );
 
-  if( pcCU->getSlice()->getPPS()->getUseDQP() && (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() )
-  {
-    if ( pcCU->getCbf( 0, TEXT_LUMA, 0 ) || pcCU->getCbf( 0, TEXT_CHROMA_U, 0 ) || pcCU->getCbf( 0, TEXT_CHROMA_V, 0 ) )
-    {
-#if !RDO_WITHOUT_DQP_BITS
+  const TComPPS &pps = *(pcCU->getSlice()->getPPS());
+  if ( pps.getUseDQP() && uiDepth <= pps.getMaxCuDQPDepth() )
+  {
+    if ( pcCU->getQtRootCbf( 0) )
+    {
       m_pcEntropyCoder->resetBits();
       m_pcEntropyCoder->encodeQP( pcCU, 0, false );
       pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
-        pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-#if H_3D_VSO // M45
+      pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+#if NH_3D_VSO // M45
       if ( m_pcRdCost->getUseVSO() )      
+      {
         pcCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( pcCU->getTotalBits(), pcCU->getTotalDistortion() );      
+      }
       else
 #endif
-      pcCU->getTotalCost() = m_pcRdCost->calcRdCost( pcCU->getTotalBits(), pcCU->getTotalDistortion() );
-#endif
+        pcCU->getTotalCost() = m_pcRdCost->calcRdCost( pcCU->getTotalBits(), pcCU->getTotalDistortion() );
     }
     else
@@ -2845,40 +2911,15 @@
   }
 }
-Void TEncCu::xCopyYuv2Pic(TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth, TComDataCU* pcCU, UInt uiLPelX, UInt uiTPelY )
+Void TEncCu::xCopyYuv2Pic(TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth )
 {
-  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
-  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
-  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
-  Bool bSliceStart = pcSlice->getSliceSegmentCurStartCUAddr() > rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
-    pcSlice->getSliceSegmentCurStartCUAddr() < rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) );
-  Bool bSliceEnd   = pcSlice->getSliceSegmentCurEndCUAddr() > rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
-    pcSlice->getSliceSegmentCurEndCUAddr() < rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) );
-  if(!bSliceEnd && !bSliceStart && ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
-  {
-    UInt uiAbsPartIdxInRaster = g_auiZscanToRaster[uiAbsPartIdx];
-    UInt uiSrcBlkWidth = rpcPic->getNumPartInWidth() >> (uiSrcDepth);
-    UInt uiBlkWidth    = rpcPic->getNumPartInWidth() >> (uiDepth);
-    UInt uiPartIdxX = ( ( uiAbsPartIdxInRaster % rpcPic->getNumPartInWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
-    UInt uiPartIdxY = ( ( uiAbsPartIdxInRaster / rpcPic->getNumPartInWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
-    UInt uiPartIdx = uiPartIdxY * ( uiSrcBlkWidth / uiBlkWidth ) + uiPartIdxX;
-    m_ppcRecoYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
-  }
-  else
-  {
-    UInt uiQNumParts = ( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) )>>2;
-
-    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++, uiAbsPartIdx+=uiQNumParts )
-    {
-      UInt uiSubCULPelX   = uiLPelX + ( g_uiMaxCUWidth >>(uiDepth+1) )*( uiPartUnitIdx &  1 );
-      UInt uiSubCUTPelY   = uiTPelY + ( g_uiMaxCUHeight>>(uiDepth+1) )*( uiPartUnitIdx >> 1 );
-
-      Bool bInSlice = rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+uiQNumParts > pcSlice->getSliceSegmentCurStartCUAddr() && 
-        rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx < pcSlice->getSliceSegmentCurEndCUAddr();
-      if(bInSlice&&( uiSubCULPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiSubCUTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
-      {
-        xCopyYuv2Pic( rpcPic, uiCUAddr, uiAbsPartIdx, uiDepth+1, uiSrcDepth, pcCU, uiSubCULPelX, uiSubCUTPelY );   // Copy Yuv data to picture Yuv
-      }
-    }
-  }
+  UInt uiAbsPartIdxInRaster = g_auiZscanToRaster[uiAbsPartIdx];
+  UInt uiSrcBlkWidth = rpcPic->getNumPartInCtuWidth() >> (uiSrcDepth);
+  UInt uiBlkWidth    = rpcPic->getNumPartInCtuWidth() >> (uiDepth);
+  UInt uiPartIdxX = ( ( uiAbsPartIdxInRaster % rpcPic->getNumPartInCtuWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
+  UInt uiPartIdxY = ( ( uiAbsPartIdxInRaster / rpcPic->getNumPartInCtuWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
+  UInt uiPartIdx = uiPartIdxY * ( uiSrcBlkWidth / uiBlkWidth ) + uiPartIdxX;
+  m_ppcRecoYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
+
+  m_ppcPredYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvPred (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
 }
 
@@ -2887,52 +2928,37 @@
   UInt uiCurrDepth = uiNextDepth - 1;
   m_ppcRecoYuvBest[uiNextDepth]->copyToPartYuv( m_ppcRecoYuvTemp[uiCurrDepth], uiPartUnitIdx );
+  m_ppcPredYuvBest[uiNextDepth]->copyToPartYuv( m_ppcPredYuvBest[uiCurrDepth], uiPartUnitIdx);
 }
 
-/** Function for filling the PCM buffer of a CU using its original sample array 
- * \param pcCU pointer to current CU
- * \param pcOrgYuv pointer to original sample array
- * \returns Void
+/** Function for filling the PCM buffer of a CU using its original sample array
+ * \param pCU pointer to current CU
+ * \param pOrgYuv pointer to original sample array
  */
-Void TEncCu::xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv )
+Void TEncCu::xFillPCMBuffer     ( TComDataCU* pCU, TComYuv* pOrgYuv )
 {
-
-  UInt   width        = pCU->getWidth(0);
-  UInt   height       = pCU->getHeight(0);
-
-  Pel*   pSrcY = pOrgYuv->getLumaAddr(0, width); 
-  Pel*   pDstY = pCU->getPCMSampleY();
-  UInt   srcStride = pOrgYuv->getStride();
-
-  for(Int y = 0; y < height; y++ )
-  {
-    for(Int x = 0; x < width; x++ )
-    {
-      pDstY[x] = pSrcY[x];
-    }
-    pDstY += width;
-    pSrcY += srcStride;
-  }
-
-  Pel* pSrcCb       = pOrgYuv->getCbAddr();
-  Pel* pSrcCr       = pOrgYuv->getCrAddr();;
-
-  Pel* pDstCb       = pCU->getPCMSampleCb();
-  Pel* pDstCr       = pCU->getPCMSampleCr();;
-
-  UInt srcStrideC = pOrgYuv->getCStride();
-  UInt heightC   = height >> 1;
-  UInt widthC    = width  >> 1;
-
-  for(Int y = 0; y < heightC; y++ )
-  {
-    for(Int x = 0; x < widthC; x++ )
-    {
-      pDstCb[x] = pSrcCb[x];
-      pDstCr[x] = pSrcCr[x];
-    }
-    pDstCb += widthC;
-    pDstCr += widthC;
-    pSrcCb += srcStrideC;
-    pSrcCr += srcStrideC;
+  const ChromaFormat format = pCU->getPic()->getChromaFormat();
+  const UInt numberValidComponents = getNumberValidComponents(format);
+  for (UInt componentIndex = 0; componentIndex < numberValidComponents; componentIndex++)
+  {
+    const ComponentID component = ComponentID(componentIndex);
+
+    const UInt width  = pCU->getWidth(0)  >> getComponentScaleX(component, format);
+    const UInt height = pCU->getHeight(0) >> getComponentScaleY(component, format);
+
+    Pel *source      = pOrgYuv->getAddr(component, 0, width);
+    Pel *destination = pCU->getPCMSample(component);
+
+    const UInt sourceStride = pOrgYuv->getStride(component);
+
+    for (Int line = 0; line < height; line++)
+    {
+      for (Int column = 0; column < width; column++)
+      {
+        destination[column] = source[column];
+      }
+
+      source      += sourceStride;
+      destination += width;
+    }
   }
 }
@@ -2941,10 +2967,10 @@
 /** Collect ARL statistics from one block
   */
-Int TEncCu::xTuCollectARLStats(TCoeff* rpcCoeff, Int* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples )
+Int TEncCu::xTuCollectARLStats(TCoeff* rpcCoeff, TCoeff* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples )
 {
   for( Int n = 0; n < NumCoeffInCU; n++ )
   {
-    Int u = abs( rpcCoeff[ n ] );
-    Int absc = rpcArlCoeff[ n ];
+    TCoeff u = abs( rpcCoeff[ n ] );
+    TCoeff absc = rpcArlCoeff[ n ];
 
     if( u != 0 )
@@ -2955,5 +2981,5 @@
         numSamples[ u ]++;
       }
-      else 
+      else
       {
         cSum[ LEVEL_RANGE ] += ( Double )absc - ( Double )( u << ARL_C_PRECISION );
@@ -2966,17 +2992,16 @@
 }
 
-/** Collect ARL statistics from one LCU
- * \param pcCU
- */
-Void TEncCu::xLcuCollectARLStats(TComDataCU* rpcCU )
+//! Collect ARL statistics from one CTU
+Void TEncCu::xCtuCollectARLStats(TComDataCU* pCtu )
 {
-  Double cSum[ LEVEL_RANGE + 1 ];     //: the sum of DCT coefficients corresponding to datatype and quantization output
-  UInt numSamples[ LEVEL_RANGE + 1 ]; //: the number of coefficients corresponding to datatype and quantization output
-
-  TCoeff* pCoeffY = rpcCU->getCoeffY();
-  Int* pArlCoeffY = rpcCU->getArlCoeffY();
-
-  UInt uiMinCUWidth = g_uiMaxCUWidth >> g_uiMaxCUDepth;
-  UInt uiMinNumCoeffInCU = 1 << uiMinCUWidth;
+  Double cSum[ LEVEL_RANGE + 1 ];     //: the sum of DCT coefficients corresponding to data type and quantization output
+  UInt numSamples[ LEVEL_RANGE + 1 ]; //: the number of coefficients corresponding to data type and quantization output
+
+  TCoeff* pCoeffY = pCtu->getCoeff(COMPONENT_Y);
+  TCoeff* pArlCoeffY = pCtu->getArlCoeff(COMPONENT_Y);
+  const TComSPS &sps = *(pCtu->getSlice()->getSPS());
+
+  const UInt uiMinCUWidth = sps.getMaxCUWidth() >> sps.getMaxTotalCUDepth(); // NOTE: ed - this is not the minimum CU width. It is the square-root of the number of coefficients per part.
+  const UInt uiMinNumCoeffInCU = 1 << uiMinCUWidth;                          // NOTE: ed - what is this?
 
   memset( cSum, 0, sizeof( Double )*(LEVEL_RANGE+1) );
@@ -2984,14 +3009,13 @@
 
   // Collect stats to cSum[][] and numSamples[][]
-  for(Int i = 0; i < rpcCU->getTotalNumPart(); i ++ )
-  {
-    UInt uiTrIdx = rpcCU->getTransformIdx(i);
-
-    if(rpcCU->getPredictionMode(i) == MODE_INTER)
-    if( rpcCU->getCbf( i, TEXT_LUMA, uiTrIdx ) )
+  for(Int i = 0; i < pCtu->getTotalNumPart(); i ++ )
+  {
+    UInt uiTrIdx = pCtu->getTransformIdx(i);
+
+    if(pCtu->isInter(i) && pCtu->getCbf( i, COMPONENT_Y, uiTrIdx ) )
     {
       xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
     }//Note that only InterY is processed. QP rounding is based on InterY data only.
-   
+
     pCoeffY  += uiMinNumCoeffInCU;
     pArlCoeffY  += uiMinNumCoeffInCU;
@@ -3007,3 +3031,4 @@
 }
 #endif
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCu.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncCu.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -66,5 +66,5 @@
 {
 private:
-  
+
   TComDataCU**            m_ppcBestCU;      ///< Best CUs in each depth
   TComDataCU**            m_ppcTempCU;      ///< Temporary CUs in each depth
@@ -73,5 +73,5 @@
 #endif
   UChar                   m_uhTotalDepth;
-  
+
   TComYuv**               m_ppcPredYuvBest; ///< Best Prediction Yuv for each depth
   TComYuv**               m_ppcResiYuvBest; ///< Best Residual Yuv for each depth
@@ -81,5 +81,5 @@
   TComYuv**               m_ppcRecoYuvTemp; ///< Temporary Reconstruction Yuv for each depth
   TComYuv**               m_ppcOrigYuv;     ///< Original Yuv for each depth
-  
+
 #if H_3D_DBBP
   TComYuv**               m_ppcOrigYuvDBBP;
@@ -88,21 +88,21 @@
   //  Data : encoder control
   Bool                    m_bEncodeDQP;
-  
+  Bool                    m_stillToCodeChromaQpOffsetFlag; //indicates whether chroma QP offset flag needs to coded at this particular CU granularity.
+  Int                     m_cuChromaQpOffsetIdxPlus1; // if 0, then cu_chroma_qp_offset_flag will be 0, otherwise cu_chroma_qp_offset_flag will be 1.
+
   //  Access channel
   TEncCfg*                m_pcEncCfg;
   TEncSearch*             m_pcPredSearch;
   TComTrQuant*            m_pcTrQuant;
-  TComBitCounter*         m_pcBitCounter;
   TComRdCost*             m_pcRdCost;
-  
+
   TEncEntropy*            m_pcEntropyCoder;
-  TEncCavlc*              m_pcCavlcCoder;
-  TEncSbac*               m_pcSbacCoder;
   TEncBinCABAC*           m_pcBinCABAC;
-  
+
   // SBAC RD
   TEncSbac***             m_pppcRDSbacCoder;
   TEncSbac*               m_pcRDGoOnSbacCoder;
   TEncRateCtrl*           m_pcRateCtrl;
+
 #if KWU_RC_MADPRED_E0227
   UInt                    m_LCUPredictionSAD;
@@ -114,35 +114,35 @@
   /// copy parameters from encoder class
   Void  init                ( TEncTop* pcEncTop );
-  
+
   /// create internal buffers
-  Void  create              ( UChar uhTotalDepth, UInt iMaxWidth, UInt iMaxHeight );
-  
+  Void  create              ( UChar uhTotalDepth, UInt iMaxWidth, UInt iMaxHeight, ChromaFormat chromaFormat );
+
   /// destroy internal buffers
   Void  destroy             ();
-  
-  /// CU analysis function
-  Void  compressCU          ( TComDataCU*&  rpcCU );
-  
-  /// CU encoding function
-  Void  encodeCU            ( TComDataCU*    pcCU );
-  
-  Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
+
+  /// CTU analysis function
+  Void  compressCtu         ( TComDataCU*  pCtu );
+
+  /// CTU encoding function
+  Void  encodeCtu           ( TComDataCU*  pCtu );
+
+  Int   updateCtuDataISlice ( TComDataCU* pCtu, Int width, Int height );
 #if KWU_RC_MADPRED_E0227
   UInt getLCUPredictionSAD() { return m_LCUPredictionSAD; }
 #endif
-  Int   updateLCUDataISlice ( TComDataCU* pcCU, Int LCUIdx, Int width, Int height );
+
 protected:
-  Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
+  Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx );
 #if AMP_ENC_SPEEDUP
-  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth, PartSize eParentPartSize = SIZE_NONE );
+  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth DEBUG_STRING_FN_DECLARE(sDebug), PartSize eParentPartSize = NUMBER_OF_PART_SIZES );
 #else
   Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
 #endif
   Void  xEncodeCU           ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
-  
+
   Int   xComputeQP          ( TComDataCU* pcCU, UInt uiDepth );
-  Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
-  
-  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode);
+  Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth DEBUG_STRING_FN_DECLARE(sParent) DEBUG_STRING_FN_DECLARE(sTest) DEBUG_STRING_PASS_INTO(Bool bAddSizeInfo=true));
+
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU DEBUG_STRING_FN_DECLARE(sDebug), Bool *earlyDetectionSkipMode );
 
 #if AMP_MRG
@@ -150,5 +150,5 @@
   Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize,  Bool bFMD, Bool bUseMRG = false  ) ;
 #else
-  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG = false  );
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseMRG = false  );
 #endif
 #else
@@ -165,11 +165,16 @@
   Void  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bOnlyIVP );
 #else
-  Void  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+  Void  xCheckRDCostIntra   ( TComDataCU *&rpcBestCU,
+                              TComDataCU *&rpcTempCU,
+                              Double      &cost,
+                              PartSize     ePartSize
+                              DEBUG_STRING_FN_DECLARE(sDebug)
+                            );
 #endif
   Void  xCheckDQP           ( TComDataCU*  pcCU );
-  
+
   Void  xCheckIntraPCM      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU                      );
   Void  xCopyAMVPInfo       ( AMVPInfo* pSrc, AMVPInfo* pDst );
-  Void  xCopyYuv2Pic        (TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth, TComDataCU* pcCU, UInt uiLPelX, UInt uiTPelY );
+  Void  xCopyYuv2Pic        (TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth );
   Void  xCopyYuv2Tmp        ( UInt uhPartUnitIdx, UInt uiDepth );
 
@@ -177,19 +182,22 @@
   Void setdQPFlag           ( Bool b )                { m_bEncodeDQP = b;           }
 
+  Bool getCodeChromaQpAdjFlag() { return m_stillToCodeChromaQpOffsetFlag; }
+  Void setCodeChromaQpAdjFlag( Bool b ) { m_stillToCodeChromaQpOffsetFlag = b; }
+
 #if ADAPTIVE_QP_SELECTION
   // Adaptive reconstruction level (ARL) statistics collection functions
-  Void xLcuCollectARLStats(TComDataCU* rpcCU);
-  Int  xTuCollectARLStats(TCoeff* rpcCoeff, Int* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples );
-#endif
-
-#if AMP_ENC_SPEEDUP 
+  Void xCtuCollectARLStats(TComDataCU* pCtu);
+  Int  xTuCollectARLStats(TCoeff* rpcCoeff, TCoeff* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples );
+#endif
+
+#if AMP_ENC_SPEEDUP
 #if AMP_MRG
-  Void deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver);
-#else
-  Void deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver);
-#endif
-#endif
-
-  Void  xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv ); 
+  Void deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver);
+#else
+  Void deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver);
+#endif
+#endif
+
+  Void  xFillPCMBuffer     ( TComDataCU* pCU, TComYuv* pOrgYuv );
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,14 +37,19 @@
 
 #include "TEncEntropy.h"
-#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/CommonDef.h"
 #include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComTU.h"
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+#include "../TLibCommon/Debug.h"
+static const Bool bDebugPredEnabled = DebugOptionList::DebugPred.getInt()!=0;
+#endif
 
 //! \ingroup TLibEncoder
 //! \{
 
-Void TEncEntropy::setEntropyCoder ( TEncEntropyIf* e, TComSlice* pcSlice )
+Void TEncEntropy::setEntropyCoder ( TEncEntropyIf* e )
 {
   m_pcEntropyCoderIf = e;
-  m_pcEntropyCoderIf->setSlice ( pcSlice );
 }
 
@@ -63,5 +68,5 @@
 {
   m_pcEntropyCoderIf->codeTerminatingBit( uiIsLast );
-  
+
   return;
 }
@@ -72,5 +77,5 @@
 }
 
-Void TEncEntropy::encodePPS( TComPPS* pcPPS )
+Void TEncEntropy::encodePPS( const TComPPS* pcPPS )
 {
   m_pcEntropyCoderIf->codePPS( pcPPS );
@@ -78,5 +83,5 @@
 }
 
-Void TEncEntropy::encodeSPS( TComSPS* pcSPS )
+Void TEncEntropy::encodeSPS( const TComSPS* pcSPS )
 {
   m_pcEntropyCoderIf->codeSPS( pcSPS );
@@ -93,5 +98,5 @@
 }
 
-Void TEncEntropy::encodeVPS( TComVPS* pcVPS )
+Void TEncEntropy::encodeVPS( const TComVPS* pcVPS )
 {
   m_pcEntropyCoderIf->codeVPS( pcVPS );
@@ -125,22 +130,12 @@
 }
 #endif
-/** encode merge flag
- * \param pcCU
- * \param uiAbsPartIdx
- * \returns Void
- */
+//! encode merge flag
 Void TEncEntropy::encodeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
-{ 
+{
   // at least one merge candidate exists
   m_pcEntropyCoderIf->codeMergeFlag( pcCU, uiAbsPartIdx );
 }
 
-/** encode merge index
- * \param pcCU
- * \param uiAbsPartIdx
- * \param uiPUIdx
- * \param bRD
- * \returns Void
- */
+//! encode merge index
 Void TEncEntropy::encodeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
 {
@@ -208,10 +203,6 @@
 #endif
 
-/** encode prediction mode
- * \param pcCU
- * \param uiAbsPartIdx
- * \param bRD
- * \returns Void
- */
+
+//! encode prediction mode
 Void TEncEntropy::encodePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
 {
@@ -220,4 +211,5 @@
     uiAbsPartIdx = 0;
   }
+
   if ( pcCU->getSlice()->isIntra() )
   {
@@ -228,5 +220,5 @@
 }
 
-// Split mode
+//! encode split flag
 Void TEncEntropy::encodeSplitFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
 {
@@ -235,14 +227,9 @@
     uiAbsPartIdx = 0;
   }
+
   m_pcEntropyCoderIf->codeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
 }
 
-/** encode partition size
- * \param pcCU
- * \param uiAbsPartIdx
- * \param uiDepth
- * \param bRD
- * \returns Void
- */
+//! encode partition size
 Void TEncEntropy::encodePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
 {
@@ -251,14 +238,13 @@
     uiAbsPartIdx = 0;
   }
-  
+
   m_pcEntropyCoderIf->codePartSize( pcCU, uiAbsPartIdx, uiDepth );
-  
-}
-
-/** Encode I_PCM information. 
- * \param pcCU pointer to CU 
- * \param uiAbsPartIdx CU index
- * \param bRD flag indicating estimation or encoding
- * \returns Void
+}
+
+
+/** Encode I_PCM information.
+ * \param pcCU          pointer to CU
+ * \param uiAbsPartIdx  CU index
+ * \param bRD           flag indicating estimation or encoding
  */
 Void TEncEntropy::encodeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
@@ -270,20 +256,25 @@
     return;
   }
-  
-  if( bRD )
-  {
-    uiAbsPartIdx = 0;
-  }
-  
+
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+
   m_pcEntropyCoderIf->codeIPCMInfo ( pcCU, uiAbsPartIdx );
-}
-
-#if H_3D_DISABLE_CHROMA
-Void TEncEntropy::xEncodeTransform( TComDataCU* pcCU,UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP, Bool rd )
-#else
-Void TEncEntropy::xEncodeTransform( TComDataCU* pcCU,UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP )
-#endif
-{
-
+
+}
+
+Void TEncEntropy::xEncodeTransform( Bool& bCodeDQP, Bool& codeChromaQpAdj, TComTU &rTu )
+{
+
+//pcCU, absPartIdxCU, uiAbsPartIdx, uiDepth+1, uiTrIdx+1, quadrant,
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  const UInt numValidComponent = pcCU->getPic()->getNumberValidComponents();
+  const Bool bChroma = isChromaEnabled(pcCU->getPic()->getChromaFormat());
+  const UInt uiTrIdx = rTu.GetTransformDepthRel();
+  const UInt uiDepth = rTu.GetTransformDepthTotal();
 #if H_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
@@ -292,54 +283,48 @@
 
   DTRACE_TU_S("=========== transform_tree ===========\n")
-  DTRACE_TU("x0", uiLPelX)
-  DTRACE_TU("x1", uiTPelY)
-  DTRACE_TU("log2TrafoSize", g_uiMaxCUWidth>>uiDepth)
-  DTRACE_TU("trafoDepth"  , uiDepth)
-#endif
-#endif
-
-  const UInt uiSubdiv = pcCU->getTransformIdx( uiAbsPartIdx ) + pcCU->getDepth( uiAbsPartIdx ) > uiDepth;
-  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
-  UInt cbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA    , uiTrIdx );
-  UInt cbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
-  UInt cbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
-#if H_3D_DISABLE_CHROMA
-  if( !rd && pcCU->getSlice()->getSPS()->getChromaFormatIdc() == 0 )
-  {
-    cbfU = 0;
-    cbfV = 0;
-  }
-#endif
-  if(uiTrIdx==0)
-  {
-    m_bakAbsPartIdxCU = uiAbsPartIdx;
-  }
-  if( uiLog2TrafoSize == 2 )
-  {
-    UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
-    if( ( uiAbsPartIdx % partNum ) == 0 )
-    {
-      m_uiBakAbsPartIdx   = uiAbsPartIdx;
-      m_uiBakChromaOffset = offsetChroma;
-    }
-    else if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
-    {
-      cbfU = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
-      cbfV = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
-#if H_3D_DISABLE_CHROMA
-      if( !rd && pcCU->getSlice()->getSPS()->getChromaFormatIdc() == 0 )
-      {
-        cbfU = 0;
-        cbfV = 0;
-      }
-#endif
-    }
-  }
-  
-  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+    DTRACE_TU("x0", uiLPelX)
+    DTRACE_TU("x1", uiTPelY)
+    DTRACE_TU("log2TrafoSize", pcCU->getSlice()->getSPS()->getMaxCUWidth()  >> uiDepth )
+    DTRACE_TU("trafoDepth"  , uiDepth)
+#endif
+#endif
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  const Bool bDebugRQT=pcCU->getSlice()->getFinalized() && DebugOptionList::DebugRQT.getInt()!=0;
+  if (bDebugRQT)
+  {
+    printf("x..codeTransform: offsetLuma=%d offsetChroma=%d absPartIdx=%d, uiDepth=%d\n width=%d, height=%d, uiTrIdx=%d, uiInnerQuadIdx=%d\n",
+           rTu.getCoefficientOffset(COMPONENT_Y), rTu.getCoefficientOffset(COMPONENT_Cb), uiAbsPartIdx, uiDepth, rTu.getRect(COMPONENT_Y).width, rTu.getRect(COMPONENT_Y).height, rTu.GetTransformDepthRel(), rTu.GetSectionNumber());
+  }
+#endif
+  const UInt uiSubdiv = pcCU->getTransformIdx( uiAbsPartIdx ) > uiTrIdx;// + pcCU->getDepth( uiAbsPartIdx ) > uiDepth;
+  const UInt uiLog2TrafoSize = rTu.GetLog2LumaTrSize();
+
+
+  UInt cbf[MAX_NUM_COMPONENT] = {0,0,0};
+  Bool bHaveACodedBlock       = false;
+  Bool bHaveACodedChromaBlock = false;
+
+  for(UInt ch=0; ch<numValidComponent; ch++)
+  {
+    const ComponentID compID = ComponentID(ch);
+
+    cbf[compID] = pcCU->getCbf( uiAbsPartIdx, compID , uiTrIdx );
+    
+    if (cbf[ch] != 0)
+    {
+      bHaveACodedBlock = true;
+      if (isChroma(compID))
+      {
+        bHaveACodedChromaBlock = true;
+      }
+    }
+  }
+
+  if( pcCU->isIntra(uiAbsPartIdx) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
   {
     assert( uiSubdiv );
   }
-  else if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && (pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N) && uiDepth == pcCU->getDepth(uiAbsPartIdx) &&  (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) )
+  else if( pcCU->isInter(uiAbsPartIdx) && (pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N) && uiDepth == pcCU->getDepth(uiAbsPartIdx) &&  (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) )
   {
     if ( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
@@ -372,76 +357,28 @@
   const UInt uiTrDepthCurr = uiDepth - pcCU->getDepth( uiAbsPartIdx );
   const Bool bFirstCbfOfCU = uiTrDepthCurr == 0;
-  if( bFirstCbfOfCU || uiLog2TrafoSize > 2 )
-  {
-#if H_3D_DISABLE_CHROMA
-    if (pcCU->getSlice()->getSPS()->getChromaFormatIdc() != 0 || rd)
-    {
-      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) )
-      {
-        m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr );
-      }
-      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) )
-      {
-        m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr );
-      }
-    }
-#else
-    if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) )
-    {
-      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr );
-    }
-    if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) )
-    {
-      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr );
-    }
-#endif
-  }
-  else if( uiLog2TrafoSize == 2 )
-  {
-#if H_3D_DISABLE_CHROMA
-    if ( rd && pcCU->getSlice()->getSPS()->getChromaFormatIdc() != 0 )
-    {
-    assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) );
-    assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) );
-  }
-#else
-    assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) );
-    assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) );
-#endif
-  }
-  
+
+  for(UInt ch=COMPONENT_Cb; ch<numValidComponent; ch++)
+  {
+    const ComponentID compID=ComponentID(ch);
+    if( bFirstCbfOfCU || rTu.ProcessingAllQuadrants(compID) )
+    {
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepthCurr - 1 ) )
+      {
+        m_pcEntropyCoderIf->codeQtCbf( rTu, compID, (uiSubdiv == 0) );
+      }
+    }
+    else
+    {
+      assert( pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepthCurr - 1 ) );
+    }
+  }
+
   if( uiSubdiv )
   {
-    UInt size;
-    width  >>= 1;
-    height >>= 1;
-    size = width*height;
-    uiTrIdx++;
-    ++uiDepth;
-    const UInt partNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
-    
-#if H_3D_DISABLE_CHROMA
-    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP, rd );
-
-    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
-    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP ,rd );
-
-    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
-    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP, rd );
-
-    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
-    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP, rd );
-#else
-    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
-
-    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
-    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
-
-    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
-    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
-
-    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
-    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
-#endif
+    TComTURecurse tuRecurseChild(rTu, true);
+    do
+    {
+      xEncodeTransform( bCodeDQP, codeChromaQpAdj, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
   }
   else
@@ -459,67 +396,84 @@
     }
 #endif
-    
-#if H_3D_DISABLE_CHROMA
-    Bool notcbfUV = !rd && pcCU->getSlice()->getSPS()->getChromaFormatIdc() == 0 ? 1 : ( !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) ) ;
-    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && 
-      uiDepth == pcCU->getDepth( uiAbsPartIdx ) && notcbfUV ) 
-#else
-    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
-#endif
-    {
-      assert( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, 0 ) );
+    if( !pcCU->isIntra(uiAbsPartIdx) && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && (!bChroma || (!pcCU->getCbf( uiAbsPartIdx, COMPONENT_Cb, 0 ) && !pcCU->getCbf( uiAbsPartIdx, COMPONENT_Cr, 0 ) ) ) )
+    {
+      assert( pcCU->getCbf( uiAbsPartIdx, COMPONENT_Y, 0 ) );
       //      printf( "saved one bin! " );
     }
     else
     {
-      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, pcCU->getTransformIdx( uiAbsPartIdx ) );
-    }
-
-
-    if ( cbfY || cbfU || cbfV )
-    {
-      // dQP: only for LCU once
+      m_pcEntropyCoderIf->codeQtCbf( rTu, COMPONENT_Y, true ); //luma CBF is always at the lowest level
+    }
+
+    if ( bHaveACodedBlock )
+    {
+      // dQP: only for CTU once
       if ( pcCU->getSlice()->getPPS()->getUseDQP() )
       {
         if ( bCodeDQP )
         {
-          encodeQP( pcCU, m_bakAbsPartIdxCU );
+          encodeQP( pcCU, rTu.GetAbsPartIdxCU() );
           bCodeDQP = false;
         }
       }
-    }
-    if( cbfY )
-    {
-      Int trWidth = width;
-      Int trHeight = height;
-      m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffY()+offsetLuma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
-    }
-    if( uiLog2TrafoSize > 2 )
-    {
-      Int trWidth = width >> 1;
-      Int trHeight = height >> 1;
-      if( cbfU )
-      {
-        m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCb()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
-      }
-      if( cbfV )
-      {
-        m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCr()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
-      }
-    }
-    else
-    {
-      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
-      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
-      {
-        Int trWidth = width;
-        Int trHeight = height;
-        if( cbfU )
+
+      if ( pcCU->getSlice()->getUseChromaQpAdj() )
+      {
+        if ( bHaveACodedChromaBlock && codeChromaQpAdj && !pcCU->getCUTransquantBypass(rTu.GetAbsPartIdxCU()) )
         {
-          m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCb()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+          encodeChromaQpAdjustment( pcCU, rTu.GetAbsPartIdxCU() );
+          codeChromaQpAdj = false;
         }
-        if( cbfV )
+      }
+
+      const UInt numValidComp=pcCU->getPic()->getNumberValidComponents();
+
+      for(UInt ch=COMPONENT_Y; ch<numValidComp; ch++)
+      {
+        const ComponentID compID=ComponentID(ch);
+
+        if (rTu.ProcessComponentSection(compID))
         {
-          m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCr()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+          if (bDebugRQT)
+          {
+            printf("Call NxN for chan %d width=%d height=%d cbf=%d\n", compID, rTu.getRect(compID).width, rTu.getRect(compID).height, 1);
+          }
+#endif
+
+          if (rTu.getRect(compID).width != rTu.getRect(compID).height)
+          {
+            //code two sub-TUs
+            TComTURecurse subTUIterator(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+            do
+            {
+              const UChar subTUCBF = pcCU->getCbf(subTUIterator.GetAbsPartIdxTU(compID), compID, (uiTrIdx + 1));
+
+              if (subTUCBF != 0)
+              {
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+                if (bDebugRQT)
+                {
+                  printf("Call NxN for chan %d width=%d height=%d cbf=%d\n", compID, subTUIterator.getRect(compID).width, subTUIterator.getRect(compID).height, 1);
+                }
+#endif
+                m_pcEntropyCoderIf->codeCoeffNxN( subTUIterator, (pcCU->getCoeff(compID) + subTUIterator.getCoefficientOffset(compID)), compID );
+              }
+            }
+            while (subTUIterator.nextSection(rTu));
+          }
+          else
+          {
+            if (isChroma(compID) && (cbf[COMPONENT_Y] != 0))
+            {
+              m_pcEntropyCoderIf->codeCrossComponentPrediction( rTu, compID );
+            }
+
+            if (cbf[compID] != 0)
+            {
+              m_pcEntropyCoderIf->codeCoeffNxN( rTu, (pcCU->getCoeff(compID) + rTu.getCoefficientOffset(compID)), compID );
+            }
+          }
         }
       }
@@ -528,5 +482,6 @@
 }
 
-// Intra direction for Luma
+
+//! encode intra direction for luma
 Void TEncEntropy::encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiplePU )
 {
@@ -534,56 +489,67 @@
 }
 
-// Intra direction for Chroma
-Void TEncEntropy::encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
-{
-  if( bRD )
-  {
-    uiAbsPartIdx = 0;
-  }
-  
+
+//! encode intra direction for chroma
+Void TEncEntropy::encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
   m_pcEntropyCoderIf->codeIntraDirChroma( pcCU, uiAbsPartIdx );
-}
-
-Void TEncEntropy::encodePredInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
-{
-  if( bRD )
-  {
-    uiAbsPartIdx = 0;
-  }
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugPredEnabled && pcCU->getSlice()->getFinalized())
+  {
+    UInt cdir=pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, uiAbsPartIdx);
+    if (cdir==36)
+    {
+      cdir=pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiAbsPartIdx);
+    }
+    printf("coding chroma Intra dir: %d, uiAbsPartIdx: %d, luma dir: %d\n", cdir, uiAbsPartIdx, pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiAbsPartIdx));
+  }
+#endif
+}
+
+
+Void TEncEntropy::encodePredInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
   if( pcCU->isIntra( uiAbsPartIdx ) )                                 // If it is Intra mode, encode intra prediction mode.
   {
     encodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx,true );
 #if H_3D_DIM_SDC
-#if H_3D_DISABLE_CHROMA
-    if(!pcCU->getSDCFlag(uiAbsPartIdx) && ( pcCU->getSlice()->getSPS()->getChromaFormatIdc() != 0  || bRD ) ) 
-#else
     if(!pcCU->getSDCFlag(uiAbsPartIdx))
 #endif
-#endif
-      encodeIntraDirModeChroma( pcCU, uiAbsPartIdx, bRD );
+    if (pcCU->getPic()->getChromaFormat()!=CHROMA_400)
+    {
+      encodeIntraDirModeChroma( pcCU, uiAbsPartIdx );
+
+      if (enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()) && pcCU->getPartitionSize( uiAbsPartIdx )==SIZE_NxN)
+      {
+        UInt uiPartOffset = ( pcCU->getPic()->getNumPartitionsInCtu() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+        encodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset   );
+        encodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset*2 );
+        encodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset*3 );
+      }
+    }
   }
   else                                                                // if it is Inter mode, encode motion vector and reference index
   {
-    encodePUWise( pcCU, uiAbsPartIdx, bRD );
-  }
-}
-
-/** encode motion information for every PU block
- * \param pcCU
- * \param uiAbsPartIdx
- * \param bRD
- * \returns Void
- */
-Void TEncEntropy::encodePUWise( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
-{
-  if ( bRD )
-  {
-    uiAbsPartIdx = 0;
-  }
-  
+    encodePUWise( pcCU, uiAbsPartIdx );
+  }
+}
+
+Void TEncEntropy::encodeCrossComponentPrediction( TComTU &rTu, ComponentID compID )
+{
+  m_pcEntropyCoderIf->codeCrossComponentPrediction( rTu, compID );
+}
+
+//! encode motion information for every PU block
+Void TEncEntropy::encodePUWise( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  const Bool bDebugPred = bDebugPredEnabled && pcCU->getSlice()->getFinalized();
+#endif
+
   PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
   UInt uiNumPU = ( ePartSize == SIZE_2Nx2N ? 1 : ( ePartSize == SIZE_NxN ? 4 : 2 ) );
   UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
-  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxTotalCUDepth() - uiDepth ) << 1 ) ) >> 4;
 
   for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
@@ -599,4 +565,11 @@
     {
       encodeMergeIndex( pcCU, uiSubPartIdx );
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      if (bDebugPred)
+      {
+        std::cout << "Coded merge flag, CU absPartIdx: " << uiAbsPartIdx << " PU(" << uiPartIdx << ") absPartIdx: " << uiSubPartIdx;
+        std::cout << " merge index: " << (UInt)pcCU->getMergeIndex(uiSubPartIdx) << std::endl;
+      }
+#endif
     }
     else
@@ -610,4 +583,14 @@
           encodeMvdPU       ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
           encodeMVPIdxPU    ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+          if (bDebugPred)
+          {
+            std::cout << "refListIdx: " << uiRefListIdx << std::endl;
+            std::cout << "MVD horizontal: " << pcCU->getCUMvField(RefPicList(uiRefListIdx))->getMvd( uiAbsPartIdx ).getHor() << std::endl;
+            std::cout << "MVD vertical:   " << pcCU->getCUMvField(RefPicList(uiRefListIdx))->getMvd( uiAbsPartIdx ).getVer() << std::endl;
+            std::cout << "MVPIdxPU: " << pcCU->getMVPIdx(RefPicList( uiRefListIdx ), uiSubPartIdx) << std::endl;
+            std::cout << "InterDir: " << (UInt)pcCU->getInterDir(uiSubPartIdx) << std::endl;
+          }
+#endif
         }
       }
@@ -626,40 +609,30 @@
 
   m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
-  return;
-}
-
-/** encode reference frame index for a PU block
- * \param pcCU
- * \param uiAbsPartIdx
- * \param eRefList
- * \returns Void
- */
+
+  return;
+}
+
+//! encode reference frame index for a PU block
 Void TEncEntropy::encodeRefFrmIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
 {
-  assert( !pcCU->isIntra( uiAbsPartIdx ) );
-  {
-    if ( ( pcCU->getSlice()->getNumRefIdx( eRefList ) == 1 ) )
-    {
-      return;
-    }
-
-    if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
-    {
-      m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
-    }
-  }
-
-  return;
-}
-
-/** encode motion vector difference for a PU block
- * \param pcCU
- * \param uiAbsPartIdx
- * \param eRefList
- * \returns Void
- */
+  assert( pcCU->isInter( uiAbsPartIdx ) );
+
+  if ( ( pcCU->getSlice()->getNumRefIdx( eRefList ) == 1 ) )
+  {
+    return;
+  }
+
+  if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+  {
+    m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+  }
+
+  return;
+}
+
+//! encode motion vector difference for a PU block
 Void TEncEntropy::encodeMvdPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
 {
-  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+  assert( pcCU->isInter( uiAbsPartIdx ) );
 
   if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
@@ -680,7 +653,7 @@
 }
 
-Void TEncEntropy::encodeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
-{
-  m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, eType, uiTrDepth );
+Void TEncEntropy::encodeQtCbf( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
+{
+  m_pcEntropyCoderIf->codeQtCbf( rTu, compID, lowestLevel );
 }
 
@@ -695,11 +668,12 @@
 }
 
-Void TEncEntropy::encodeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
-{
-  m_pcEntropyCoderIf->codeQtCbfZero( pcCU, eType, uiTrDepth );
-}
-Void TEncEntropy::encodeQtRootCbfZero( TComDataCU* pcCU )
-{
-  m_pcEntropyCoderIf->codeQtRootCbfZero( pcCU );
+Void TEncEntropy::encodeQtCbfZero( TComTU &rTu, const ChannelType chType )
+{
+  m_pcEntropyCoderIf->codeQtCbfZero( rTu, chType );
+}
+
+Void TEncEntropy::encodeQtRootCbfZero( )
+{
+  m_pcEntropyCoderIf->codeQtRootCbfZero( );
 }
 
@@ -711,5 +685,5 @@
     uiAbsPartIdx = 0;
   }
-  
+
   if ( pcCU->getSlice()->getPPS()->getUseDQP() )
   {
@@ -718,22 +692,25 @@
 }
 
+//! encode chroma qp adjustment
+Void TEncEntropy::encodeChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx, Bool inRd )
+{
+  if( inRd )
+  {
+    absPartIdx = 0;
+  }
+
+  m_pcEntropyCoderIf->codeChromaQpAdjustment( cu, absPartIdx );
+}
 
 // texture
-/** encode coefficients
- * \param pcCU
- * \param uiAbsPartIdx
- * \param uiDepth
- * \param uiWidth
- * \param uiHeight
- */
-#if H_3D_DISABLE_CHROMA
-Void TEncEntropy::encodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP, Bool rd )
-#else
-Void TEncEntropy::encodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP )
-#endif
-{
-  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
-  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
-  UInt uiChromaOffset = uiLumaOffset>>2;
+
+//! encode coefficients
+Void TEncEntropy::encodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool& bCodeDQP, Bool& codeChromaQpAdj )
+{
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  const Bool bDebugRQT=pcCU->getSlice()->getFinalized() && DebugOptionList::DebugRQT.getInt()!=0;
+#endif
+
 #if H_3D_DIM_SDC
   if( pcCU->getSDCFlag( uiAbsPartIdx ) && pcCU->isIntra( uiAbsPartIdx ) )
@@ -742,14 +719,6 @@
     assert( pcCU->getTransformIdx(uiAbsPartIdx) == 0 );
     assert( pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA) == 1 );
-#if H_3D_DISABLE_CHROMA
-    if (!pcCU->getSlice()->getIsDepth() )
-    {
-      assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
-      assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
-    }
-#else
     assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
     assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
-#endif
   }
 
@@ -785,11 +754,15 @@
 #endif
 
+
   if( pcCU->isIntra(uiAbsPartIdx) )
   {
-#if !H_MV
-    DTRACE_CABAC_VL( g_nSymbolCounter++ )
-    DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
-    DTRACE_CABAC_V( uiDepth )
-    DTRACE_CABAC_T( "\n" )
+#if !NH_MV
+    if (false)
+    {
+      DTRACE_CABAC_VL( g_nSymbolCounter++ )
+      DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
+      DTRACE_CABAC_V( uiDepth )
+      DTRACE_CABAC_T( "\n" )
+    }
 #endif
   }
@@ -805,23 +778,52 @@
     }
   }
-  
-#if H_3D_DISABLE_CHROMA
-  xEncodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, bCodeDQP, rd);
-#else
-  xEncodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, bCodeDQP);
-#endif
-}
-
-Void TEncEntropy::encodeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiTrWidth, UInt uiTrHeight, UInt uiDepth, TextType eType )
-{
-  // This is for Transform unit processing. This may be used at mode selection stage for Inter.
-  m_pcEntropyCoderIf->codeCoeffNxN( pcCU, pcCoeff, uiAbsPartIdx, uiTrWidth, uiTrHeight, uiDepth, eType );
-}
-
-Void TEncEntropy::estimateBit (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType)
-{  
-  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : TEXT_CHROMA;
-  
-  m_pcEntropyCoderIf->estBit ( pcEstBitsSbac, width, height, eTType );
+
+  TComTURecurse tuRecurse(pcCU, uiAbsPartIdx, uiDepth);
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugRQT)
+  {
+    printf("..codeCoeff: uiAbsPartIdx=%d, PU format=%d, 2Nx2N=%d, NxN=%d\n", uiAbsPartIdx, pcCU->getPartitionSize(uiAbsPartIdx), SIZE_2Nx2N, SIZE_NxN);
+  }
+#endif
+
+  xEncodeTransform( bCodeDQP, codeChromaQpAdj, tuRecurse );
+}
+
+Void TEncEntropy::encodeCoeffNxN( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID)
+{
+  TComDataCU *pcCU = rTu.getCU();
+
+  if (pcCU->getCbf(rTu.GetAbsPartIdxTU(), compID, rTu.GetTransformDepthRel()) != 0)
+  {
+    if (rTu.getRect(compID).width != rTu.getRect(compID).height)
+    {
+      //code two sub-TUs
+      TComTURecurse subTUIterator(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+      const UInt subTUSize = subTUIterator.getRect(compID).width * subTUIterator.getRect(compID).height;
+
+      do
+      {
+        const UChar subTUCBF = pcCU->getCbf(subTUIterator.GetAbsPartIdxTU(compID), compID, (subTUIterator.GetTransformDepthRel() + 1));
+
+        if (subTUCBF != 0)
+        {
+          m_pcEntropyCoderIf->codeCoeffNxN( subTUIterator, (pcCoef + (subTUIterator.GetSectionNumber() * subTUSize)), compID);
+        }
+      }
+      while (subTUIterator.nextSection(rTu));
+    }
+    else
+    {
+      m_pcEntropyCoderIf->codeCoeffNxN(rTu, pcCoef, compID);
+    }
+  }
+}
+
+Void TEncEntropy::estimateBit (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, const ChannelType chType)
+{
+  const UInt heightAtEntropyCoding = (width != height) ? (height >> 1) : height;
+
+  m_pcEntropyCoderIf->estBit ( pcEstBitsSbac, width, heightAtEntropyCoding, chType );
 }
 
@@ -829,19 +831,11 @@
 {
   Int count = 0;
-  
+
   for ( Int i = 0; i < uiSize; i++ )
   {
     count += pcCoef[i] != 0;
   }
-  
+
   return count;
-}
-
-/** encode quantization matrix
- * \param scalingList quantization matrix information
- */
-Void TEncEntropy::encodeScalingList( TComScalingList* scalingList )
-{
-  m_pcEntropyCoderIf->codeScalingList( scalingList );
 }
 
@@ -893,3 +887,4 @@
 }
 #endif
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,4 +46,5 @@
 #include "TLibCommon/TComTrQuant.h"
 #include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComChromaFormat.h"
 
 class TEncSbac;
@@ -59,16 +60,13 @@
 {
 public:
-  virtual Void  resetEntropy          ()                = 0;
-  virtual Void  determineCabacInitIdx ()                = 0;
+  virtual Void  resetEntropy          (const TComSlice *pSlice)                = 0;
+  virtual SliceType determineCabacInitIdx (const TComSlice *pSlice)                = 0;
   virtual Void  setBitstream          ( TComBitIf* p )  = 0;
-  virtual Void  setSlice              ( TComSlice* p )  = 0;
   virtual Void  resetBits             ()                = 0;
-  virtual Void  resetCoeffCost        ()                = 0;
   virtual UInt  getNumberOfWrittenBits()                = 0;
-  virtual UInt  getCoeffCost          ()                = 0;
-
-  virtual Void  codeVPS                 ( TComVPS* pcVPS )                                      = 0;
-  virtual Void  codeSPS                 ( TComSPS* pcSPS )                                      = 0;
-  virtual Void  codePPS                 ( TComPPS* pcPPS )                                      = 0;
+
+  virtual Void  codeVPS                 ( const TComVPS* pcVPS )                                      = 0;
+  virtual Void  codeSPS                 ( const TComSPS* pcSPS )                                      = 0;
+  virtual Void  codePPS                 ( const TComPPS* pcPPS )                                      = 0;
   virtual Void  codeSliceHeader         ( TComSlice* pcSlice )                                  = 0;
 
@@ -76,7 +74,6 @@
   virtual Void  codeTerminatingBit      ( UInt uilsLast )                                       = 0;
   virtual Void  codeSliceFinish         ()                                                      = 0;
-  virtual Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) = 0;
-  virtual Void codeScalingList   ( TComScalingList* scalingList )      = 0;
-  
+  virtual Void  codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) = 0;
+
 public:
   virtual Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
@@ -101,35 +98,34 @@
 #endif
   virtual Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-  
+
   virtual Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
   virtual Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-  
+
   virtual Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
 
   virtual Void codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx ) = 0;
-  virtual Void codeQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth ) = 0;
+  virtual Void codeQtCbf         ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel ) = 0;
   virtual Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-  virtual Void codeQtCbfZero     ( TComDataCU* pcCU, TextType eType, UInt uiTrDepth ) = 0;
-  virtual Void codeQtRootCbfZero ( TComDataCU* pcCU ) = 0;
+  virtual Void codeQtCbfZero     ( TComTU &rTu, const ChannelType chType ) = 0;
+  virtual Void codeQtRootCbfZero ( ) = 0;
   virtual Void codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiplePU ) = 0;
-  
+
   virtual Void codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
   virtual Void codeInterDir      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
   virtual Void codeRefFrmIdx     ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )      = 0;
   virtual Void codeMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )      = 0;
+
+  virtual Void codeCrossComponentPrediction( TComTU &rTu, ComponentID compID ) = 0;
+
   virtual Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-  virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
-  virtual Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType ) = 0;
-  virtual Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
-  virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType) = 0;
-  
-  virtual Void updateContextTables ( SliceType eSliceType, Int iQp, Bool bExecuteFinish )   = 0;
-  virtual Void updateContextTables ( SliceType eSliceType, Int iQp )   = 0;
-
-  virtual Void codeDFFlag (UInt uiCode, const Char *pSymbolName) = 0;
-  virtual Void codeDFSvlc (Int iCode, const Char *pSymbolName)   = 0;
+  virtual Void codeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeCoeffNxN      ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID ) = 0;
+  virtual Void codeTransformSkipFlags ( TComTU &rTu, ComponentID component ) = 0;
+  virtual Void codeSAOBlkParam   (SAOBlkParam& saoBlkParam, const BitDepths &bitDepths, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
+  virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType) = 0;
+
+  virtual Void codeExplicitRdpcmMode ( TComTU &rTu, const ComponentID compID ) = 0;
 
   virtual ~TEncEntropyIf() {}
-
 };
 
@@ -137,16 +133,10 @@
 class TEncEntropy
 {
-private:
-  UInt    m_uiBakAbsPartIdx;
-  UInt    m_uiBakChromaOffset;
-  UInt    m_bakAbsPartIdxCU;
-
-public:
-  Void    setEntropyCoder           ( TEncEntropyIf* e, TComSlice* pcSlice );
+public:
+  Void    setEntropyCoder           ( TEncEntropyIf* e );
   Void    setBitstream              ( TComBitIf* p )          { m_pcEntropyCoderIf->setBitstream(p);  }
   Void    resetBits                 ()                        { m_pcEntropyCoderIf->resetBits();      }
-  Void    resetCoeffCost            ()                        { m_pcEntropyCoderIf->resetCoeffCost(); }
   UInt    getNumberOfWrittenBits    ()
-  {
+                        {
 #if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
     Bool oldJustDoIt = g_bJustDoIt;
@@ -155,10 +145,8 @@
     g_bJustDoIt = oldJustDoIt; 
 #endif
-    return m_pcEntropyCoderIf->getNumberOfWrittenBits(); 
-  }
-  UInt    getCoeffCost              ()                        { return  m_pcEntropyCoderIf->getCoeffCost(); }
-  Void    resetEntropy              ()                        { m_pcEntropyCoderIf->resetEntropy();  }
-  Void    determineCabacInitIdx     ()                        { m_pcEntropyCoderIf->determineCabacInitIdx(); }
-  
+ return m_pcEntropyCoderIf->getNumberOfWrittenBits(); }
+  Void    resetEntropy              (const TComSlice *pSlice) { m_pcEntropyCoderIf->resetEntropy(pSlice);  }
+  SliceType determineCabacInitIdx   (const TComSlice *pSlice) { return m_pcEntropyCoderIf->determineCabacInitIdx(pSlice); }
+
   Void    encodeSliceHeader         ( TComSlice* pcSlice );
   Void    encodeTilesWPPEntryPoint( TComSlice* pSlice );
@@ -166,10 +154,10 @@
   Void    encodeSliceFinish         ();
   TEncEntropyIf*      m_pcEntropyCoderIf;
-  
-public:
-  Void encodeVPS               ( TComVPS* pcVPS);
+
+public:
+  Void encodeVPS               ( const TComVPS* pcVPS);
   // SPS
-  Void encodeSPS               ( TComSPS* pcSPS );
-  Void encodePPS               ( TComPPS* pcPPS );
+  Void encodeSPS               ( const TComSPS* pcSPS );
+  Void encodePPS               ( const TComPPS* pcPPS );
   Void encodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD = false );
   Void encodeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
@@ -178,5 +166,5 @@
   Void encodeDIS               ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD=false );
 #endif
-  Void encodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void encodeInterDirPU   ( TComDataCU* pcSubCU, UInt uiAbsPartIdx  );
   Void encodeRefFrmIdxPU  ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
@@ -201,35 +189,32 @@
   Void encodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD = false );
   Void encodeIPCMInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
-  Void encodePredInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePredInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiplePU = false );
-  
-  Void encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
-  
+
+  Void encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
   Void encodeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
-  Void encodeQtCbf             ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
-  Void encodeQtCbfZero         ( TComDataCU* pcCU, TextType eType, UInt uiTrDepth );
-  Void encodeQtRootCbfZero     ( TComDataCU* pcCU );
+  Void encodeQtCbf             ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel );
+
+  Void encodeQtCbfZero         ( TComTU &rTu, const ChannelType chType );
+  Void encodeQtRootCbfZero     ( );
   Void encodeQtRootCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void encodeQP                ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
-  Void updateContextTables     ( SliceType eSliceType, Int iQp, Bool bExecuteFinish )   { m_pcEntropyCoderIf->updateContextTables( eSliceType, iQp, bExecuteFinish );     }
-  Void updateContextTables     ( SliceType eSliceType, Int iQp )                        { m_pcEntropyCoderIf->updateContextTables( eSliceType, iQp, true );               }
-
-  Void encodeScalingList       ( TComScalingList* scalingList );
+  Void encodeChromaQpAdjustment ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+
+  Void encodeCrossComponentPrediction( TComTU &rTu, ComponentID compID );
 
 private:
-#if H_3D_DISABLE_CHROMA
-  Void xEncodeTransform        ( TComDataCU* pcCU,UInt offsetLumaOffset, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP, Bool rd );
-public:
-  Void encodeCoeff             ( TComDataCU* pcCU,                 UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP, Bool rd );
-#else
-  Void xEncodeTransform        ( TComDataCU* pcCU,UInt offsetLumaOffset, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP );
-public:
-  Void encodeCoeff             ( TComDataCU* pcCU,                 UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
-#endif
-  
-  Void encodeCoeffNxN         ( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiTrWidth, UInt uiTrHeight, UInt uiDepth, TextType eType );
-  
-  Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
-  Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
+  Void xEncodeTransform        ( Bool& bCodeDQP, Bool& codeChromaQpAdj, TComTU &rTu );
+
+public:
+  Void encodeCoeff             ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool& bCodeDQP, Bool& codeChromaQpAdj );
+
+  Void encodeCoeffNxN         ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID );
+
+  Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+
+  Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, const BitDepths &bitDepths, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, bitDepths, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
+
   static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -50,5 +50,7 @@
 #include <math.h>
 
+#include <deque>
 using namespace std;
+
 //! \ingroup TLibEncoder
 //! \{
@@ -75,19 +77,17 @@
   m_iNumPicCoded        = 0; //Niko
   m_bFirst              = true;
-#if ALLOW_RECOVERY_POINT_AS_RAP
   m_iLastRecoveryPicPOC = 0;
-#endif
-  
+
   m_pcCfg               = NULL;
   m_pcSliceEncoder      = NULL;
   m_pcListPic           = NULL;
-  
+
   m_pcEntropyCoder      = NULL;
   m_pcCavlcCoder        = NULL;
   m_pcSbacCoder         = NULL;
   m_pcBinCABAC          = NULL;
-  
+
   m_bSeqFirst           = true;
-  
+
   m_bRefreshPending     = 0;
   m_pocCRA            = 0;
@@ -95,21 +95,17 @@
   ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
   ::memset(m_ltRefPicUsedByCurrPicFlag, 0, sizeof(m_ltRefPicUsedByCurrPicFlag));
-  m_cpbRemovalDelay   = 0;
   m_lastBPSEI         = 0;
-  xResetNonNestedSEIPresentFlags();
-  xResetNestedSEIPresentFlags();
-#if H_MV
+  m_bufferingPeriodSEIPresentInAU = false;
+#if NH_MV
   m_layerId      = 0;
   m_viewId       = 0;
   m_pocLastCoded = -1; 
-#if H_3D
+#if NH_3D
   m_viewIndex  =   0; 
   m_isDepth = false;
 #endif
 #endif
-#if FIX1172
   m_associatedIRAPType = NAL_UNIT_CODED_SLICE_IDR_N_LP;
   m_associatedIRAPPOC  = 0;
-#endif
   return;
 }
@@ -119,5 +115,5 @@
 }
 
-/** Create list to contain pointers to LCU start addresses of slice.
+/** Create list to contain pointers to CTU start addresses of slice.
  */
 Void  TEncGOP::create()
@@ -135,7 +131,8 @@
   m_pcEncTop     = pcTEncTop;
   m_pcCfg                = pcTEncTop;
+  m_seiEncoder.init(m_pcCfg, pcTEncTop, this);
   m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
   m_pcListPic            = pcTEncTop->getListPic();
-  
+
   m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
   m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
@@ -143,7 +140,5 @@
   m_pcBinCABAC           = pcTEncTop->getBinCABAC();
   m_pcLoopFilter         = pcTEncTop->getLoopFilter();
-  m_pcBitCounter         = pcTEncTop->getBitCounter();
-  
-  //--Adaptive Loop filter
+
   m_pcSAO                = pcTEncTop->getSAO();
   m_pcRateCtrl           = pcTEncTop->getRateCtrl();
@@ -151,9 +146,9 @@
   m_totalCoded         = 0;
 
-#if H_MV
+#if NH_MV
   m_ivPicLists           = pcTEncTop->getIvPicLists(); 
   m_layerId              = pcTEncTop->getLayerId();
   m_viewId               = pcTEncTop->getViewId();
-#if H_3D
+#if NH_3D
   m_viewIndex            = pcTEncTop->getViewIndex();
   m_isDepth              = pcTEncTop->getIsDepth();
@@ -169,222 +164,893 @@
 }
 
-SEIActiveParameterSets* TEncGOP::xCreateSEIActiveParameterSets (TComSPS *sps)
-{
-  SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets(); 
-  seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId(); 
-  seiActiveParameterSets->m_selfContainedCvsFlag = false;
-  seiActiveParameterSets->m_noParameterSetUpdateFlag = false;
-  seiActiveParameterSets->numSpsIdsMinus1 = 0;
-  seiActiveParameterSets->activeSeqParameterSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1); 
-  seiActiveParameterSets->activeSeqParameterSetId[0] = sps->getSPSId();
-  return seiActiveParameterSets;
-}
-
-SEIFramePacking* TEncGOP::xCreateSEIFramePacking()
-{
-  SEIFramePacking *seiFramePacking = new SEIFramePacking();
-  seiFramePacking->m_arrangementId = m_pcCfg->getFramePackingArrangementSEIId();
-  seiFramePacking->m_arrangementCancelFlag = 0;
-  seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
-  assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
-  seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
-  seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
-  seiFramePacking->m_spatialFlippingFlag = 0;
-  seiFramePacking->m_frame0FlippedFlag = 0;
-  seiFramePacking->m_fieldViewsFlag = (seiFramePacking->m_arrangementType == 2);
-  seiFramePacking->m_currentFrameIsFrame0Flag = ((seiFramePacking->m_arrangementType == 5) && m_iNumPicCoded&1);
-  seiFramePacking->m_frame0SelfContainedFlag = 0;
-  seiFramePacking->m_frame1SelfContainedFlag = 0;
-  seiFramePacking->m_frame0GridPositionX = 0;
-  seiFramePacking->m_frame0GridPositionY = 0;
-  seiFramePacking->m_frame1GridPositionX = 0;
-  seiFramePacking->m_frame1GridPositionY = 0;
-  seiFramePacking->m_arrangementReservedByte = 0;
-  seiFramePacking->m_arrangementPersistenceFlag = true;
-  seiFramePacking->m_upsampledAspectRatio = 0;
-  return seiFramePacking;
-}
-
-SEIDisplayOrientation* TEncGOP::xCreateSEIDisplayOrientation()
-{
-  SEIDisplayOrientation *seiDisplayOrientation = new SEIDisplayOrientation();
-  seiDisplayOrientation->cancelFlag = false;
-  seiDisplayOrientation->horFlip = false;
-  seiDisplayOrientation->verFlip = false;
-  seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
-  return seiDisplayOrientation;
-}
-
-SEIToneMappingInfo*  TEncGOP::xCreateSEIToneMappingInfo()
-{
-  SEIToneMappingInfo *seiToneMappingInfo = new SEIToneMappingInfo();
-  seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
-  seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
-  seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
-
-  seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
-  assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
-  seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
-  assert( seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17 );
-  seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
-  assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
-
-  switch( seiToneMappingInfo->m_modelId)
-  {
-  case 0:
-    {
-      seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
-      seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
-      break;
-    }
-  case 1:
-    {
-      seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
-      seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
-      break;
-    }
-  case 2:
-    {
-      UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
-      seiToneMappingInfo->m_startOfCodedInterval.resize(num);
-      Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
-      if(ptmp)
-      {
-        for(int i=0; i<num;i++)
-        {
-          seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
-        }
-      }
-      break;
-    }
-  case 3:
-    {
-      seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
-      seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
-      seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
-      Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
-      Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
-      if(ptmpcoded&&ptmptarget)
-      {
-        for(int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
-        {
-          seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
-          seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
-         }
-       }
-       break;
-     }
-  case 4:
-     {
-       seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
-       seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
-       assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
-       seiToneMappingInfo->m_exposureIndexIdc = m_pcCfg->getTMISEIExposurIndexIdc();
-       seiToneMappingInfo->m_exposureIndexValue = m_pcCfg->getTMISEIExposurIndexValue();
-       assert( seiToneMappingInfo->m_exposureIndexValue !=0 );
-       seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
-       seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
-       seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
-       seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
-       seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
-       assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
-       seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
-       seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
-       assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
-       seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
-       assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
-       break;
-    }
-  default:
-    {
-      assert(!"Undefined SEIToneMapModelId");
-      break;
-    }
-  }
-  return seiToneMappingInfo;
-}
-
-#if H_MV
-SEISubBitstreamProperty *TEncGOP::xCreateSEISubBitstreamProperty( TComSPS *sps)
-{
-  SEISubBitstreamProperty *seiSubBitstreamProperty = new SEISubBitstreamProperty();
-
-  seiSubBitstreamProperty->m_activeVpsId = sps->getVPSId();
-  /* These values can be determined by the encoder; for now we will use the input parameter */
-  TEncTop *encTop = this->m_pcEncTop;
-  seiSubBitstreamProperty->m_numAdditionalSubStreams = encTop->getNumAdditionalSubStreams();
-  seiSubBitstreamProperty->m_subBitstreamMode        = encTop->getSubBitstreamMode();
-  seiSubBitstreamProperty->m_outputLayerSetIdxToVps  = encTop->getOutputLayerSetIdxToVps();
-  seiSubBitstreamProperty->m_highestSublayerId       = encTop->getHighestSublayerId();
-  seiSubBitstreamProperty->m_avgBitRate              = encTop->getAvgBitRate();
-  seiSubBitstreamProperty->m_maxBitRate              = encTop->getMaxBitRate();
-
-  return seiSubBitstreamProperty;
-}
-#endif
-
-Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
-{
+Int TEncGOP::xWriteVPS (AccessUnit &accessUnit, const TComVPS *vps)
+{
+  OutputNALUnit nalu(NAL_UNIT_VPS);
+  m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+  m_pcEntropyCoder->encodeVPS(vps);
+  accessUnit.push_back(new NALUnitEBSP(nalu));
+  return (Int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+}
+
+Int TEncGOP::xWriteSPS (AccessUnit &accessUnit, const TComSPS *sps)
+{
+#if NH_MV
+  OutputNALUnit nalu(NAL_UNIT_SPS, 0, getLayerId() );
+#else
+  OutputNALUnit nalu(NAL_UNIT_SPS);
+#endif
+  m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+  m_pcEntropyCoder->encodeSPS(sps);
+  accessUnit.push_back(new NALUnitEBSP(nalu));
+  return (Int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+
+}
+
+Int TEncGOP::xWritePPS (AccessUnit &accessUnit, const TComPPS *pps)
+{
+#if NH_MV
+  OutputNALUnit nalu(NAL_UNIT_PPS, 0, getLayerId() );
+#else
+  OutputNALUnit nalu(NAL_UNIT_PPS);
+#endif
+  m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+  m_pcEntropyCoder->encodePPS(pps);
+  accessUnit.push_back(new NALUnitEBSP(nalu));
+  return (Int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+}
+
+
+Int TEncGOP::xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice)
+{
+  Int actualTotalBits = 0;
+
+#if NH_MV
+  if ( getLayerId() == 0 )
+  {  
+    actualTotalBits += xWriteVPS(accessUnit, m_pcEncTop->getVPS());
+  }
+#else
+  actualTotalBits += xWriteVPS(accessUnit, m_pcEncTop->getVPS());
+#endif
+  actualTotalBits += xWriteSPS(accessUnit, slice->getSPS());
+  actualTotalBits += xWritePPS(accessUnit, slice->getPPS());
+
+  return actualTotalBits;
+}
+
+// write SEI list into one NAL unit and add it to the Access unit at auPos
+Void TEncGOP::xWriteSEI (NalUnitType naluType, SEIMessages& seiMessages, AccessUnit &accessUnit, AccessUnit::iterator &auPos, Int temporalId, const TComSPS *sps)
+{
+  // don't do anything, if we get an empty list
+  if (seiMessages.empty())
+  {
+    return;
+  }
+#if NH_MV
+  OutputNALUnit nalu(naluType, temporalId, getLayerId() );
+#else
+  OutputNALUnit nalu(naluType, temporalId);
+#endif
+  m_seiWriter.writeSEImessages(nalu.m_Bitstream, seiMessages, sps, false);
+  auPos = accessUnit.insert(auPos, new NALUnitEBSP(nalu));
+  auPos++;
+}
+
+Void TEncGOP::xWriteSEISeparately (NalUnitType naluType, SEIMessages& seiMessages, AccessUnit &accessUnit, AccessUnit::iterator &auPos, Int temporalId, const TComSPS *sps)
+{
+  // don't do anything, if we get an empty list
+  if (seiMessages.empty())
+  {
+    return;
+  }
+  for (SEIMessages::const_iterator sei = seiMessages.begin(); sei!=seiMessages.end(); sei++ )
+  {
+    SEIMessages tmpMessages;
+    tmpMessages.push_back(*sei);
+#if NH_MV
+    OutputNALUnit nalu(naluType, temporalId, getLayerId() );
+#else
+    OutputNALUnit nalu(naluType, temporalId);
+#endif
+    m_seiWriter.writeSEImessages(nalu.m_Bitstream, tmpMessages, sps, false);
+    auPos = accessUnit.insert(auPos, new NALUnitEBSP(nalu));
+    auPos++;
+  }
+}
+
+Void TEncGOP::xClearSEIs(SEIMessages& seiMessages, Bool deleteMessages)
+{
+  if (deleteMessages)
+  {
+    deleteSEIs(seiMessages);
+  }
+  else
+  {
+    seiMessages.clear();
+  }
+}
+
+// write SEI messages as separate NAL units ordered
+Void TEncGOP::xWriteLeadingSEIOrdered (SEIMessages& seiMessages, SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, Bool testWrite)
+{
+  AccessUnit::iterator itNalu = accessUnit.begin();
+
+  while ( (itNalu!=accessUnit.end())&&
+    ( (*itNalu)->m_nalUnitType==NAL_UNIT_ACCESS_UNIT_DELIMITER 
+    || (*itNalu)->m_nalUnitType==NAL_UNIT_VPS
+    || (*itNalu)->m_nalUnitType==NAL_UNIT_SPS
+    || (*itNalu)->m_nalUnitType==NAL_UNIT_PPS
+    ))
+  {
+    itNalu++;
+  }
+
+  SEIMessages localMessages = seiMessages;
+  SEIMessages currentMessages;
+  
+#if ENC_DEC_TRACE
+  g_HLSTraceEnable = !testWrite;
+#endif
+  // The case that a specific SEI is not present is handled in xWriteSEI (empty list)
+
+  // Active parameter sets SEI must always be the first SEI
+  currentMessages = extractSeisByType(localMessages, SEI::ACTIVE_PARAMETER_SETS);
+  assert (currentMessages.size() <= 1);
+  xWriteSEI(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(currentMessages, !testWrite);
+  
+  // Buffering period SEI must always be following active parameter sets
+  currentMessages = extractSeisByType(localMessages, SEI::BUFFERING_PERIOD);
+  assert (currentMessages.size() <= 1);
+  xWriteSEI(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(currentMessages, !testWrite);
+
+  // Picture timing SEI must always be following buffering period
+  currentMessages = extractSeisByType(localMessages, SEI::PICTURE_TIMING);
+  assert (currentMessages.size() <= 1);
+  xWriteSEI(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(currentMessages, !testWrite);
+
+  // Decoding unit info SEI must always be following picture timing
+  if (!duInfoSeiMessages.empty())
+  {
+    currentMessages.push_back(duInfoSeiMessages.front());
+    if (!testWrite)
+    {
+      duInfoSeiMessages.pop_front();
+    }
+    xWriteSEI(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+    xClearSEIs(currentMessages, !testWrite);
+  }
+
+  // Scalable nesting SEI must always be the following DU info
+  currentMessages = extractSeisByType(localMessages, SEI::SCALABLE_NESTING);
+  xWriteSEISeparately(NAL_UNIT_PREFIX_SEI, currentMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(currentMessages, !testWrite);
+
+  // And finally everything else one by one
+  xWriteSEISeparately(NAL_UNIT_PREFIX_SEI, localMessages, accessUnit, itNalu, temporalId, sps);
+  xClearSEIs(localMessages, !testWrite);
+
+  if (!testWrite)
+  {
+    seiMessages.clear();
+  }
+}
+
+
+Void TEncGOP::xWriteLeadingSEIMessages (SEIMessages& seiMessages, SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, std::deque<DUData> &duData)
+{
+  AccessUnit testAU;
+  SEIMessages picTimingSEIs = getSeisByType(seiMessages, SEI::PICTURE_TIMING);
+  assert (picTimingSEIs.size() < 2);
+  SEIPictureTiming * picTiming = picTimingSEIs.empty() ? NULL : (SEIPictureTiming*) picTimingSEIs.front();
+
+  // test writing
+  xWriteLeadingSEIOrdered(seiMessages, duInfoSeiMessages, testAU, temporalId, sps, true);
+  // update Timing and DU info SEI
+  xUpdateDuData(testAU, duData);
+  xUpdateTimingSEI(picTiming, duData, sps);
+  xUpdateDuInfoSEI(duInfoSeiMessages, picTiming);
+  // actual writing
+  xWriteLeadingSEIOrdered(seiMessages, duInfoSeiMessages, accessUnit, temporalId, sps, false);
+
+  // testAU will automatically be cleaned up when losing scope
+}
+
+Void TEncGOP::xWriteTrailingSEIMessages (SEIMessages& seiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps)
+{
+  // Note: using accessUnit.end() works only as long as this function is called after slice coding and before EOS/EOB NAL units
+  AccessUnit::iterator pos = accessUnit.end();
+  xWriteSEISeparately(NAL_UNIT_SUFFIX_SEI, seiMessages, accessUnit, pos, temporalId, sps);
+  deleteSEIs(seiMessages);
+}
+
+Void TEncGOP::xWriteDuSEIMessages (SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, std::deque<DUData> &duData)
+{
+  const TComHRD *hrd = sps->getVuiParameters()->getHrdParameters();
+
+  if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
+  {
+    Int naluIdx = 0;
+    AccessUnit::iterator nalu = accessUnit.begin();
+
+    // skip over first DU, we have a DU info SEI there already
+    while (naluIdx < duData[0].accumNalsDU && nalu!=accessUnit.end())
+    {
+      naluIdx++;
+      nalu++;
+    }
+
+    SEIMessages::iterator duSEI = duInfoSeiMessages.begin();
+    // loop over remaining DUs
+    for (Int duIdx = 1; duIdx < duData.size(); duIdx++)
+    {
+      if (duSEI == duInfoSeiMessages.end())
+      {
+        // if the number of generated SEIs matches the number of DUs, this should not happen
+        assert (false);
+        return;
+      }
+      // write the next SEI
+      SEIMessages tmpSEI;
+      tmpSEI.push_back(*duSEI);
+      xWriteSEI(NAL_UNIT_PREFIX_SEI, tmpSEI, accessUnit, nalu, temporalId, sps);
+      // nalu points to the position after the SEI, so we have to increase the index as well
+      naluIdx++;
+      while ((naluIdx < duData[duIdx].accumNalsDU) && nalu!=accessUnit.end())
+      {
+        naluIdx++;
+        nalu++;
+      }
+      duSEI++;
+    }
+  }
+  deleteSEIs(duInfoSeiMessages);
+}
+
+Void TEncGOP::xCreateIRAPLeadingSEIMessages (SEIMessages& seiMessages, const TComSPS *sps, const TComPPS *pps)
+{
+#if NH_MV
+  OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, 0, getLayerId());
+#else
   OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-
+#endif
   if(m_pcCfg->getActiveParameterSetsSEIEnabled())
   {
-    SEIActiveParameterSets *sei = xCreateSEIActiveParameterSets (sps);
-
-    //nalu = NALUnit(NAL_UNIT_SEI); 
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-    m_activeParameterSetSEIPresentInAU = true;
+    SEIActiveParameterSets *sei = new SEIActiveParameterSets;
+    m_seiEncoder.initSEIActiveParameterSets (sei, m_pcCfg->getVPS(), sps);
+    seiMessages.push_back(sei);
   }
 
   if(m_pcCfg->getFramePackingArrangementSEIEnabled())
   {
-    SEIFramePacking *sei = xCreateSEIFramePacking ();
-
-    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-  }
+    SEIFramePacking *sei = new SEIFramePacking;
+    m_seiEncoder.initSEIFramePacking (sei, m_iNumPicCoded);
+    seiMessages.push_back(sei);
+  }
+
+  if(m_pcCfg->getSegmentedRectFramePackingArrangementSEIEnabled())
+  {
+    SEISegmentedRectFramePacking *sei = new SEISegmentedRectFramePacking;
+    m_seiEncoder.initSEISegmentedRectFramePacking(sei);
+    seiMessages.push_back(sei);
+  }
+
   if (m_pcCfg->getDisplayOrientationSEIAngle())
   {
-    SEIDisplayOrientation *sei = xCreateSEIDisplayOrientation();
-
-    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-  }
+    SEIDisplayOrientation *sei = new SEIDisplayOrientation;
+    m_seiEncoder.initSEIDisplayOrientation(sei);
+    seiMessages.push_back(sei);
+  }
+
   if(m_pcCfg->getToneMappingInfoSEIEnabled())
   {
-    SEIToneMappingInfo *sei = xCreateSEIToneMappingInfo ();
-      
-    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-  }
-#if H_MV
-  if( m_pcCfg->getSubBitstreamPropSEIEnabled() )
-  {
-    SEISubBitstreamProperty *sei = xCreateSEISubBitstreamProperty ( sps );
-
-    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
-    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
-    writeRBSPTrailingBits(nalu.m_Bitstream);
-    accessUnit.push_back(new NALUnitEBSP(nalu));
-    delete sei;
-  }
-#endif
+    SEIToneMappingInfo *sei = new SEIToneMappingInfo;
+    m_seiEncoder.initSEIToneMappingInfo (sei);
+    seiMessages.push_back(sei);
+  }
+
+  if(m_pcCfg->getTMCTSSEIEnabled())
+  {
+    SEITempMotionConstrainedTileSets *sei = new SEITempMotionConstrainedTileSets;
+    m_seiEncoder.initSEITempMotionConstrainedTileSets(sei, pps);
+    seiMessages.push_back(sei);
+  }
+
+  if(m_pcCfg->getTimeCodeSEIEnabled())
+  {
+    SEITimeCode *seiTimeCode = new SEITimeCode;
+    m_seiEncoder.initSEITimeCode(seiTimeCode);
+    seiMessages.push_back(seiTimeCode);
+  }
+
+  if(m_pcCfg->getKneeSEIEnabled())
+  {
+    SEIKneeFunctionInfo *sei = new SEIKneeFunctionInfo;
+    m_seiEncoder.initSEIKneeFunctionInfo(sei);
+    seiMessages.push_back(sei);
+  }
+    
+  if(m_pcCfg->getMasteringDisplaySEI().colourVolumeSEIEnabled)
+  {
+    const TComSEIMasteringDisplay &seiCfg=m_pcCfg->getMasteringDisplaySEI();
+    SEIMasteringDisplayColourVolume *sei = new SEIMasteringDisplayColourVolume;
+    sei->values = seiCfg;
+    seiMessages.push_back(sei);
+  }
+
+#if NH_MV
+  if( m_pcCfg->getSubBitstreamPropSEIEnabled() && ( getLayerId() == 0 ) )
+  {
+    SEISubBitstreamProperty *sei = new SEISubBitstreamProperty;
+    m_seiEncoder.initSEISubBitstreamProperty( sei, sps );   
+    seiMessages.push_back(sei);
+  }
+#endif
+}
+
+Void TEncGOP::xCreatePerPictureSEIMessages (Int picInGOP, SEIMessages& seiMessages, SEIMessages& nestedSeiMessages, TComSlice *slice)
+{
+  if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( slice->getSliceType() == I_SLICE ) &&
+    ( slice->getSPS()->getVuiParametersPresentFlag() ) &&
+    ( ( slice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
+    || ( slice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
+  {
+    SEIBufferingPeriod *bufferingPeriodSEI = new SEIBufferingPeriod();
+    m_seiEncoder.initSEIBufferingPeriod(bufferingPeriodSEI, slice);
+    seiMessages.push_back(bufferingPeriodSEI);
+    m_bufferingPeriodSEIPresentInAU = true;
+
+    if (m_pcCfg->getScalableNestingSEIEnabled())
+    {
+      SEIBufferingPeriod *bufferingPeriodSEIcopy = new SEIBufferingPeriod();
+      bufferingPeriodSEI->copyTo(*bufferingPeriodSEIcopy);
+      nestedSeiMessages.push_back(bufferingPeriodSEIcopy);
+    }
+  }
+
+  if (picInGOP ==0 && m_pcCfg->getSOPDescriptionSEIEnabled() ) // write SOP description SEI (if enabled) at the beginning of GOP
+  {
+    SEISOPDescription* sopDescriptionSEI = new SEISOPDescription();
+    m_seiEncoder.initSEISOPDescription(sopDescriptionSEI, slice, picInGOP, m_iLastIDR, m_iGopSize);
+    seiMessages.push_back(sopDescriptionSEI);
+  }
+
+  if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( slice->getSliceType() == I_SLICE ) )
+  {
+    if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !slice->getRapPicFlag() )
+    {
+      // Gradual decoding refresh SEI
+      SEIGradualDecodingRefreshInfo *gradualDecodingRefreshInfoSEI = new SEIGradualDecodingRefreshInfo();
+      gradualDecodingRefreshInfoSEI->m_gdrForegroundFlag = true; // Indicating all "foreground"
+      seiMessages.push_back(gradualDecodingRefreshInfoSEI);
+    }
+    // Recovery point SEI
+    SEIRecoveryPoint *recoveryPointSEI = new SEIRecoveryPoint();
+    m_seiEncoder.initSEIRecoveryPoint(recoveryPointSEI, slice);
+    seiMessages.push_back(recoveryPointSEI);
+  }
+  if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
+  {
+    SEITemporalLevel0Index *temporalLevel0IndexSEI = new SEITemporalLevel0Index();
+    m_seiEncoder.initTemporalLevel0IndexSEI(temporalLevel0IndexSEI, slice);
+    seiMessages.push_back(temporalLevel0IndexSEI);
+  }
+
+  if(slice->getSPS()->getVuiParametersPresentFlag() && m_pcCfg->getChromaSamplingFilterHintEnabled() && ( slice->getSliceType() == I_SLICE ))
+  {
+    SEIChromaSamplingFilterHint *seiChromaSamplingFilterHint = new SEIChromaSamplingFilterHint;
+    m_seiEncoder.initSEIChromaSamplingFilterHint(seiChromaSamplingFilterHint, m_pcCfg->getChromaSamplingHorFilterIdc(), m_pcCfg->getChromaSamplingVerFilterIdc());
+    seiMessages.push_back(seiChromaSamplingFilterHint);
+  }
+
+  if( m_pcEncTop->getNoDisplaySEITLayer() && ( slice->getTLayer() >= m_pcEncTop->getNoDisplaySEITLayer() ) )
+  {
+    SEINoDisplay *seiNoDisplay = new SEINoDisplay;
+    seiNoDisplay->m_noDisplay = true;
+    seiMessages.push_back(seiNoDisplay);
+  }
+}
+
+Void TEncGOP::xCreateScalableNestingSEI (SEIMessages& seiMessages, SEIMessages& nestedSeiMessages)
+{
+  SEIMessages tmpMessages;
+  while (!nestedSeiMessages.empty())
+  {
+    SEI* sei=nestedSeiMessages.front();
+    nestedSeiMessages.pop_front();
+    tmpMessages.push_back(sei);
+    SEIScalableNesting *nestingSEI = new SEIScalableNesting();
+    m_seiEncoder.initSEIScalableNesting(nestingSEI, tmpMessages);
+    seiMessages.push_back(nestingSEI);
+    tmpMessages.clear();
+  }
+}
+
+Void TEncGOP::xCreatePictureTimingSEI  (Int IRAPGOPid, SEIMessages& seiMessages, SEIMessages& nestedSeiMessages, SEIMessages& duInfoSeiMessages, TComSlice *slice, Bool isField, std::deque<DUData> &duData)
+{
+  Int picSptDpbOutputDuDelay = 0;
+#if !NH_MV
+  SEIPictureTiming *pictureTimingSEI = new SEIPictureTiming();
+#endif
+
+  const TComVUI *vui = slice->getSPS()->getVuiParameters();
+  const TComHRD *hrd = vui->getHrdParameters();
+
+  // update decoding unit parameters
+  if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
+    ( slice->getSPS()->getVuiParametersPresentFlag() ) &&
+    (  hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() ) )
+  {
+#if NH_MV
+    // Preliminary fix to avoid memory leak.
+    SEIPictureTiming *pictureTimingSEI = new SEIPictureTiming();
+#endif
+
+    // DU parameters
+    if( hrd->getSubPicCpbParamsPresentFlag() )
+    {
+      UInt numDU = (UInt) duData.size();
+      pictureTimingSEI->m_numDecodingUnitsMinus1     = ( numDU - 1 );
+      pictureTimingSEI->m_duCommonCpbRemovalDelayFlag = false;
+      pictureTimingSEI->m_numNalusInDuMinus1.resize( numDU );
+      pictureTimingSEI->m_duCpbRemovalDelayMinus1.resize( numDU );
+    }
+    pictureTimingSEI->m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<Double>(hrd->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
+    pictureTimingSEI->m_picDpbOutputDelay = slice->getSPS()->getNumReorderPics(slice->getSPS()->getMaxTLayers()-1) + slice->getPOC() - m_totalCoded;
+    if(m_pcCfg->getEfficientFieldIRAPEnabled() && IRAPGOPid > 0 && IRAPGOPid < m_iGopSize)
+    {
+      // if pictures have been swapped there is likely one more picture delay on their tid. Very rough approximation
+      pictureTimingSEI->m_picDpbOutputDelay ++;
+    }
+    Int factor = hrd->getTickDivisorMinus2() + 2;
+    pictureTimingSEI->m_picDpbOutputDuDelay = factor * pictureTimingSEI->m_picDpbOutputDelay;
+    if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
+    {
+      picSptDpbOutputDuDelay = factor * pictureTimingSEI->m_picDpbOutputDelay;
+    }
+    if (m_bufferingPeriodSEIPresentInAU)
+    {
+      m_lastBPSEI = m_totalCoded;
+    }
+
+    if( hrd->getSubPicCpbParamsPresentFlag() )
+    {
+      Int i;
+      UInt64 ui64Tmp;
+      UInt uiPrev = 0;
+      UInt numDU = ( pictureTimingSEI->m_numDecodingUnitsMinus1 + 1 );
+      std::vector<UInt> &rDuCpbRemovalDelayMinus1 = pictureTimingSEI->m_duCpbRemovalDelayMinus1;
+      UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
+
+      for( i = 0; i < numDU; i ++ )
+      {
+        pictureTimingSEI->m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( duData[i].accumNalsDU - 1 ) : ( duData[i].accumNalsDU- duData[i-1].accumNalsDU - 1 );
+      }
+
+      if( numDU == 1 )
+      {
+        rDuCpbRemovalDelayMinus1[ 0 ] = 0; /* don't care */
+      }
+      else
+      {
+        rDuCpbRemovalDelayMinus1[ numDU - 1 ] = 0;/* by definition */
+        UInt tmp = 0;
+        UInt accum = 0;
+
+        for( i = ( numDU - 2 ); i >= 0; i -- )
+        {
+          ui64Tmp = ( ( ( duData[numDU - 1].accumBitsDU  - duData[i].accumBitsDU ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+          if( (UInt)ui64Tmp > maxDiff )
+          {
+            tmp ++;
+          }
+        }
+        uiPrev = 0;
+
+        UInt flag = 0;
+        for( i = ( numDU - 2 ); i >= 0; i -- )
+        {
+          flag = 0;
+          ui64Tmp = ( ( ( duData[numDU - 1].accumBitsDU  - duData[i].accumBitsDU ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+
+          if( (UInt)ui64Tmp > maxDiff )
+          {
+            if(uiPrev >= maxDiff - tmp)
+            {
+              ui64Tmp = uiPrev + 1;
+              flag = 1;
+            }
+            else                            ui64Tmp = maxDiff - tmp + 1;
+          }
+          rDuCpbRemovalDelayMinus1[ i ] = (UInt)ui64Tmp - uiPrev - 1;
+          if( (Int)rDuCpbRemovalDelayMinus1[ i ] < 0 )
+          {
+            rDuCpbRemovalDelayMinus1[ i ] = 0;
+          }
+          else if (tmp > 0 && flag == 1)
+          {
+            tmp --;
+          }
+          accum += rDuCpbRemovalDelayMinus1[ i ] + 1;
+          uiPrev = accum;
+        }
+      }
+    }
+    
+    if( m_pcCfg->getPictureTimingSEIEnabled() )
+    {
+      pictureTimingSEI->m_picStruct = (isField && slice->getPic()->isTopField())? 1 : isField? 2 : 0;
+      seiMessages.push_back(pictureTimingSEI);
+
+      if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
+      {
+          SEIPictureTiming *pictureTimingSEIcopy = new SEIPictureTiming();
+          pictureTimingSEI->copyTo(*pictureTimingSEIcopy);
+          nestedSeiMessages.push_back(pictureTimingSEIcopy);
+        }
+    }
+
+    if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
+    {
+      for( Int i = 0; i < ( pictureTimingSEI->m_numDecodingUnitsMinus1 + 1 ); i ++ )
+      {
+        SEIDecodingUnitInfo *duInfoSEI = new SEIDecodingUnitInfo();
+        duInfoSEI->m_decodingUnitIdx = i;
+        duInfoSEI->m_duSptCpbRemovalDelay = pictureTimingSEI->m_duCpbRemovalDelayMinus1[i] + 1;
+        duInfoSEI->m_dpbOutputDuDelayPresentFlag = false;
+        duInfoSEI->m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
+
+        duInfoSeiMessages.push_back(duInfoSEI);
+      }
+    }
+  }
+}
+
+Void TEncGOP::xUpdateDuData(AccessUnit &testAU, std::deque<DUData> &duData)
+{
+  if (duData.empty())
+  {
+    return;
+  }
+  // fix first 
+  UInt numNalUnits = (UInt)testAU.size();
+  UInt numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = testAU.begin(); it != testAU.end(); it++)
+  {
+    numRBSPBytes += UInt((*it)->m_nalUnitData.str().size());
+  }
+  duData[0].accumBitsDU += ( numRBSPBytes << 3 );
+  duData[0].accumNalsDU += numNalUnits;
+
+  // adapt cumulative sums for all following DUs
+  // and add one DU info SEI, if enabled
+  for (Int i=1; i<duData.size(); i++)
+  {
+    if (m_pcCfg->getDecodingUnitInfoSEIEnabled())
+    {
+      numNalUnits  += 1;
+      numRBSPBytes += ( 5 << 3 );
+    }
+    duData[i].accumBitsDU += numRBSPBytes; // probably around 5 bytes
+    duData[i].accumNalsDU += numNalUnits;
+  }
+
+  // The last DU may have a trailing SEI
+  if (m_pcCfg->getDecodedPictureHashSEIEnabled())
+  {
+    duData.back().accumBitsDU += ( 20 << 3 ); // probably around 20 bytes - should be further adjusted, e.g. by type
+    duData.back().accumNalsDU += 1;
+  }
+
+}
+Void TEncGOP::xUpdateTimingSEI(SEIPictureTiming *pictureTimingSEI, std::deque<DUData> &duData, const TComSPS *sps)
+{
+  if (!pictureTimingSEI)
+  {
+    return;
+  }
+  const TComVUI *vui = sps->getVuiParameters();
+  const TComHRD *hrd = vui->getHrdParameters();
+  if( hrd->getSubPicCpbParamsPresentFlag() )
+  {
+    Int i;
+    UInt64 ui64Tmp;
+    UInt uiPrev = 0;
+    UInt numDU = ( pictureTimingSEI->m_numDecodingUnitsMinus1 + 1 );
+    std::vector<UInt> &rDuCpbRemovalDelayMinus1 = pictureTimingSEI->m_duCpbRemovalDelayMinus1;
+    UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
+
+    for( i = 0; i < numDU; i ++ )
+    {
+      pictureTimingSEI->m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( duData[i].accumNalsDU - 1 ) : ( duData[i].accumNalsDU- duData[i-1].accumNalsDU - 1 );
+    }
+
+    if( numDU == 1 )
+    {
+      rDuCpbRemovalDelayMinus1[ 0 ] = 0; /* don't care */
+    }
+    else
+    {
+      rDuCpbRemovalDelayMinus1[ numDU - 1 ] = 0;/* by definition */
+      UInt tmp = 0;
+      UInt accum = 0;
+
+      for( i = ( numDU - 2 ); i >= 0; i -- )
+      {
+        ui64Tmp = ( ( ( duData[numDU - 1].accumBitsDU  - duData[i].accumBitsDU ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+        if( (UInt)ui64Tmp > maxDiff )
+        {
+          tmp ++;
+        }
+      }
+      uiPrev = 0;
+
+      UInt flag = 0;
+      for( i = ( numDU - 2 ); i >= 0; i -- )
+      {
+        flag = 0;
+        ui64Tmp = ( ( ( duData[numDU - 1].accumBitsDU  - duData[i].accumBitsDU ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+
+        if( (UInt)ui64Tmp > maxDiff )
+        {
+          if(uiPrev >= maxDiff - tmp)
+          {
+            ui64Tmp = uiPrev + 1;
+            flag = 1;
+          }
+          else                            ui64Tmp = maxDiff - tmp + 1;
+        }
+        rDuCpbRemovalDelayMinus1[ i ] = (UInt)ui64Tmp - uiPrev - 1;
+        if( (Int)rDuCpbRemovalDelayMinus1[ i ] < 0 )
+        {
+          rDuCpbRemovalDelayMinus1[ i ] = 0;
+        }
+        else if (tmp > 0 && flag == 1)
+        {
+          tmp --;
+        }
+        accum += rDuCpbRemovalDelayMinus1[ i ] + 1;
+        uiPrev = accum;
+      }
+    }
+  }
+}
+Void TEncGOP::xUpdateDuInfoSEI(SEIMessages &duInfoSeiMessages, SEIPictureTiming *pictureTimingSEI)
+{
+  if (duInfoSeiMessages.empty() || (pictureTimingSEI == NULL))
+  {
+    return;
+  }
+
+  Int i=0;
+
+  for (SEIMessages::iterator du = duInfoSeiMessages.begin(); du!= duInfoSeiMessages.end(); du++)
+  {
+    SEIDecodingUnitInfo *duInfoSEI = (SEIDecodingUnitInfo*) (*du);
+    duInfoSEI->m_decodingUnitIdx = i;
+    duInfoSEI->m_duSptCpbRemovalDelay = pictureTimingSEI->m_duCpbRemovalDelayMinus1[i] + 1;
+    duInfoSEI->m_dpbOutputDuDelayPresentFlag = false;
+    i++;
+  }
+}
+
+static Void
+cabac_zero_word_padding(TComSlice *const pcSlice, TComPic *const pcPic, const std::size_t binCountsInNalUnits, const std::size_t numBytesInVclNalUnits, std::ostringstream &nalUnitData, const Bool cabacZeroWordPaddingEnabled)
+{
+  const TComSPS &sps=*(pcSlice->getSPS());
+  const Int log2subWidthCxsubHeightC = (pcPic->getComponentScaleX(COMPONENT_Cb)+pcPic->getComponentScaleY(COMPONENT_Cb));
+  const Int minCuWidth  = pcPic->getMinCUWidth();
+  const Int minCuHeight = pcPic->getMinCUHeight();
+  const Int paddedWidth = ((sps.getPicWidthInLumaSamples()  + minCuWidth  - 1) / minCuWidth) * minCuWidth;
+  const Int paddedHeight= ((sps.getPicHeightInLumaSamples() + minCuHeight - 1) / minCuHeight) * minCuHeight;
+  const Int rawBits = paddedWidth * paddedHeight *
+                         (sps.getBitDepth(CHANNEL_TYPE_LUMA) + 2*(sps.getBitDepth(CHANNEL_TYPE_CHROMA)>>log2subWidthCxsubHeightC));
+  const std::size_t threshold = (32/3)*numBytesInVclNalUnits + (rawBits/32);
+  if (binCountsInNalUnits >= threshold)
+  {
+    // need to add additional cabac zero words (each one accounts for 3 bytes (=00 00 03)) to increase numBytesInVclNalUnits
+    const std::size_t targetNumBytesInVclNalUnits = ((binCountsInNalUnits - (rawBits/32))*3+31)/32;
+
+    if (targetNumBytesInVclNalUnits>numBytesInVclNalUnits) // It should be!
+    {
+      const std::size_t numberOfAdditionalBytesNeeded=targetNumBytesInVclNalUnits - numBytesInVclNalUnits;
+      const std::size_t numberOfAdditionalCabacZeroWords=(numberOfAdditionalBytesNeeded+2)/3;
+      const std::size_t numberOfAdditionalCabacZeroBytes=numberOfAdditionalCabacZeroWords*3;
+      if (cabacZeroWordPaddingEnabled)
+      {
+        std::vector<Char> zeroBytesPadding(numberOfAdditionalCabacZeroBytes, Char(0));
+        for(std::size_t i=0; i<numberOfAdditionalCabacZeroWords; i++)
+        {
+          zeroBytesPadding[i*3+2]=3;  // 00 00 03
+        }
+        nalUnitData.write(&(zeroBytesPadding[0]), numberOfAdditionalCabacZeroBytes);
+        printf("Adding %d bytes of padding\n", UInt(numberOfAdditionalCabacZeroWords*3));
+      }
+      else
+      {
+        printf("Standard would normally require adding %d bytes of padding\n", UInt(numberOfAdditionalCabacZeroWords*3));
+      }
+    }
+  }
+}
+
+class EfficientFieldIRAPMapping
+{
+  private:
+    Int  IRAPGOPid;
+    Bool IRAPtoReorder;
+    Bool swapIRAPForward;
+
+  public:
+    EfficientFieldIRAPMapping() :
+      IRAPGOPid(-1),
+      IRAPtoReorder(false),
+      swapIRAPForward(false)
+    { }
+
+    Void initialize(const Bool isField, const Int gopSize, const Int POCLast, const Int numPicRcvd, const Int lastIDR, TEncGOP *pEncGop, TEncCfg *pCfg);
+
+    Int adjustGOPid(const Int gopID);
+    Int restoreGOPid(const Int gopID);
+    Int GetIRAPGOPid() const { return IRAPGOPid; }
+};
+
+Void EfficientFieldIRAPMapping::initialize(const Bool isField, const Int gopSize, const Int POCLast, const Int numPicRcvd, const Int lastIDR, TEncGOP *pEncGop, TEncCfg *pCfg )
+{
+  if(isField)
+  {
+    Int pocCurr;
+    for ( Int iGOPid=0; iGOPid < gopSize; iGOPid++ )
+    {
+      // determine actual POC
+      if(POCLast == 0) //case first frame or first top field
+      {
+        pocCurr=0;
+      }
+      else if(POCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+      {
+        pocCurr = 1;
+      }
+      else
+      {
+        pocCurr = POCLast - numPicRcvd + pCfg->getGOPEntry(iGOPid).m_POC - isField;
+      }
+
+      // check if POC corresponds to IRAP
+      NalUnitType tmpUnitType = pEncGop->getNalUnitType(pocCurr, lastIDR, isField);
+      if(tmpUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && tmpUnitType <= NAL_UNIT_CODED_SLICE_CRA) // if picture is an IRAP
+      {
+        if(pocCurr%2 == 0 && iGOPid < gopSize-1 && pCfg->getGOPEntry(iGOPid).m_POC == pCfg->getGOPEntry(iGOPid+1).m_POC-1)
+        { // if top field and following picture in enc order is associated bottom field
+          IRAPGOPid = iGOPid;
+          IRAPtoReorder = true;
+          swapIRAPForward = true; 
+          break;
+        }
+        if(pocCurr%2 != 0 && iGOPid > 0 && pCfg->getGOPEntry(iGOPid).m_POC == pCfg->getGOPEntry(iGOPid-1).m_POC+1)
+        {
+          // if picture is an IRAP remember to process it first
+          IRAPGOPid = iGOPid;
+          IRAPtoReorder = true;
+          swapIRAPForward = false; 
+          break;
+        }
+      }
+    }
+  }
+}
+
+Int EfficientFieldIRAPMapping::adjustGOPid(const Int GOPid)
+{
+  if(IRAPtoReorder)
+  {
+    if(swapIRAPForward)
+    {
+      if(GOPid == IRAPGOPid)
+      {
+        return IRAPGOPid +1;
+      }
+      else if(GOPid == IRAPGOPid +1)
+      {
+        return IRAPGOPid;
+      }
+    }
+    else
+    {
+      if(GOPid == IRAPGOPid -1)
+      {
+        return IRAPGOPid;
+      }
+      else if(GOPid == IRAPGOPid)
+      {
+        return IRAPGOPid -1;
+      }
+    }
+  }
+  return GOPid;
+}
+
+Int EfficientFieldIRAPMapping::restoreGOPid(const Int GOPid)
+{
+  if(IRAPtoReorder)
+  {
+    if(swapIRAPForward)
+    {
+      if(GOPid == IRAPGOPid)
+      {
+        IRAPtoReorder = false;
+        return IRAPGOPid +1;
+      }
+      else if(GOPid == IRAPGOPid +1)
+      {
+        return GOPid -1;
+      }
+    }
+    else
+    {
+      if(GOPid == IRAPGOPid)
+      {
+        return IRAPGOPid -1;
+      }
+      else if(GOPid == IRAPGOPid -1)
+      {
+        IRAPtoReorder = false;
+        return IRAPGOPid;
+      }
+    }
+  }
+  return GOPid;
+}
+
+
+static UInt calculateCollocatedFromL1Flag(TEncCfg *pCfg, const Int GOPid, const Int gopSize)
+{
+  Int iCloseLeft=1, iCloseRight=-1;
+  for(Int i = 0; i<pCfg->getGOPEntry(GOPid).m_numRefPics; i++)
+  {
+    Int iRef = pCfg->getGOPEntry(GOPid).m_referencePics[i];
+    if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
+    {
+      iCloseRight=iRef;
+    }
+    else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
+    {
+      iCloseLeft=iRef;
+    }
+  }
+  if(iCloseRight>-1)
+  {
+    iCloseRight=iCloseRight+pCfg->getGOPEntry(GOPid).m_POC-1;
+  }
+  if(iCloseLeft<1)
+  {
+    iCloseLeft=iCloseLeft+pCfg->getGOPEntry(GOPid).m_POC-1;
+    while(iCloseLeft<0)
+    {
+      iCloseLeft+=gopSize;
+    }
+  }
+  Int iLeftQP=0, iRightQP=0;
+  for(Int i=0; i<gopSize; i++)
+  {
+    if(pCfg->getGOPEntry(i).m_POC==(iCloseLeft%gopSize)+1)
+    {
+      iLeftQP= pCfg->getGOPEntry(i).m_QPOffset;
+    }
+    if (pCfg->getGOPEntry(i).m_POC==(iCloseRight%gopSize)+1)
+    {
+      iRightQP=pCfg->getGOPEntry(i).m_QPOffset;
+    }
+  }
+  if(iCloseRight>-1&&iRightQP<iLeftQP)
+  {
+    return 0;
+  }
+  else
+  {
+    return 1;
+  }
 }
 
@@ -392,18 +1058,24 @@
 // Public member functions
 // ====================================================================================================================
-#if H_MV
+#if NH_MV
 Void TEncGOP::initGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
 {
-  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, false );
+  xInitGOP( iPOCLast, iNumPicRcvd, false );
   m_iNumPicCoded = 0;
 }
 #endif
-#if H_MV
-Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, bool isField, bool isTff)
+#if NH_MV
+Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, 
+                                TComList<TComPicYuv*>& rcListPicYuvRecOut,  std::list<AccessUnit>& accessUnitsInGOP, 
+                                Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Int iGOPid )
 #else
-Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, bool isField, bool isTff)
-#endif
-{
-  TComPic*        pcPic;
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic,
+                           TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP,
+                           Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE )
+#endif
+{
+  // TODO: Split this function up.
+
+  TComPic*        pcPic = NULL;
   TComPicYuv*     pcPicYuvRecOut;
   TComSlice*      pcSlice;
@@ -411,160 +1083,46 @@
   pcBitstreamRedirect = new TComOutputBitstream;
   AccessUnit::iterator  itLocationToPushSliceHeaderNALU; // used to store location where NALU containing slice header is to be inserted
-  UInt                  uiOneBitstreamPerSliceLength = 0;
-  TEncSbac* pcSbacCoders = NULL;
-  TComOutputBitstream* pcSubstreamsOut = NULL;
-
-#if !H_MV
-  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, isField );
-
-  
+#if !NH_MV
+  xInitGOP( iPOCLast, iNumPicRcvd, isField );
+#endif
+
   m_iNumPicCoded = 0;
-#endif
-  SEIPictureTiming pictureTimingSEI;
-  Bool writeSOP = m_pcCfg->getSOPDescriptionSEIEnabled();
-  // Initialize Scalable Nesting SEI with single layer values
-  SEIScalableNesting scalableNestingSEI;
-  scalableNestingSEI.m_bitStreamSubsetFlag           = 1;      // If the nested SEI messages are picture buffereing SEI mesages, picure timing SEI messages or sub-picture timing SEI messages, bitstream_subset_flag shall be equal to 1
-  scalableNestingSEI.m_nestingOpFlag                 = 0;
-  scalableNestingSEI.m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
-  scalableNestingSEI.m_allLayersFlag                 = 0;
-  scalableNestingSEI.m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
-  scalableNestingSEI.m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
-  scalableNestingSEI.m_nestingLayerId[0]             = 0;
-  scalableNestingSEI.m_callerOwnsSEIs                = true;
-  Int picSptDpbOutputDuDelay = 0;
-  UInt *accumBitsDU = NULL;
-  UInt *accumNalsDU = NULL;
+  SEIMessages leadingSeiMessages;
+  SEIMessages nestedSeiMessages;
+  SEIMessages duInfoSeiMessages;
+  SEIMessages trailingSeiMessages;
+  std::deque<DUData> duData;
   SEIDecodingUnitInfo decodingUnitInfoSEI;
-#if EFFICIENT_FIELD_IRAP
-  Int IRAPGOPid = -1;
-  Bool IRAPtoReorder = false;
-  Bool swapIRAPForward = false;
-  if(isField)
-  {
-    Int pocCurr;
-#if !H_MV
-    for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
-#endif
-    {
-      // determine actual POC
-      if(iPOCLast == 0) //case first frame or first top field
-      {
-        pocCurr=0;
-      }
-      else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
-      {
-        pocCurr = 1;
-      }
-      else
-      {
-        pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
-      }
-
-      // check if POC corresponds to IRAP
-      NalUnitType tmpUnitType = getNalUnitType(pocCurr, m_iLastIDR, isField);
-      if(tmpUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && tmpUnitType <= NAL_UNIT_CODED_SLICE_CRA) // if picture is an IRAP
-      {
-        if(pocCurr%2 == 0 && iGOPid < m_iGopSize-1 && m_pcCfg->getGOPEntry(iGOPid).m_POC == m_pcCfg->getGOPEntry(iGOPid+1).m_POC-1)
-        { // if top field and following picture in enc order is associated bottom field
-          IRAPGOPid = iGOPid;
-          IRAPtoReorder = true;
-          swapIRAPForward = true; 
-          break;
-        }
-        if(pocCurr%2 != 0 && iGOPid > 0 && m_pcCfg->getGOPEntry(iGOPid).m_POC == m_pcCfg->getGOPEntry(iGOPid-1).m_POC+1)
-        {
-          // if picture is an IRAP remember to process it first
-          IRAPGOPid = iGOPid;
-          IRAPtoReorder = true;
-          swapIRAPForward = false; 
-          break;
-        }
-      }
-    }
-  }
-#endif
-#if !H_MV
+
+  EfficientFieldIRAPMapping effFieldIRAPMap;
+  if (m_pcCfg->getEfficientFieldIRAPEnabled())
+  {
+   effFieldIRAPMap.initialize(isField, m_iGopSize, iPOCLast, iNumPicRcvd, m_iLastIDR, this, m_pcCfg);
+  }
+
+  // reset flag indicating whether pictures have been encoded
+#if !NH_MV
   for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
 #endif
   {
-#if EFFICIENT_FIELD_IRAP
-    if(IRAPtoReorder)
-    {
-      if(swapIRAPForward)
-      {
-        if(iGOPid == IRAPGOPid)
-        {
-          iGOPid = IRAPGOPid +1;
-        }
-        else if(iGOPid == IRAPGOPid +1)
-        {
-          iGOPid = IRAPGOPid;
-        }
-      }
-      else
-      {
-        if(iGOPid == IRAPGOPid -1)
-        {
-          iGOPid = IRAPGOPid;
-        }
-        else if(iGOPid == IRAPGOPid)
-        {
-          iGOPid = IRAPGOPid -1;
-        }
-      }
-    }
-#endif
-    UInt uiColDir = 1;
+    m_pcCfg->setEncodedFlag(iGOPid, false);
+  }
+#if !NH_MV
+  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+#endif
+  {
+    if (m_pcCfg->getEfficientFieldIRAPEnabled())
+    {
+      iGOPid=effFieldIRAPMap.adjustGOPid(iGOPid);
+    }
+
     //-- For time output for each slice
-    long iBeforeTime = clock();
-
-    //select uiColDir
-    Int iCloseLeft=1, iCloseRight=-1;
-    for(Int i = 0; i<m_pcCfg->getGOPEntry(iGOPid).m_numRefPics; i++) 
-    {
-      Int iRef = m_pcCfg->getGOPEntry(iGOPid).m_referencePics[i];
-      if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
-      {
-        iCloseRight=iRef;
-      }
-      else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
-      {
-        iCloseLeft=iRef;
-      }
-    }
-    if(iCloseRight>-1)
-    {
-      iCloseRight=iCloseRight+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
-    }
-    if(iCloseLeft<1) 
-    {
-      iCloseLeft=iCloseLeft+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
-      while(iCloseLeft<0)
-      {
-        iCloseLeft+=m_iGopSize;
-      }
-    }
-    Int iLeftQP=0, iRightQP=0;
-    for(Int i=0; i<m_iGopSize; i++)
-    {
-      if(m_pcCfg->getGOPEntry(i).m_POC==(iCloseLeft%m_iGopSize)+1)
-      {
-        iLeftQP= m_pcCfg->getGOPEntry(i).m_QPOffset;
-      }
-      if (m_pcCfg->getGOPEntry(i).m_POC==(iCloseRight%m_iGopSize)+1)
-      {
-        iRightQP=m_pcCfg->getGOPEntry(i).m_QPOffset;
-      }
-    }
-    if(iCloseRight>-1&&iRightQP<iLeftQP)
-    {
-      uiColDir=0;
-    }
+    clock_t iBeforeTime = clock();
+
+    UInt uiColDir = calculateCollocatedFromL1Flag(m_pcCfg, iGOPid, m_iGopSize);
 
     /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
     Int iTimeOffset;
     Int pocCurr;
-    
     if(iPOCLast == 0) //case first frame or first top field
     {
@@ -579,39 +1137,15 @@
     else
     {
-      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
+      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - ((isField && m_iGopSize>1) ? 1:0);
       iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
     }
+
     if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
     {
-#if EFFICIENT_FIELD_IRAP
-      if(IRAPtoReorder)
-      {
-        if(swapIRAPForward)
-        {
-          if(iGOPid == IRAPGOPid)
-          {
-            iGOPid = IRAPGOPid +1;
-            IRAPtoReorder = false;
-          }
-          else if(iGOPid == IRAPGOPid +1)
-          {
-            iGOPid --;
-          }
-        }
-        else
-        {
-          if(iGOPid == IRAPGOPid)
-          {
-            iGOPid = IRAPGOPid -1;
-          }
-          else if(iGOPid == IRAPGOPid -1)
-          {
-            iGOPid = IRAPGOPid;
-            IRAPtoReorder = false;
-          }
-        }
-      }
-#endif
-#if H_MV
+      if (m_pcCfg->getEfficientFieldIRAPEnabled())
+      {
+        iGOPid=effFieldIRAPMap.restoreGOPid(iGOPid);
+      }
+#if NH_MV
       delete pcBitstreamRedirect;
       return;
@@ -624,23 +1158,21 @@
     {
       m_iLastIDR = pocCurr;
-    }        
+    }
     // start a new access unit: create an entry in the list of output access units
     accessUnitsInGOP.push_back(AccessUnit());
     AccessUnit& accessUnit = accessUnitsInGOP.back();
-    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField);
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField );
 
     //  Slice data initialization
     pcPic->clearSliceBuffer();
-    assert(pcPic->getNumAllocatedSlice() == 1);
+    pcPic->allocateNewSlice();
     m_pcSliceEncoder->setSliceIdx(0);
     pcPic->setCurrSliceIdx(0);
-
-
-#if H_MV
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId(), isField  );     
+#if NH_MV
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iGOPid, pcSlice, m_pcEncTop->getVPS(), getLayerId(), isField  );     
 #else
-    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), isField  );
-#endif
-    
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iGOPid, pcSlice, isField );
+#endif
+
     //Set Frame/Field coding
     pcSlice->getPic()->setField(isField);
@@ -648,9 +1180,9 @@
     pcSlice->setLastIDR(m_iLastIDR);
     pcSlice->setSliceIdx(0);
-#if H_MV
+#if NH_MV
     pcSlice->setRefPicSetInterLayer ( &m_refPicSetInterLayer0, &m_refPicSetInterLayer1 ); 
     pcPic  ->setLayerId     ( getLayerId()   );
     pcPic  ->setViewId      ( getViewId()    );    
-#if !H_3D
+#if !NH_3D
     pcSlice->setLayerId     ( getLayerId() );
     pcSlice->setViewId      ( getViewId()  );    
@@ -664,39 +1196,5 @@
     //set default slice level flag to the same as SPS level flag
     pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
-    pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
-    if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
-    {
-      m_pcEncTop->getTrQuant()->setFlatScalingList();
-      m_pcEncTop->getTrQuant()->setUseScalingList(false);
-      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
-      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
-    }
-    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
-    {
-      pcSlice->setDefaultScalingList ();
-      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
-      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
-      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
-      m_pcEncTop->getTrQuant()->setUseScalingList(true);
-    }
-    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
-    {
-      if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
-      {
-        pcSlice->setDefaultScalingList ();
-      }
-      pcSlice->getScalingList()->checkDcOfMatrix();
-      m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
-      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
-      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
-      m_pcEncTop->getTrQuant()->setUseScalingList(true);
-    }
-    else
-    {
-      printf("error : ScalingList == %d no support\n",m_pcEncTop->getUseScalingListId());
-      assert(0);
-    }
-
-#if H_MV
+#if NH_MV
     // Set the nal unit type
     pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
@@ -718,4 +1216,5 @@
     }
 #else
+
     if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
     {
@@ -747,7 +1246,6 @@
       }
     }
-
-#if EFFICIENT_FIELD_IRAP
-#if FIX1172
+    if (m_pcCfg->getEfficientFieldIRAPEnabled())
+    {
     if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
@@ -762,13 +1260,11 @@
     pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
     pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
-#endif
-#endif
-    // Do decoding refresh marking if any 
-    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+    }
+    // Do decoding refresh marking if any
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic, m_pcCfg->getEfficientFieldIRAPEnabled());
     m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
     pcSlice->getRPS()->setNumberOfLongtermPictures(0);
-#if EFFICIENT_FIELD_IRAP
-#else
-#if FIX1172
+    if (!m_pcCfg->getEfficientFieldIRAPEnabled())
+    {
     if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
@@ -783,22 +1279,12 @@
     pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
     pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
-#endif
-#endif
-
-#if ALLOW_RECOVERY_POINT_AS_RAP
+    }
     if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false, m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3) != 0) || (pcSlice->isIRAP()) 
-#if EFFICIENT_FIELD_IRAP
-      || (isField && pcSlice->getAssociatedIRAPType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getAssociatedIRAPType() <= NAL_UNIT_CODED_SLICE_CRA && pcSlice->getAssociatedIRAPPOC() == pcSlice->getPOC()+1)
-#endif
+      || (m_pcCfg->getEfficientFieldIRAPEnabled() && isField && pcSlice->getAssociatedIRAPType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getAssociatedIRAPType() <= NAL_UNIT_CODED_SLICE_CRA && pcSlice->getAssociatedIRAPPOC() == pcSlice->getPOC()+1)
       )
     {
-      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP(), m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3);
-    }
-#else
-    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
-    {
-      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
-    }
-#endif
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP(), m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3, m_pcCfg->getEfficientFieldIRAPEnabled());
+    }
+
     pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
 
@@ -827,10 +1313,10 @@
         {
           Int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
-          if(lTid==pcSlice->getTLayer()) 
+          if(lTid==pcSlice->getTLayer())
           {
-            TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
+            const TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
             for(Int jj=0;jj<nRPS->getNumberOfPictures();jj++)
             {
-              if(nRPS->getUsed(jj)) 
+              if(nRPS->getUsed(jj))
               {
                 Int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
@@ -839,5 +1325,7 @@
                 {
                   if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
+                  {
                     break;
+                  }
                 }
                 Int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
@@ -852,5 +1340,5 @@
         }
         if(isSTSA==true)
-        {    
+        {
           if(pcSlice->getTemporalLayerNonReferenceFlag())
           {
@@ -868,5 +1356,5 @@
     refPicListModification->setRefPicListModificationFlagL0(0);
     refPicListModification->setRefPicListModificationFlagL1(0);
-#if H_MV
+#if NH_MV
     if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > 0 )
     {
@@ -875,11 +1363,11 @@
     }    
 
-    TComVPS*           vps = pcSlice->getVPS();     
-#if H_3D
+    const TComVPS*           vps = pcSlice->getVPS();     
+#if NH_3D
     Int numDirectRefLayers = vps    ->getNumRefListLayers( getLayerId() ); 
 #else
     Int numDirectRefLayers = vps    ->getNumDirectRefLayers( getLayerId() ); 
 #endif
-#if H_3D
+#if NH_3D
     pcSlice->setIvPicLists( m_ivPicLists );         
 
@@ -902,5 +1390,5 @@
           pcSlice->setNumInterLayerRefPicsMinus1( gopEntry.m_numActiveRefLayerPics - 1 ); 
         }
-#if H_3D
+#if NH_3D
         if ( gopEntry.m_numActiveRefLayerPics != vps->getNumRefListLayers( getLayerId() ) )
 #else
@@ -927,8 +1415,8 @@
     assert( pcSlice->getNumActiveRefLayerPics() == gopEntry.m_numActiveRefLayerPics ); 
     
-#if H_3D
+#if NH_3D
     if ( m_pcEncTop->decProcAnnexI() )
     {    
-      pcSlice->deriveInCmpPredAndCpAvailFlag(); 
+      pcSlice->deriveInCmpPredAndCpAvailFlag( ); 
       if ( pcSlice->getInCmpPredAvailFlag() )
       {      
@@ -953,9 +1441,10 @@
       pcSlice->init3dToolParameters(); 
       pcSlice->checkInCompPredRefLayers(); 
-    }
-    
-
-    // This needs to be done after initilizaiton of 3D tool parameters.
+    }   
+
+#if H_3D_IV_MERGE
+    // This needs to be done after initialization of 3D tool parameters.
     pcSlice->setMaxNumMergeCand      ( m_pcCfg->getMaxNumMergeCand()   + ( ( pcSlice->getMpiFlag( ) || pcSlice->getIvMvPredFlag( ) || pcSlice->getViewSynthesisPredFlag( )   ) ? 1 : 0 ));
+#endif
 #endif
 
@@ -976,11 +1465,6 @@
     pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
 #endif
-
-#if ADAPTIVE_QP_SELECTION
-    pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
-#endif      
-
     //  Set reference list
-#if H_MV    
+#if NH_MV    
     pcSlice->setRefPicList( tempRefPicLists, usedAsLongTerm, numPocTotalCurr ); 
 #else
@@ -1010,6 +1494,7 @@
     pcSlice->setICEnableNum( m_aICEnableNum );         
 #endif
+
     //  Slice info. refinement
-#if H_MV
+#if NH_MV
     if ( pcSlice->getSliceType() == B_SLICE )
     {
@@ -1025,4 +1510,6 @@
     }
 #endif
+    pcSlice->setEncCABACTableIdx(m_pcSliceEncoder->getEncCABACTableIdx());
+
     if (pcSlice->getSliceType() == B_SLICE)
     {
@@ -1047,9 +1534,9 @@
       }
 
-      pcSlice->setCheckLDC(bLowDelay);  
+      pcSlice->setCheckLDC(bLowDelay);
     }
     else
     {
-      pcSlice->setCheckLDC(true);  
+      pcSlice->setCheckLDC(true);
     }
 
@@ -1064,4 +1551,5 @@
       pcSlice->generateAlterRefforTMVP();
 #endif
+
     if (m_pcEncTop->getTMVPModeId() == 2)
     {
@@ -1075,17 +1563,14 @@
         pcSlice->setEnableTMVPFlag(1);
       }
-      pcSlice->getSPS()->setTMVPFlagsPresent(1);
     }
     else if (m_pcEncTop->getTMVPModeId() == 1)
     {
-      pcSlice->getSPS()->setTMVPFlagsPresent(1);
       pcSlice->setEnableTMVPFlag(1);
     }
     else
     {
-      pcSlice->getSPS()->setTMVPFlagsPresent(0);
       pcSlice->setEnableTMVPFlag(0);
     }
-#if H_MV
+#if NH_MV
     if( pcSlice->getIdrPicFlag() )
     {
@@ -1094,5 +1579,5 @@
 #endif
 
-#if H_3D_VSO
+#if NH_3D_VSO
   // Should be moved to TEncTop !!! 
   Bool bUseVSO = m_pcEncTop->getUseVSO();
@@ -1128,4 +1613,5 @@
   }
 #endif
+
     /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
     //  Slice compression
@@ -1144,5 +1630,5 @@
         for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
         {
-          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) )
           {
             bGPBcheck=false;
@@ -1161,4 +1647,5 @@
     }
     pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
+
 
     Double lambda            = 0.0;
@@ -1167,5 +1654,5 @@
     Int estimatedBits        = 0;
     Int tmpBitsBeforeWriting = 0;
-    if ( m_pcCfg->getUseRateCtrl() )
+    if ( m_pcCfg->getUseRateCtrl() ) // TODO: does this work with multiple slices and slice-segments?
     {
       Int frameLevel = m_pcRateCtrl->getRCSeq()->getGOPID2Level( iGOPid );
@@ -1198,5 +1685,6 @@
       else if ( frameLevel == 0 )   // intra case, but use the model
       {
-        m_pcSliceEncoder->calCostSliceI(pcPic);
+        m_pcSliceEncoder->calCostSliceI(pcPic); // TODO: This only analyses the first slice segment - what about the others?
+
         if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
         {
@@ -1235,5 +1723,5 @@
       }
 
-      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, sliceQP );
+      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, sliceQP );
       m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
 
@@ -1241,63 +1729,6 @@
     }
 
-    UInt uiNumSlices = 1;
-
-    UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
-    UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
-    UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-    UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-    UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
-    UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
-    while(uiPosX>=uiWidth||uiPosY>=uiHeight) 
-    {
-      uiInternalAddress--;
-      uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-      uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-    }
-    uiInternalAddress++;
-    if(uiInternalAddress==pcPic->getNumPartInCU()) 
-    {
-      uiInternalAddress = 0;
-      uiExternalAddress++;
-    }
-    UInt uiRealEndAddress = uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress;
-
-    Int  p, j;
-    UInt uiEncCUAddr;
-
-    pcPic->getPicSym()->initTiles(pcSlice->getPPS());
-
-    // Allocate some coders, now we know how many tiles there are.
-    Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
-
-    //generate the Coding Order Map and Inverse Coding Order Map
-    for(p=0, uiEncCUAddr=0; p<pcPic->getPicSym()->getNumberOfCUsInFrame(); p++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
-    {
-      pcPic->getPicSym()->setCUOrderMap(p, uiEncCUAddr);
-      pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, p);
-    }
-    pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());    
-    pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
-
-    // Allocate some coders, now we know how many tiles there are.
-    m_pcEncTop->createWPPCoders(iNumSubstreams);
-    pcSbacCoders = m_pcEncTop->getSbacCoders();
-    pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
-
-    UInt startCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
-    UInt startCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
-    pcSlice->setSliceCurStartCUAddr( startCUAddrSlice ); // Setting "start CU addr" for current slice
-    m_storedStartCUAddrForEncodingSlice.clear();
-
-    UInt startCUAddrSliceSegmentIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
-    UInt startCUAddrSliceSegment    = 0; // used to keep track of current Dependent slice's starting CU addr.
-    pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment ); // Setting "start CU addr" for current Dependent slice
-
-    m_storedStartCUAddrForEncodingSliceSegment.clear();
-    UInt nextCUAddr = 0;
-    m_storedStartCUAddrForEncodingSlice.push_back (nextCUAddr);
-    startCUAddrSliceIdx++;
-    m_storedStartCUAddrForEncodingSliceSegment.push_back(nextCUAddr);
-    startCUAddrSliceSegmentIdx++;
+    UInt uiNumSliceSegments = 1;
+
 #if H_3D_NBDV
       if(pcSlice->getViewIndex() && !pcSlice->getIsDepth()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
@@ -1307,5 +1738,5 @@
       }
 #endif
-#if H_3D
+#if NH_3D
       pcSlice->setDepthToDisparityLUTs(); 
 
@@ -1323,64 +1754,58 @@
       }
 #endif
-    while(nextCUAddr<uiRealEndAddress) // determine slice boundaries
-    {
-      pcSlice->setNextSlice       ( false );
-      pcSlice->setNextSliceSegment( false );
-      assert(pcPic->getNumAllocatedSlice() == startCUAddrSliceIdx);
-      m_pcSliceEncoder->precompressSlice( pcPic );
-      m_pcSliceEncoder->compressSlice   ( pcPic );
-
-      Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextSliceSegment());
-      if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU))
-      {
-        startCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
-        // Reconstruction slice
-        m_storedStartCUAddrForEncodingSlice.push_back(startCUAddrSlice);
-        startCUAddrSliceIdx++;
-        // Dependent slice
-        if (startCUAddrSliceSegmentIdx>0 && m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx-1] != startCUAddrSlice)
-        {
-          m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSlice);
-          startCUAddrSliceSegmentIdx++;
-        }
-
-        if (startCUAddrSlice < uiRealEndAddress)
-        {
-          pcPic->allocateNewSlice();          
-          pcPic->setCurrSliceIdx                  ( startCUAddrSliceIdx-1 );
-          m_pcSliceEncoder->setSliceIdx           ( startCUAddrSliceIdx-1 );
-          pcSlice = pcPic->getSlice               ( startCUAddrSliceIdx-1 );
-          pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
-          pcSlice->setSliceIdx                    ( startCUAddrSliceIdx-1 );
-          pcSlice->setSliceCurStartCUAddr         ( startCUAddrSlice      );
-          pcSlice->setSliceSegmentCurStartCUAddr  ( startCUAddrSlice      );
-          pcSlice->setSliceBits(0);
-          uiNumSlices ++;
-        }
-      }
-      else if (pcSlice->isNextSliceSegment() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU))
-      {
-        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
-        m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSliceSegment);
-        startCUAddrSliceSegmentIdx++;
-        pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment );
-      }
-      else
-      {
-        startCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
-        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
-      }        
-
-      nextCUAddr = (startCUAddrSlice > startCUAddrSliceSegment) ? startCUAddrSlice : startCUAddrSliceSegment;
-    }
-    m_storedStartCUAddrForEncodingSlice.push_back( pcSlice->getSliceCurEndCUAddr());
-    startCUAddrSliceIdx++;
-    m_storedStartCUAddrForEncodingSliceSegment.push_back(pcSlice->getSliceCurEndCUAddr());
-    startCUAddrSliceSegmentIdx++;
-
+    // Allocate some coders, now the number of tiles are known.
+    const Int numSubstreamsColumns = (pcSlice->getPPS()->getNumTileColumnsMinus1() + 1);
+    const Int numSubstreamRows     = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() ? pcPic->getFrameHeightInCtus() : (pcSlice->getPPS()->getNumTileRowsMinus1() + 1);
+    const Int numSubstreams        = numSubstreamRows * numSubstreamsColumns;
+    std::vector<TComOutputBitstream> substreamsOut(numSubstreams);
+
+    // now compress (trial encode) the various slice segments (slices, and dependent slices)
+    {
+      const UInt numberOfCtusInFrame=pcPic->getPicSym()->getNumberOfCtusInFrame();
+      pcSlice->setSliceCurStartCtuTsAddr( 0 );
+      pcSlice->setSliceSegmentCurStartCtuTsAddr( 0 );
+
+      for(UInt nextCtuTsAddr = 0; nextCtuTsAddr < numberOfCtusInFrame; )
+      {
+        m_pcSliceEncoder->precompressSlice( pcPic );
+        m_pcSliceEncoder->compressSlice   ( pcPic, false );
+
+        const UInt curSliceSegmentEnd = pcSlice->getSliceSegmentCurEndCtuTsAddr();
+        if (curSliceSegmentEnd < numberOfCtusInFrame)
+        {
+          const Bool bNextSegmentIsDependentSlice=curSliceSegmentEnd<pcSlice->getSliceCurEndCtuTsAddr();
+          const UInt sliceBits=pcSlice->getSliceBits();
+          pcPic->allocateNewSlice();
+          // prepare for next slice
+          pcPic->setCurrSliceIdx                    ( uiNumSliceSegments );
+          m_pcSliceEncoder->setSliceIdx             ( uiNumSliceSegments   );
+          pcSlice = pcPic->getSlice                 ( uiNumSliceSegments   );
+          assert(pcSlice->getPPS()!=0);
+          pcSlice->copySliceInfo                    ( pcPic->getSlice(uiNumSliceSegments-1)  );
+          pcSlice->setSliceIdx                      ( uiNumSliceSegments   );
+          if (bNextSegmentIsDependentSlice)
+          {
+            pcSlice->setSliceBits(sliceBits);
+          }
+          else
+          {
+            pcSlice->setSliceCurStartCtuTsAddr      ( curSliceSegmentEnd );
+            pcSlice->setSliceBits(0);
+          }
+          pcSlice->setDependentSliceSegmentFlag(bNextSegmentIsDependentSlice);
+          pcSlice->setSliceSegmentCurStartCtuTsAddr ( curSliceSegmentEnd );
+          // TODO: optimise cabac_init during compress slice to improve multi-slice operation
+          // pcSlice->setEncCABACTableIdx(m_pcSliceEncoder->getEncCABACTableIdx());
+          uiNumSliceSegments ++;
+        }
+        nextCtuTsAddr = curSliceSegmentEnd;
+      }
+    }
+
+    duData.clear();
     pcSlice = pcPic->getSlice(0);
 
-    // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
-    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
+    // SAO parameter estimation using non-deblocked pixels for CTU bottom and right boundary areas
+    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoCtuBoundary() )
     {
       m_pcSAO->getPreDBFStatistics(pcPic);
@@ -1392,5 +1817,5 @@
     if ( m_pcCfg->getDeblockingFilterMetric() )
     {
-      dblMetric(pcPic, uiNumSlices);
+      applyDeblockingFilterMetric(pcPic, uiNumSliceSegments);
     }
     m_pcLoopFilter->loopFilterPic( pcPic );
@@ -1398,1022 +1823,315 @@
     /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
     // Set entropy coder
-    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
-
-    /* write various header sets. */
+    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder );
     if ( m_bSeqFirst )
     {
-      OutputNALUnit nalu(NAL_UNIT_VPS);
-#if H_MV
-      if( getLayerId() == 0 )
-      {
+      // write various parameter sets
+      actualTotalBits += xWriteParameterSets(accessUnit, pcSlice);
+#if PPS_FIX_DEPTH
+      if(!pcSlice->getIsDepth() || !pcSlice->getViewIndex() )
+      {
+#endif
+#if PPS_FIX_DEPTH
+      }
+#endif
+
+
+      // create prefix SEI messages at the beginning of the sequence
+      assert(leadingSeiMessages.empty());
+      xCreateIRAPLeadingSEIMessages(leadingSeiMessages, pcSlice->getSPS(), pcSlice->getPPS());
+
+      m_bSeqFirst = false;
+    }
+
+    // reset presence of BP SEI indication
+    m_bufferingPeriodSEIPresentInAU = false;
+    // create prefix SEI associated with a picture
+    xCreatePerPictureSEIMessages(iGOPid, leadingSeiMessages, nestedSeiMessages, pcSlice);
+
+    /* use the main bitstream buffer for storing the marshalled picture */
+    m_pcEntropyCoder->setBitstream(NULL);
+
+    pcSlice = pcPic->getSlice(0);
+
+    if (pcSlice->getSPS()->getUseSAO())
+    {
+      Bool sliceEnabled[MAX_NUM_COMPONENT];
+      TComBitCounter tempBitCounter;
+      tempBitCounter.resetBits();
+      m_pcEncTop->getRDGoOnSbacCoder()->setBitstream(&tempBitCounter);
+      m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
+      m_pcSAO->SAOProcess(pcPic, sliceEnabled, pcPic->getSlice(0)->getLambdas(), m_pcCfg->getTestSAODisableAtPictureLevel(), m_pcCfg->getSaoEncodingRate(), m_pcCfg->getSaoEncodingRateChroma(), m_pcCfg->getSaoCtuBoundary());
+      m_pcSAO->PCMLFDisableProcess(pcPic);
+      m_pcEncTop->getRDGoOnSbacCoder()->setBitstream(NULL);
+
+      //assign SAO slice header
+      for(Int s=0; s< uiNumSliceSegments; s++)
+      {
+        pcPic->getSlice(s)->setSaoEnabledFlag(CHANNEL_TYPE_LUMA, sliceEnabled[COMPONENT_Y]);
+        assert(sliceEnabled[COMPONENT_Cb] == sliceEnabled[COMPONENT_Cr]);
+        pcPic->getSlice(s)->setSaoEnabledFlag(CHANNEL_TYPE_CHROMA, sliceEnabled[COMPONENT_Cb]);
+      }
+    }
+
+    // pcSlice is currently slice 0.
+    std::size_t binCountsInNalUnits   = 0; // For implementation of cabac_zero_word stuffing (section 7.4.3.10)
+    std::size_t numBytesInVclNalUnits = 0; // For implementation of cabac_zero_word stuffing (section 7.4.3.10)
+
+    for( UInt sliceSegmentStartCtuTsAddr = 0, sliceIdxCount=0; sliceSegmentStartCtuTsAddr < pcPic->getPicSym()->getNumberOfCtusInFrame(); sliceIdxCount++, sliceSegmentStartCtuTsAddr=pcSlice->getSliceSegmentCurEndCtuTsAddr() )
+    {
+      pcSlice = pcPic->getSlice(sliceIdxCount);
+      if(sliceIdxCount > 0 && pcSlice->getSliceType()!= I_SLICE)
+      {
+        pcSlice->checkColRefIdx(sliceIdxCount, pcPic);
+      }
+      pcPic->setCurrSliceIdx(sliceIdxCount);
+      m_pcSliceEncoder->setSliceIdx(sliceIdxCount);
+
+      pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
+      pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
+
+      for ( UInt ui = 0 ; ui < numSubstreams; ui++ )
+      {
+        substreamsOut[ui].clear();
+      }
+
+      m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder );
+      m_pcEntropyCoder->resetEntropy      ( pcSlice );
+      /* start slice NALunit */
+#if NH_MV
+      OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), getLayerId() );
+#else
+      OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
 #endif
       m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
+
+      pcSlice->setNoRaslOutputFlag(false);
+      if (pcSlice->isIRAP())
+      {
+        if (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_IDR_N_LP)
+        {
+          pcSlice->setNoRaslOutputFlag(true);
+        }
+        //the inference for NoOutputPriorPicsFlag
+        // KJS: This cannot happen at the encoder
+        if (!m_bFirst && pcSlice->isIRAP() && pcSlice->getNoRaslOutputFlag())
+        {
+          if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+          {
+            pcSlice->setNoOutputPriorPicsFlag(true);
+          }
+        }
+      }
+
+      pcSlice->setEncCABACTableIdx(m_pcSliceEncoder->getEncCABACTableIdx());
+
+      tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
+      m_pcEntropyCoder->encodeSliceHeader(pcSlice);
+      actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
+
+      pcSlice->setFinalized(true);
+
+      pcSlice->clearSubstreamSizes(  );
+      {
+        UInt numBinsCoded = 0;
+        m_pcSliceEncoder->encodeSlice(pcPic, &(substreamsOut[0]), numBinsCoded);
+        binCountsInNalUnits+=numBinsCoded;
+      }
+
+      {
+        // Construct the final bitstream by concatenating substreams.
+        // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
+        // Complete the slice header info.
+        m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder );
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+        m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
+
+        // Append substreams...
+        TComOutputBitstream *pcOut = pcBitstreamRedirect;
+        const Int numZeroSubstreamsAtStartOfSlice  = pcPic->getSubstreamForCtuAddr(pcSlice->getSliceSegmentCurStartCtuTsAddr(), false, pcSlice);
+        const Int numSubstreamsToCode  = pcSlice->getNumberOfSubstreamSizes()+1;
+        for ( UInt ui = 0 ; ui < numSubstreamsToCode; ui++ )
+        {
+          pcOut->addSubstream(&(substreamsOut[ui+numZeroSubstreamsAtStartOfSlice]));
+        }
+      }
+
+      // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
+      // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
+      Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
+      xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
       accessUnit.push_back(new NALUnitEBSP(nalu));
       actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-
-#if H_MV
-      }
-      nalu = NALUnit(NAL_UNIT_SPS, 0, getLayerId());
-#else
-      nalu = NALUnit(NAL_UNIT_SPS);
-#endif
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-      if (m_bSeqFirst)
-      {
-        pcSlice->getSPS()->setNumLongTermRefPicSPS(m_numLongTermRefPicSPS);
-        for (Int k = 0; k < m_numLongTermRefPicSPS; k++)
-        {
-          pcSlice->getSPS()->setLtRefPicPocLsbSps(k, m_ltRefPicPocLsbSps[k]);
-          pcSlice->getSPS()->setUsedByCurrPicLtSPSFlag(k, m_ltRefPicUsedByCurrPicFlag[k]);
-        }
-      }
-      if( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
-      {
-        UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
-        UInt numDU = ( m_pcCfg->getSliceMode() == 1 ) ? ( pcPic->getNumCUsInFrame() / maxCU ) : ( 0 );
-        if( pcPic->getNumCUsInFrame() % maxCU != 0 || numDU == 0 )
-        {
-          numDU ++;
-        }
-        pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->setNumDU( numDU );
-        pcSlice->getSPS()->setHrdParameters( m_pcCfg->getFrameRate(), numDU, m_pcCfg->getTargetBitrate(), ( m_pcCfg->getIntraPeriod() > 0 ) );
-      }
-      if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
-      {
-        pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
-      }
-      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-
-#if H_MV
-      nalu = NALUnit(NAL_UNIT_PPS, 0, getLayerId());
-#else
-      nalu = NALUnit(NAL_UNIT_PPS);
-#endif
-#if PPS_FIX_DEPTH
-      if(!pcSlice->getIsDepth() || !pcSlice->getViewIndex() )
-      {
-#endif
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-      
-#if PPS_FIX_DEPTH
-      }
-#endif
-      xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
-
-      m_bSeqFirst = false;
-    }
-
-    if (writeSOP) // write SOP description SEI (if enabled) at the beginning of GOP
-    {
-      Int SOPcurrPOC = pocCurr;
-
-      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-      SEISOPDescription SOPDescriptionSEI;
-      SOPDescriptionSEI.m_sopSeqParameterSetId = pcSlice->getSPS()->getSPSId();
-
-      UInt i = 0;
-      UInt prevEntryId = iGOPid;
-      for (j = iGOPid; j < m_iGopSize; j++)
-      {
-        Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
-        if ((SOPcurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
-        {
-          SOPcurrPOC += deltaPOC;
-          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR, isField);
-          SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
-          SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
-          SOPDescriptionSEI.m_sopDescPocDelta[i] = deltaPOC;
-
-          prevEntryId = j;
-          i++;
-        }
-      }
-
-      SOPDescriptionSEI.m_numPicsInSopMinus1 = i - 1;
-
-      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, pcSlice->getSPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-
-      writeSOP = false;
-    }
-
-    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
-        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
-        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
-       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
-    {
-      if( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() )
-      {
-        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumDU();
-        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
-        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = false;
-
-        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
-        {
-          pictureTimingSEI.m_numNalusInDuMinus1       = new UInt[ numDU ];
-        }
-        if( pictureTimingSEI.m_duCpbRemovalDelayMinus1  == NULL )
-        {
-          pictureTimingSEI.m_duCpbRemovalDelayMinus1  = new UInt[ numDU ];
-        }
-        if( accumBitsDU == NULL )
-        {
-          accumBitsDU                                  = new UInt[ numDU ];
-        }
-        if( accumNalsDU == NULL )
-        {
-          accumNalsDU                                  = new UInt[ numDU ];
-        }
-      }
-      pictureTimingSEI.m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<double>(pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
-      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(pcSlice->getSPS()->getMaxTLayers()-1) + pcSlice->getPOC() - m_totalCoded;
-#if EFFICIENT_FIELD_IRAP
-      if(IRAPGOPid > 0 && IRAPGOPid < m_iGopSize)
-      {
-        // if pictures have been swapped there is likely one more picture delay on their tid. Very rough approximation
-        pictureTimingSEI.m_picDpbOutputDelay ++;
-      }
-#endif
-      Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
-      pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
-      if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
-      {
-        picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
-      }
-    }
-
-    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
-        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
-        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
-       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
-    {
-      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-      SEIBufferingPeriod sei_buffering_period;
-      
-      UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
-      sei_buffering_period.m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
-
-      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
-
-      UInt uiTmp = (UInt)( dTmp * 90000.0 ); 
-      uiInitialCpbRemovalDelay -= uiTmp;
-      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
-      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
-      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
-
-      sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
-      //for the concatenation, it can be set to one during splicing.
-      sei_buffering_period.m_concatenationFlag = 0;
-      //since the temporal layer HRD is not ready, we assumed it is fixed
-      sei_buffering_period.m_auCpbRemovalDelayDelta = 1;
-      sei_buffering_period.m_cpbDelayOffset = 0;
-      sei_buffering_period.m_dpbDelayOffset = 0;
-
-      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      {
-      UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-      UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
-      AccessUnit::iterator it;
-      for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-      {
-        it++;
-      }
-      accessUnit.insert(it, new NALUnitEBSP(nalu));
-      m_bufferingPeriodSEIPresentInAU = true;
-      }
-
-      if (m_pcCfg->getScalableNestingSEIEnabled())
-      {
-        OutputNALUnit naluTmp(NAL_UNIT_PREFIX_SEI);
-        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-        m_pcEntropyCoder->setBitstream(&naluTmp.m_Bitstream);
-        scalableNestingSEI.m_nestedSEIs.clear();
-        scalableNestingSEI.m_nestedSEIs.push_back(&sei_buffering_period);
-        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
-        writeRBSPTrailingBits(naluTmp.m_Bitstream);
-        UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-        UInt offsetPosition = m_activeParameterSetSEIPresentInAU + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU;   // Insert BP SEI after non-nested APS, BP and PT SEIs
-        AccessUnit::iterator it;
-        for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-        {
-          it++;
-        }
-        accessUnit.insert(it, new NALUnitEBSP(naluTmp));
-        m_nestedBufferingPeriodSEIPresentInAU = true;
-      }
-
-      m_lastBPSEI = m_totalCoded;
-      m_cpbRemovalDelay = 0;
-    }
-    m_cpbRemovalDelay ++;
-    if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) )
-    {
-      if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !pcSlice->getRapPicFlag() )
-      {
-        // Gradual decoding refresh SEI 
-        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-        SEIGradualDecodingRefreshInfo seiGradualDecodingRefreshInfo;
-        seiGradualDecodingRefreshInfo.m_gdrForegroundFlag = true; // Indicating all "foreground"
-
-        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, pcSlice->getSPS() );
-        writeRBSPTrailingBits(nalu.m_Bitstream);
+      numBytesInVclNalUnits += (std::size_t)(accessUnit.back()->m_nalUnitData.str().size());
+      bNALUAlignedWrittenToList = true;
+
+      if (!bNALUAlignedWrittenToList)
+      {
+        nalu.m_Bitstream.writeAlignZero();
         accessUnit.push_back(new NALUnitEBSP(nalu));
-      }
-    // Recovery point SEI
-      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
-      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-      SEIRecoveryPoint sei_recovery_point;
-      sei_recovery_point.m_recoveryPocCnt    = 0;
-      sei_recovery_point.m_exactMatchingFlag = ( pcSlice->getPOC() == 0 ) ? (true) : (false);
-      sei_recovery_point.m_brokenLinkFlag    = false;
-#if ALLOW_RECOVERY_POINT_AS_RAP
-      if(m_pcCfg->getDecodingRefreshType() == 3)
-      {
-        m_iLastRecoveryPicPOC = pocCurr;
-      }
-#endif
-
-      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, pcSlice->getSPS() );
-      writeRBSPTrailingBits(nalu.m_Bitstream);
-      accessUnit.push_back(new NALUnitEBSP(nalu));
-    }
-
-    /* use the main bitstream buffer for storing the marshalled picture */
-    m_pcEntropyCoder->setBitstream(NULL);
-
-    startCUAddrSliceIdx = 0;
-    startCUAddrSlice    = 0; 
-
-    startCUAddrSliceSegmentIdx = 0;
-    startCUAddrSliceSegment    = 0; 
-    nextCUAddr                 = 0;
-    pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
-
-    Int processingState = (pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
-    Bool skippedSlice=false;
-    while (nextCUAddr < uiRealEndAddress) // Iterate over all slices
-    {
-      switch(processingState)
-      {
-      case ENCODE_SLICE:
-        {
-          pcSlice->setNextSlice       ( false );
-          pcSlice->setNextSliceSegment( false );
-          if (nextCUAddr == m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx])
-          {
-            pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
-            if(startCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
-            {
-              pcSlice->checkColRefIdx(startCUAddrSliceIdx, pcPic);
-            }
-            pcPic->setCurrSliceIdx(startCUAddrSliceIdx);
-            m_pcSliceEncoder->setSliceIdx(startCUAddrSliceIdx);
-            assert(startCUAddrSliceIdx == pcSlice->getSliceIdx());
-            // Reconstruction slice
-            pcSlice->setSliceCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
-            pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx+1 ] );
-            // Dependent slice
-            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
-            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
-
-            pcSlice->setNextSlice       ( true );
-
-            startCUAddrSliceIdx++;
-            startCUAddrSliceSegmentIdx++;
-          } 
-          else if (nextCUAddr == m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx])
-          {
-            // Dependent slice
-            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
-            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
-
-            pcSlice->setNextSliceSegment( true );
-
-            startCUAddrSliceSegmentIdx++;
-          }
-
-          pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
-          pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
-          UInt uiDummyStartCUAddr;
-          UInt uiDummyBoundingCUAddr;
-          m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
-
-          uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
-          uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
-          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-          uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
-          uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
-          while(uiPosX>=uiWidth||uiPosY>=uiHeight)
-          {
-            uiInternalAddress--;
-            uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-            uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-          }
-          uiInternalAddress++;
-          if(uiInternalAddress==pcPic->getNumPartInCU())
-          {
-            uiInternalAddress = 0;
-            uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
-          }
-          UInt endAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
-          if(endAddress<=pcSlice->getSliceSegmentCurStartCUAddr()) 
-          {
-            UInt boundingAddrSlice, boundingAddrSliceSegment;
-            boundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];          
-            boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];          
-            nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
-            if(pcSlice->isNextSlice())
-            {
-              skippedSlice=true;
-            }
-            continue;
-          }
-          if(skippedSlice) 
-          {
-            pcSlice->setNextSlice       ( true );
-            pcSlice->setNextSliceSegment( false );
-          }
-          skippedSlice=false;
-          pcSlice->allocSubstreamSizes( iNumSubstreams );
-          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
-          {
-            pcSubstreamsOut[ui].clear();
-          }
-
-          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
-          m_pcEntropyCoder->resetEntropy      ();
-          /* start slice NALunit */
-#if H_MV
-          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), getLayerId() );
-#else
-          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
-#endif
-          Bool sliceSegment = (!pcSlice->isNextSlice());
-          if (!sliceSegment)
-          {
-            uiOneBitstreamPerSliceLength = 0; // start of a new slice
-          }
-          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-
-#if SETTING_NO_OUT_PIC_PRIOR
-          pcSlice->setNoRaslOutputFlag(false);
-          if (pcSlice->isIRAP())
-          {
-            if (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_IDR_N_LP)
-            {
-              pcSlice->setNoRaslOutputFlag(true);
-            }
-            //the inference for NoOutputPriorPicsFlag
-            // KJS: This cannot happen at the encoder
-            if (!m_bFirst && pcSlice->isIRAP() && pcSlice->getNoRaslOutputFlag())
-            {
-              if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
-              {
-                pcSlice->setNoOutputPriorPicsFlag(true);
-              }
-            }
-          }
-#endif
-
-          tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
-          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
-          actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
-
-          // is it needed?
-          {
-            if (!sliceSegment)
-            {
-              pcBitstreamRedirect->writeAlignOne();
-            }
-            else
-            {
-              // We've not completed our slice header info yet, do the alignment later.
-            }
-            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
-            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
-            m_pcEntropyCoder->resetEntropy    ();
-            for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
-            {
-              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
-              m_pcEntropyCoder->resetEntropy    ();
-            }
-          }
-
-          if(pcSlice->isNextSlice())
-          {
-            // set entropy coder for writing
-            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
-            {
-              for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
-              {
-                m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
-                m_pcEntropyCoder->resetEntropy    ();
-              }
-              pcSbacCoders[0].load(m_pcSbacCoder);
-              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[0], pcSlice );  //ALF is written in substream #0 with CABAC coder #0 (see ALF param encoding below)
-            }
-            m_pcEntropyCoder->resetEntropy    ();
-            // File writing
-            if (!sliceSegment)
-            {
-              m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
-            }
-            else
-            {
-              m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-            }
-            // for now, override the TILES_DECODER setting in order to write substreams.
-            m_pcEntropyCoder->setBitstream    ( &pcSubstreamsOut[0] );
-
-          }
-          pcSlice->setFinalized(true);
-
-          m_pcSbacCoder->load( &pcSbacCoders[0] );
-
-          pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
-            pcSlice->setTileLocationCount ( 0 );
-          m_pcSliceEncoder->encodeSlice(pcPic, pcSubstreamsOut);
-
-          {
-            // Construct the final bitstream by flushing and concatenating substreams.
-            // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
-            UInt* puiSubstreamSizes = pcSlice->getSubstreamSizes();
-            UInt uiTotalCodedSize = 0; // for padding calcs.
-            UInt uiNumSubstreamsPerTile = iNumSubstreams;
-            if (iNumSubstreams > 1)
-            {
-              uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
-            }
-            for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
-            {
-              // Flush all substreams -- this includes empty ones.
-              // Terminating bit and flush.
-              m_pcEntropyCoder->setEntropyCoder   ( &pcSbacCoders[ui], pcSlice );
-              m_pcEntropyCoder->setBitstream      (  &pcSubstreamsOut[ui] );
-              m_pcEntropyCoder->encodeTerminatingBit( 1 );
-              m_pcEntropyCoder->encodeSliceFinish();
-
-              pcSubstreamsOut[ui].writeByteAlignment();   // Byte-alignment in slice_data() at end of sub-stream
-              // Byte alignment is necessary between tiles when tiles are independent.
-              uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
-
-              Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)&& ((ui+1)%uiNumSubstreamsPerTile == 0);
-              if (bNextSubstreamInNewTile)
-              {
-                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
-              }
-              if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
-              {
-                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits() + (pcSubstreamsOut[ui].countStartCodeEmulations()<<3);
-              }
-            }
-
-            // Complete the slice header info.
-            m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
-            m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
-            m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
-
-            // Substreams...
-            TComOutputBitstream *pcOut = pcBitstreamRedirect;
-          Int offs = 0;
-          Int nss = pcSlice->getPPS()->getNumSubstreams();
-          if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
-          {
-            // 1st line present for WPP.
-            offs = pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
-            nss  = pcSlice->getNumEntryPointOffsets()+1;
-          }
-          for ( UInt ui = 0 ; ui < nss; ui++ )
-          {
-            pcOut->addSubstream(&pcSubstreamsOut[ui+offs]);
-            }
-          }
-
-          UInt boundingAddrSlice, boundingAddrSliceSegment;
-          boundingAddrSlice        = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];          
-          boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];          
-          nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
-          // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
-          // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
-          Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
-          xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
-          accessUnit.push_back(new NALUnitEBSP(nalu));
-          actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
-          bNALUAlignedWrittenToList = true; 
-          uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
-
-          if (!bNALUAlignedWrittenToList)
-          {
-            {
-              nalu.m_Bitstream.writeAlignZero();
-            }
-            accessUnit.push_back(new NALUnitEBSP(nalu));
-            uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits() + 24; // length of bitstream after byte-alignment + 3 byte startcode 0x000001
-          }
-
-          if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
-              ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
-              ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
-             || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
-              ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
-          {
-              UInt numNalus = 0;
-            UInt numRBSPBytes = 0;
-            for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
-            {
-              UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
-              if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
-              {
-                numRBSPBytes += numRBSPBytes_nal;
-                numNalus ++;
-              }
-            }
-            accumBitsDU[ pcSlice->getSliceIdx() ] = ( numRBSPBytes << 3 );
-            accumNalsDU[ pcSlice->getSliceIdx() ] = numNalus;   // SEI not counted for bit count; hence shouldn't be counted for # of NALUs - only for consistency
-          }
-          processingState = ENCODE_SLICE;
-          }
-          break;
-        case EXECUTE_INLOOPFILTER:
-          {
-            // set entropy coder for RD
-            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
-            if ( pcSlice->getSPS()->getUseSAO() )
-            {
-              m_pcEntropyCoder->resetEntropy();
-              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
-            Bool sliceEnabled[NUM_SAO_COMPONENTS];
-            m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
-            m_pcSAO->SAOProcess(pcPic
-              , sliceEnabled
-              , pcPic->getSlice(0)->getLambdas()
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-              , m_pcCfg->getSaoLcuBoundary()
-#endif
-              );
-              m_pcSAO->PCMLFDisableProcess(pcPic);
-
-#if H_3D_DISABLE_CHROMA
-            if (pcSlice->getIsDepth())
-            {
-              sliceEnabled[SAO_Cb] = false; 
-              sliceEnabled[SAO_Cr] = false; 
-            }
-#endif
-            //assign SAO slice header
-            for(Int s=0; s< uiNumSlices; s++)
-            {
-              pcPic->getSlice(s)->setSaoEnabledFlag(sliceEnabled[SAO_Y]);
-              assert(sliceEnabled[SAO_Cb] == sliceEnabled[SAO_Cr]);
-              pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
-              }
-            }
-          processingState = ENCODE_SLICE;
-          }
-          break;
-        default:
-          {
-            printf("Not a supported encoding state\n");
-            assert(0);
-            exit(-1);
-          }
-        }
-      } // end iteration over slices
-#if H_3D
-      pcPic->compressMotion(2); 
-#endif
-#if !H_3D
-      pcPic->compressMotion(); 
-#endif
-#if H_MV
-      m_pocLastCoded = pcPic->getPOC();
-#endif
-
-      //-- For time output for each slice
-      Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
-
-      const Char* digestStr = NULL;
-      if (m_pcCfg->getDecodedPictureHashSEIEnabled())
-      {
-        /* calculate MD5sum for entire reconstructed picture */
-        SEIDecodedPictureHash sei_recon_picture_digest;
-        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
-        {
-          sei_recon_picture_digest.method = SEIDecodedPictureHash::MD5;
-          calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
-          digestStr = digestToString(sei_recon_picture_digest.digest, 16);
-        }
-        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
-        {
-          sei_recon_picture_digest.method = SEIDecodedPictureHash::CRC;
-          calcCRC(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
-          digestStr = digestToString(sei_recon_picture_digest.digest, 2);
-        }
-        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
-        {
-          sei_recon_picture_digest.method = SEIDecodedPictureHash::CHECKSUM;
-          calcChecksum(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
-          digestStr = digestToString(sei_recon_picture_digest.digest, 4);
-        }
-#if H_MV
-        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), getLayerId() );
-#else
-        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
-#endif
-
-        /* write the SEI messages */
-        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, pcSlice->getSPS());
-        writeRBSPTrailingBits(nalu.m_Bitstream);
-
-        accessUnit.insert(accessUnit.end(), new NALUnitEBSP(nalu));
-      }
-      if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
-      {
-        SEITemporalLevel0Index sei_temporal_level0_index;
-        if (pcSlice->getRapPicFlag())
-        {
-          m_tl0Idx = 0;
-          m_rapIdx = (m_rapIdx + 1) & 0xFF;
-        }
-        else
-        {
-          m_tl0Idx = (m_tl0Idx + (pcSlice->getTLayer() ? 0 : 1)) & 0xFF;
-        }
-        sei_temporal_level0_index.tl0Idx = m_tl0Idx;
-        sei_temporal_level0_index.rapIdx = m_rapIdx;
-
-        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI); 
-
-        /* write the SEI messages */
-        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, pcSlice->getSPS());
-        writeRBSPTrailingBits(nalu.m_Bitstream);
-
-        /* insert the SEI message NALUnit before any Slice NALUnits */
-        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
-        accessUnit.insert(it, new NALUnitEBSP(nalu));
-      }
-
-      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
-
-    //In case of field coding, compute the interlaced PSNR for both fields
-    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)) && (pcPic->getPOC()%m_iGopSize != 1))
-    {
-      //get complementary top field
-      TComPic* pcPicTop;
-      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
-      while ((*iterPic)->getPOC() != pcPic->getPOC()-1)
-      {
-        iterPic ++;
-      }
-      pcPicTop = *(iterPic);
-      xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
-    }
-    else if (isField && pcPic->getPOC()!= 0 && (pcPic->getPOC()%m_iGopSize == 0))
-    {
-      //get complementary bottom field
-      TComPic* pcPicBottom;
-      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
-      while ((*iterPic)->getPOC() != pcPic->getPOC()+1)
-      {
-        iterPic ++;
-      }
-      pcPicBottom = *(iterPic);
-      xCalculateInterlacedAddPSNR(pcPic, pcPicBottom, pcPic->getPicYuvRec(), pcPicBottom->getPicYuvRec(), accessUnit, dEncTime );
-    }
-    
-      if (digestStr)
-      {
-        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
-        {
-          printf(" [MD5:%s]", digestStr);
-        }
-        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
-        {
-          printf(" [CRC:%s]", digestStr);
-        }
-        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
-        {
-          printf(" [Checksum:%s]", digestStr);
-        }
-      }
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
-        Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
-        Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
-        if ( avgLambda < 0.0 )
-        {
-          avgLambda = lambda;
-        }
-        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
-        m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
-
-        m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
-        if ( pcSlice->getSliceType() != I_SLICE )
-        {
-          m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
-        }
-        else    // for intra picture, the estimated bits are used to update the current status in the GOP
-        {
-          m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
-        }
       }
 
       if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
           ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
-          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
-         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
-      {
-        TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
-        TComHRD *hrd = vui->getHrdParameters();
-
-        if( hrd->getSubPicCpbParamsPresentFlag() )
-        {
-          Int i;
-          UInt64 ui64Tmp;
-          UInt uiPrev = 0;
-          UInt numDU = ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 );
-          UInt *pCRD = &pictureTimingSEI.m_duCpbRemovalDelayMinus1[0];
-          UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
-
-          for( i = 0; i < numDU; i ++ )
-          {
-            pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] - 1 ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
-          }
-
-          if( numDU == 1 )
-          {
-            pCRD[ 0 ] = 0; /* don't care */
-          }
-          else
-          {
-            pCRD[ numDU - 1 ] = 0;/* by definition */
-            UInt tmp = 0;
-            UInt accum = 0;
-
-            for( i = ( numDU - 2 ); i >= 0; i -- )
-            {
-              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
-              if( (UInt)ui64Tmp > maxDiff )
-              {
-                tmp ++;
-              }
-            }
-            uiPrev = 0;
-
-            UInt flag = 0;
-            for( i = ( numDU - 2 ); i >= 0; i -- )
-            {
-              flag = 0;
-              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
-
-              if( (UInt)ui64Tmp > maxDiff )
-              {
-                if(uiPrev >= maxDiff - tmp)
-                {
-                  ui64Tmp = uiPrev + 1;
-                  flag = 1;
-                }
-                else                            ui64Tmp = maxDiff - tmp + 1;
-              }
-              pCRD[ i ] = (UInt)ui64Tmp - uiPrev - 1;
-              if( (Int)pCRD[ i ] < 0 )
-              {
-                pCRD[ i ] = 0;
-              }
-              else if (tmp > 0 && flag == 1) 
-              {
-                tmp --;
-              }
-              accum += pCRD[ i ] + 1;
-              uiPrev = accum;
-            }
-          }
-        }
-        if( m_pcCfg->getPictureTimingSEIEnabled() )
-        {
-          {
-            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
-          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
-          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
-          writeRBSPTrailingBits(nalu.m_Bitstream);
-          UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-          UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
-                                    + m_bufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
-          AccessUnit::iterator it;
-          for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-          {
-            it++;
-          }
-          accessUnit.insert(it, new NALUnitEBSP(nalu));
-          m_pictureTimingSEIPresentInAU = true;
-        }
-          if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
-          {
-            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
-            m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-            scalableNestingSEI.m_nestedSEIs.clear();
-            scalableNestingSEI.m_nestedSEIs.push_back(&pictureTimingSEI);
-            m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
-            writeRBSPTrailingBits(nalu.m_Bitstream);
-            UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-            UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
-              + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU + m_nestedBufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
-            AccessUnit::iterator it;
-            for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-            {
-              it++;
-            }
-            accessUnit.insert(it, new NALUnitEBSP(nalu));
-            m_nestedPictureTimingSEIPresentInAU = true;
-          }
-        }
-        if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
-        {             
-          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
-          for( Int i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
-          {
-            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
-
-            SEIDecodingUnitInfo tempSEI;
-            tempSEI.m_decodingUnitIdx = i;
-            tempSEI.m_duSptCpbRemovalDelay = pictureTimingSEI.m_duCpbRemovalDelayMinus1[i] + 1;
-            tempSEI.m_dpbOutputDuDelayPresentFlag = false;
-            tempSEI.m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
-
-            AccessUnit::iterator it;
-            // Insert the first one in the right location, before the first slice
-            if(i == 0)
-            {
-              // Insert before the first slice. 
-              m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
-              writeRBSPTrailingBits(nalu.m_Bitstream);
-
-              UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
-              UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
-                                    + m_bufferingPeriodSEIPresentInAU 
-                                    + m_pictureTimingSEIPresentInAU;  // Insert DU info SEI after APS, BP and PT SEI
-              for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
-              {
-                it++;
-              }
-              accessUnit.insert(it, new NALUnitEBSP(nalu));
-            }
-            else
-            {
-              Int ctr;
-              // For the second decoding unit onwards we know how many NALUs are present
-              for (ctr = 0, it = accessUnit.begin(); it != accessUnit.end(); it++)
-              {            
-                if(ctr == accumNalsDU[ i - 1 ])
-                {
-                  // Insert before the first slice. 
-                  m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
-                  writeRBSPTrailingBits(nalu.m_Bitstream);
-
-                  accessUnit.insert(it, new NALUnitEBSP(nalu));
-                  break;
-                }
-                if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
-                {
-                  ctr++;
-                }
-              }
-            }            
-          }
-        }
-      }
-      xResetNonNestedSEIPresentFlags();
-      xResetNestedSEIPresentFlags();
-      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
-
-      pcPic->setReconMark   ( true );
-#if H_MV
+          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
+         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
+          ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
+      {
+          UInt numNalus = 0;
+        UInt numRBSPBytes = 0;
+        for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+        {
+          numRBSPBytes += UInt((*it)->m_nalUnitData.str().size());
+          numNalus ++;
+        }
+        duData.push_back(DUData());
+        duData.back().accumBitsDU = ( numRBSPBytes << 3 );
+        duData.back().accumNalsDU = numNalus;
+      }
+    } // end iteration over slices
+
+    // cabac_zero_words processing
+    cabac_zero_word_padding(pcSlice, pcPic, binCountsInNalUnits, numBytesInVclNalUnits, accessUnit.back()->m_nalUnitData, m_pcCfg->getCabacZeroWordPaddingEnabled());
+#if NH_3D
+      pcPic->compressMotion(2); 
+#else
+    pcPic->compressMotion();
+#endif
+#if NH_MV
+      m_pocLastCoded = pcPic->getPOC();
+#endif
+
+    //-- For time output for each slice
+    Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+
+    std::string digestStr;
+    if (m_pcCfg->getDecodedPictureHashSEIEnabled())
+    {
+      SEIDecodedPictureHash *decodedPictureHashSei = new SEIDecodedPictureHash();
+      m_seiEncoder.initDecodedPictureHashSEI(decodedPictureHashSei, pcPic, digestStr, pcSlice->getSPS()->getBitDepths());
+      trailingSeiMessages.push_back(decodedPictureHashSei);
+    }
+    xWriteTrailingSEIMessages(trailingSeiMessages, accessUnit, pcSlice->getTLayer(), pcSlice->getSPS());
+
+    m_pcCfg->setEncodedFlag(iGOPid, true);
+
+    xCalculateAddPSNRs( isField, isTff, iGOPid, pcPic, accessUnit, rcListPic, dEncTime, snr_conversion, printFrameMSE );
+
+    if (!digestStr.empty())
+    {
+      if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
+      {
+        printf(" [MD5:%s]", digestStr.c_str());
+      }
+      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+      {
+        printf(" [CRC:%s]", digestStr.c_str());
+      }
+      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+      {
+        printf(" [Checksum:%s]", digestStr.c_str());
+      }
+    }
+
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+      Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
+      Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
+      if ( avgLambda < 0.0 )
+      {
+        avgLambda = lambda;
+      }
+
+      m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
+      m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
+
+      m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
+      if ( pcSlice->getSliceType() != I_SLICE )
+      {
+        m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
+      }
+      else    // for intra picture, the estimated bits are used to update the current status in the GOP
+      {
+        m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
+      }
+    }
+
+    xCreatePictureTimingSEI(m_pcCfg->getEfficientFieldIRAPEnabled()?effFieldIRAPMap.GetIRAPGOPid():0, leadingSeiMessages, nestedSeiMessages, duInfoSeiMessages, pcSlice, isField, duData);
+    if (m_pcCfg->getScalableNestingSEIEnabled())
+    {
+      xCreateScalableNestingSEI (leadingSeiMessages, nestedSeiMessages);
+    }
+    xWriteLeadingSEIMessages(leadingSeiMessages, duInfoSeiMessages, accessUnit, pcSlice->getTLayer(), pcSlice->getSPS(), duData);
+    xWriteDuSEIMessages(duInfoSeiMessages, accessUnit, pcSlice->getTLayer(), pcSlice->getSPS(), duData);
+
+    pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
+
+    pcPic->setReconMark   ( true );
+#if NH_MV
       TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer0, m_refPicSetInterLayer1 );  
       std::vector<Int> temp; 
       TComSlice::markCurrPic( pcPic ); 
 #endif
-      m_bFirst = false;
-      m_iNumPicCoded++;
-      m_totalCoded ++;
-      /* logging: insert a newline at end of picture period */
-      printf("\n");
-      fflush(stdout);
-
-      delete[] pcSubstreamsOut;
-
-#if EFFICIENT_FIELD_IRAP
-    if(IRAPtoReorder)
-    {
-      if(swapIRAPForward)
-      {
-        if(iGOPid == IRAPGOPid)
-        {
-          iGOPid = IRAPGOPid +1;
-          IRAPtoReorder = false;
-        }
-        else if(iGOPid == IRAPGOPid +1)
-        {
-          iGOPid --;
-        }
-      }
-      else
-      {
-        if(iGOPid == IRAPGOPid)
-        {
-          iGOPid = IRAPGOPid -1;
-        }
-        else if(iGOPid == IRAPGOPid -1)
-        {
-          iGOPid = IRAPGOPid;
-          IRAPtoReorder = false;
-        }
-      }
-    }
-#endif
-  }
+    m_bFirst = false;
+    m_iNumPicCoded++;
+    m_totalCoded ++;
+    /* logging: insert a newline at end of picture period */
+    printf("\n");
+    fflush(stdout);
+
+    if (m_pcCfg->getEfficientFieldIRAPEnabled())
+    {
+    iGOPid=effFieldIRAPMap.restoreGOPid(iGOPid);
+    }
+  } // iGOPid-loop
+
   delete pcBitstreamRedirect;
 
-  if( accumBitsDU != NULL) delete accumBitsDU;
-  if( accumNalsDU != NULL) delete accumNalsDU;
-
-#if !H_MV
-  assert ( (m_iNumPicCoded == iNumPicRcvd) || (isField && iPOCLast == 1) );
-#endif
-}
-
-#if !H_MV
-Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, bool isField)
+#if !NH_MV
+  assert ( (m_iNumPicCoded == iNumPicRcvd) );
+#endif
+}
+
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths)
 {
   assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
-  
-    
+
+
   //--CFG_KDY
-  if(isField)
-  {
-    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() * 2);
-    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() * 2);
-    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() * 2);
-    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() * 2);
-  }
-  else
-  {
-  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
-  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
-  }
-  
+  const Int rateMultiplier=(isField?2:1);
+  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  const ChromaFormat chFmt = m_pcCfg->getChromaFormatIdc();
+
   //-- all
+#if NH_MV
+  printf( "\n\nSUMMARY -------------------------------------------- LayerId %2d\n", getLayerId() );   
+#else
   printf( "\n\nSUMMARY --------------------------------------------------------\n" );
-  m_gcAnalyzeAll.printOut('a');
-  
+#endif
+  m_gcAnalyzeAll.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
   printf( "\n\nI Slices--------------------------------------------------------\n" );
-  m_gcAnalyzeI.printOut('i');
-  
+  m_gcAnalyzeI.printOut('i', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
   printf( "\n\nP Slices--------------------------------------------------------\n" );
-  m_gcAnalyzeP.printOut('p');
-  
+  m_gcAnalyzeP.printOut('p', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
   printf( "\n\nB Slices--------------------------------------------------------\n" );
-  m_gcAnalyzeB.printOut('b');
-  
-#if _SUMMARY_OUT_
-  m_gcAnalyzeAll.printSummaryOut();
-#endif
-#if _SUMMARY_PIC_
-  m_gcAnalyzeI.printSummary('I');
-  m_gcAnalyzeP.printSummary('P');
-  m_gcAnalyzeB.printSummary('B');
-#endif
+  m_gcAnalyzeB.printOut('b', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
+  if (!m_pcCfg->getSummaryOutFilename().empty())
+  {
+    m_gcAnalyzeAll.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryOutFilename());
+  }
+
+  if (!m_pcCfg->getSummaryPicFilenameBase().empty())
+  {
+    m_gcAnalyzeI.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryPicFilenameBase()+"I.txt");
+    m_gcAnalyzeP.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryPicFilenameBase()+"P.txt");
+    m_gcAnalyzeB.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryPicFilenameBase()+"B.txt");
+  }
 
   if(isField)
@@ -2421,34 +2139,33 @@
     //-- interlaced summary
     m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
+    m_gcAnalyzeAll_in.setBits(m_gcAnalyzeAll.getBits());
+    // prior to the above statement, the interlace analyser does not contain the correct total number of bits.
+
     printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
-    m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll.getBits());
-    
-#if _SUMMARY_OUT_
-    m_gcAnalyzeAll_in.printSummaryOutInterlaced();
-#endif
+    m_gcAnalyzeAll_in.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+
+    if (!m_pcCfg->getSummaryOutFilename().empty())
+    {
+      m_gcAnalyzeAll_in.printSummary(chFmt, printSequenceMSE, bitDepths, m_pcCfg->getSummaryOutFilename());
+    }
   }
 
   printf("\nRVM: %.3lf\n" , xCalculateRVM());
 }
-#endif
-#if H_3D_VSO
-Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, Dist64& ruiDist, UInt64& ruiBits )
+
+#if NH_3D_VSO
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, Dist64& ruiDist )
 #else
-Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
-#endif
-{
-  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist )
+#endif
+{
   Bool bCalcDist = false;
   m_pcLoopFilter->setCfg(m_pcCfg->getLFCrossTileBoundaryFlag());
   m_pcLoopFilter->loopFilterPic( pcPic );
-  
-  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
-  m_pcEntropyCoder->resetEntropy    ();
-  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
-  m_pcEntropyCoder->resetEntropy    ();
-  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
-  
+
   if (!bCalcDist)
-    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
+  {
+    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec(), pcPic->getPicSym()->getSPS().getBitDepths());
+  }
 }
 
@@ -2458,5 +2175,5 @@
 
 
-Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField )
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, Bool isField )
 {
   assert( iNumPicRcvd > 0 );
@@ -2471,7 +2188,8 @@
   }
   assert (m_iGopSize > 0);
-  
+
   return;
 }
+
 
 Void TEncGOP::xGetBuffer( TComList<TComPic*>&      rcListPic,
@@ -2482,35 +2200,22 @@
                          TComPicYuv*&              rpcPicYuvRecOut,
                          Int                       pocCurr,
-                         bool                      isField)
+                         Bool                      isField)
 {
   Int i;
   //  Rec. output
   TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
-  
-  if (isField)
-  {
-    for ( i = 0; i < ( (pocCurr == 0 ) || (pocCurr == 1 ) ? (iNumPicRcvd - iTimeOffset + 1) : (iNumPicRcvd - iTimeOffset + 2) ); i++ )
-    {
-      iterPicYuvRec--;
-    }
-  }
-  else
-  {
-    for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
+
+  if (isField && pocCurr > 1 && m_iGopSize!=1)
+  {
+    iTimeOffset--;
+  }
+
+  for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
   {
     iterPicYuvRec--;
   }
-  
-  }
-  
-  if (isField)
-  {
-    if(pocCurr == 1)
-    {
-      iterPicYuvRec++;
-    }
-  }
+
   rpcPicYuvRecOut = *(iterPicYuvRec);
-  
+
   //  Current pic.
   TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
@@ -2526,149 +2231,163 @@
   }
 
-#if !H_MV
-  assert( rpcPic != NULL );
+#if !NH_MV
+  assert (rpcPic != NULL);
 #endif
   assert (rpcPic->getPOC() == pocCurr);
-  
+
   return;
 }
 
-#if H_3D_VSO
-Dist64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
+#if NH_3D_VSO
+Dist64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1, const BitDepths &bitDepths)
 #else
-UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
-#endif
-{
-  Int     x, y;
-  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
-  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
-  UInt  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
-  Int   iTemp;
-  
-  Int   iStride = pcPic0->getStride();
-  Int   iWidth  = pcPic0->getWidth();
-  Int   iHeight = pcPic0->getHeight();
-  
-#if H_3D_VSO
+UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1, const BitDepths &bitDepths)
+#endif
+{
+#if NH_3D_VSO
   Dist64  uiTotalDiff = 0;
 #else
   UInt64  uiTotalDiff = 0;
 #endif
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
-    }
-    pSrc0 += iStride;
-    pSrc1 += iStride;
-  }
-  
-  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
-  iHeight >>= 1;
-  iWidth  >>= 1;
-  iStride >>= 1;
-  
-  pSrc0  = pcPic0->getCbAddr();
-  pSrc1  = pcPic1->getCbAddr();
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
-    }
-    pSrc0 += iStride;
-    pSrc1 += iStride;
-  }
-  
-  pSrc0  = pcPic0->getCrAddr();
-  pSrc1  = pcPic1->getCrAddr();
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
-    }
-    pSrc0 += iStride;
-    pSrc1 += iStride;
-  }
-  
+
+  for(Int chan=0; chan<pcPic0 ->getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    Pel*  pSrc0   = pcPic0 ->getAddr(ch);
+    Pel*  pSrc1   = pcPic1 ->getAddr(ch);
+    UInt  uiShift     = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepths.recon[toChannelType(ch)]-8);
+
+    const Int   iStride = pcPic0->getStride(ch);
+    const Int   iWidth  = pcPic0->getWidth(ch);
+    const Int   iHeight = pcPic0->getHeight(ch);
+
+    for(Int y = 0; y < iHeight; y++ )
+    {
+      for(Int x = 0; x < iWidth; x++ )
+      {
+        Intermediate_Int iTemp = pSrc0[x] - pSrc1[x];
+        uiTotalDiff += UInt64((iTemp*iTemp) >> uiShift);
+      }
+      pSrc0 += iStride;
+      pSrc1 += iStride;
+    }
+  }
+
   return uiTotalDiff;
 }
 
-#if VERBOSE_RATE
-static const Char* nalUnitTypeToString(NalUnitType type)
-{
-  switch (type)
-  {
-    case NAL_UNIT_CODED_SLICE_TRAIL_R: return "TRAIL_R";
-    case NAL_UNIT_CODED_SLICE_TRAIL_N: return "TRAIL_N";
-    case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
-    case NAL_UNIT_CODED_SLICE_TSA_N: return "TSA_N";
-    case NAL_UNIT_CODED_SLICE_STSA_R: return "STSA_R";
-    case NAL_UNIT_CODED_SLICE_STSA_N: return "STSA_N";
-    case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
-    case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
-    case NAL_UNIT_CODED_SLICE_BLA_N_LP: return "BLA_N_LP";
-    case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
-    case NAL_UNIT_CODED_SLICE_IDR_N_LP: return "IDR_N_LP";
-    case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
-    case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
-    case NAL_UNIT_CODED_SLICE_RADL_N:     return "RADL_N";
-    case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
-    case NAL_UNIT_CODED_SLICE_RASL_N:     return "RASL_N";
-    case NAL_UNIT_VPS: return "VPS";
-    case NAL_UNIT_SPS: return "SPS";
-    case NAL_UNIT_PPS: return "PPS";
-    case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
-    case NAL_UNIT_EOS: return "EOS";
-    case NAL_UNIT_EOB: return "EOB";
-    case NAL_UNIT_FILLER_DATA: return "FILLER";
-    case NAL_UNIT_PREFIX_SEI:             return "SEI";
-    case NAL_UNIT_SUFFIX_SEI:             return "SEI";
-    default: return "UNK";
-  }
-}
-#endif
-
-Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime )
-{
-  Int     x, y;
-  UInt64 uiSSDY  = 0;
-  UInt64 uiSSDU  = 0;
-  UInt64 uiSSDV  = 0;
-  
-  Double  dYPSNR  = 0.0;
-  Double  dUPSNR  = 0.0;
-  Double  dVPSNR  = 0.0;
-  
+Void TEncGOP::xCalculateAddPSNRs( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, const Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE )
+{
+  xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime, snr_conversion, printFrameMSE );
+
+  //In case of field coding, compute the interlaced PSNR for both fields
+  if(isField)
+  {
+    Bool bothFieldsAreEncoded = false;
+    Int correspondingFieldPOC = pcPic->getPOC();
+    Int currentPicGOPPoc = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    if(pcPic->getPOC() == 0)
+    {
+      // particular case for POC 0 and 1.
+      // If they are not encoded first and separately from other pictures, we need to change this
+      // POC 0 is always encoded first then POC 1 is encoded
+      bothFieldsAreEncoded = false;
+    }
+    else if(pcPic->getPOC() == 1)
+    {
+      // if we are at POC 1, POC 0 has been encoded for sure
+      correspondingFieldPOC = 0;
+      bothFieldsAreEncoded = true;
+    }
+    else
+    {
+      if(pcPic->getPOC()%2 == 1)
+      {
+        correspondingFieldPOC -= 1; // all odd POC are associated with the preceding even POC (e.g poc 1 is associated to poc 0)
+        currentPicGOPPoc      -= 1;
+      }
+      else
+      {
+        correspondingFieldPOC += 1; // all even POC are associated with the following odd POC (e.g poc 0 is associated to poc 1)
+        currentPicGOPPoc      += 1;
+      }
+      for(Int i = 0; i < m_iGopSize; i ++)
+      {
+        if(m_pcCfg->getGOPEntry(i).m_POC == currentPicGOPPoc)
+        {
+          bothFieldsAreEncoded = m_pcCfg->getGOPEntry(i).m_isEncoded;
+          break;
+        }
+      }
+    }
+
+    if(bothFieldsAreEncoded)
+    {
+      //get complementary top field
+      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+      while ((*iterPic)->getPOC() != correspondingFieldPOC)
+      {
+        iterPic ++;
+      }
+      TComPic* correspondingFieldPic = *(iterPic);
+
+      if( (pcPic->isTopField() && isFieldTopFieldFirst) || (!pcPic->isTopField() && !isFieldTopFieldFirst))
+      {
+        xCalculateInterlacedAddPSNR(pcPic, correspondingFieldPic, pcPic->getPicYuvRec(), correspondingFieldPic->getPicYuvRec(), snr_conversion, printFrameMSE );
+      }
+      else
+      {
+        xCalculateInterlacedAddPSNR(correspondingFieldPic, pcPic, correspondingFieldPic->getPicYuvRec(), pcPic->getPicYuvRec(), snr_conversion, printFrameMSE );
+      }
+    }
+  }
+}
+
+Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime, const InputColourSpaceConversion conversion, const Bool printFrameMSE )
+{
+  Double  dPSNR[MAX_NUM_COMPONENT];
+
+  for(Int i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    dPSNR[i]=0.0;
+  }
+
+  TComPicYuv cscd;
+  if (conversion!=IPCOLOURSPACE_UNCHANGED)
+  {
+    cscd.create(pcPicD->getWidth(COMPONENT_Y), pcPicD->getHeight(COMPONENT_Y), pcPicD->getChromaFormat(), pcPicD->getWidth(COMPONENT_Y), pcPicD->getHeight(COMPONENT_Y), 0, false);
+    TVideoIOYuv::ColourSpaceConvert(*pcPicD, cscd, conversion, false);
+  }
+  TComPicYuv &picd=(conversion==IPCOLOURSPACE_UNCHANGED)?*pcPicD : cscd;
+
   //===== calculate PSNR =====
-  Pel*  pOrg    = pcPic ->getPicYuvOrg()->getLumaAddr();
-  Pel*  pRec    = pcPicD->getLumaAddr();
-  Int   iStride = pcPicD->getStride();
-  
-  Int   iWidth;
-  Int   iHeight;
-  
-  iWidth  = pcPicD->getWidth () - m_pcEncTop->getPad(0);
-  iHeight = pcPicD->getHeight() - m_pcEncTop->getPad(1);
-  
-  Int   iSize   = iWidth*iHeight;
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrg[x] - pRec[x] );
-      uiSSDY   += iDiff * iDiff;
-    }
-    pOrg += iStride;
-    pRec += iStride;
-  }
-  
-#if H_3D_VSO
+  Double MSEyuvframe[MAX_NUM_COMPONENT] = {0, 0, 0};
+
+  for(Int chan=0; chan<pcPicD->getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    const TComPicYuv *pOrgPicYuv =(conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg() : pcPic ->getPicYuvOrg();
+    const Pel*  pOrg       = pOrgPicYuv->getAddr(ch);
+    const Int   iOrgStride = pOrgPicYuv->getStride(ch);
+    Pel*  pRec    = picd.getAddr(ch);
+    const Int   iRecStride = picd.getStride(ch);
+
+    const Int   iWidth  = pcPicD->getWidth (ch) - (m_pcEncTop->getPad(0) >> pcPic->getComponentScaleX(ch));
+    const Int   iHeight = pcPicD->getHeight(ch) - ((m_pcEncTop->getPad(1) >> (pcPic->isField()?1:0)) >> pcPic->getComponentScaleY(ch));
+
+    Int   iSize   = iWidth*iHeight;
+
+    UInt64 uiSSDtemp=0;
+    for(Int y = 0; y < iHeight; y++ )
+    {
+      for(Int x = 0; x < iWidth; x++ )
+      {
+        Intermediate_Int iDiff = (Intermediate_Int)( pOrg[x] - pRec[x] );
+        uiSSDtemp   += iDiff * iDiff;
+      }
+      pOrg += iOrgStride;
+      pRec += iRecStride;
+    }
+#if NH_3D_VSO
 #if H_3D_VSO_SYNTH_DIST_OUT
   if ( m_pcRdCost->getUseRenModel() )
@@ -2688,47 +2407,15 @@
 #endif
 #endif
-    iHeight >>= 1;
-  iWidth  >>= 1;
-  iStride >>= 1;
-  pOrg  = pcPic ->getPicYuvOrg()->getCbAddr();
-  pRec  = pcPicD->getCbAddr();
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrg[x] - pRec[x] );
-      uiSSDU   += iDiff * iDiff;
-    }
-    pOrg += iStride;
-    pRec += iStride;
-  }
-  
-  pOrg  = pcPic ->getPicYuvOrg()->getCrAddr();
-  pRec  = pcPicD->getCrAddr();
-  
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrg[x] - pRec[x] );
-      uiSSDV   += iDiff * iDiff;
-    }
-    pOrg += iStride;
-    pRec += iStride;
-  }
-  
-  Int maxvalY = 255 << (g_bitDepthY-8);
-  Int maxvalC = 255 << (g_bitDepthC-8);
-  Double fRefValueY = (Double) maxvalY * maxvalY * iSize;
-  Double fRefValueC = (Double) maxvalC * maxvalC * iSize / 4.0;
-  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
-  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
-  dVPSNR            = ( uiSSDV ? 10.0 * log10( fRefValueC / (Double)uiSSDV ) : 99.99 );
-#if H_3D_VSO
+    const Int maxval = 255 << (pcPic->getPicSym()->getSPS().getBitDepth(toChannelType(ch)) - 8);
+    const Double fRefValue = (Double) maxval * maxval * iSize;
+    dPSNR[ch]         = ( uiSSDtemp ? 10.0 * log10( fRefValue / (Double)uiSSDtemp ) : 999.99 );
+    MSEyuvframe[ch]   = (Double)uiSSDtemp/(iSize);
+  }
+
+#if NH_3D_VSO
 #if H_3D_VSO_SYNTH_DIST_OUT
 }
 #endif 
-#endif
+#endif  
   /* calculate the size of the access unit, excluding:
    *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
@@ -2739,7 +2426,8 @@
   {
     UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
-#if VERBOSE_RATE
+    if (m_pcCfg->getSummaryVerboseness() > 0)
+    {
     printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
-#endif
+    }
     if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
     {
@@ -2752,40 +2440,28 @@
 
   //===== add PSNR =====
-#if H_MV
-  m_pcEncTop->getAnalyzeAll()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#else
-  m_gcAnalyzeAll.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#endif
+  m_gcAnalyzeAll.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+
   TComSlice*  pcSlice = pcPic->getSlice(0);
   if (pcSlice->isIntra())
   {
-#if H_MV
-    m_pcEncTop->getAnalyzeI()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#else
-    m_gcAnalyzeI.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#endif
+    m_gcAnalyzeI.addResult (dPSNR, (Double)uibits, MSEyuvframe);
   }
   if (pcSlice->isInterP())
   {
-#if H_MV
-    m_pcEncTop->getAnalyzeP()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#else
-    m_gcAnalyzeP.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#endif
+    m_gcAnalyzeP.addResult (dPSNR, (Double)uibits, MSEyuvframe);
   }
   if (pcSlice->isInterB())
   {
-#if H_MV
-    m_pcEncTop->getAnalyzeB()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#else
-    m_gcAnalyzeB.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
-#endif
+    m_gcAnalyzeB.addResult (dPSNR, (Double)uibits, MSEyuvframe);
   }
 
   Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
-  if (!pcSlice->isReferenced()) c += 32;
+  if (!pcSlice->isReferenced())
+  {
+    c += 32;
+  }
 
 #if ADAPTIVE_QP_SELECTION
-#if H_MV
+#if NH_MV
   printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d  bits",
     pcSlice->getLayerId(),
@@ -2806,5 +2482,5 @@
 #endif
 #else
-#if H_MV
+#if NH_MV
   printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
     pcSlice->getLayerId(),
@@ -2823,8 +2499,15 @@
 #endif
 #endif
-
-  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
+#if NH_MV
+  printf(" [Y %8.4lf dB    U %8.4lf dB    V %8.4lf dB]", dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+#else
+  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+#endif
+  if (printFrameMSE)
+  {
+    printf(" [Y MSE %6.4lf  U MSE %6.4lf  V MSE %6.4lf]", MSEyuvframe[COMPONENT_Y], MSEyuvframe[COMPONENT_Cb], MSEyuvframe[COMPONENT_Cr] );
+  }
   printf(" [ET %5.0f ]", dEncTime );
-  
+
   for (Int iRefList = 0; iRefList < 2; iRefList++)
   {
@@ -2832,5 +2515,5 @@
     for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
     {
-#if H_MV
+#if NH_MV
       if( pcSlice->getLayerId() != pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) )
       {
@@ -2841,5 +2524,5 @@
 #endif
       printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
-#if H_MV
+#if NH_MV
       }
 #endif
@@ -2847,172 +2530,107 @@
     printf("]");
   }
-}
-
-
-Void reinterlace(Pel* top, Pel* bottom, Pel* dst, UInt stride, UInt width, UInt height, bool isTff)
-{
-  
-  for (Int y = 0; y < height; y++)
-  {
-    for (Int x = 0; x < width; x++)
-    {
-      dst[x] = isTff ? top[x] : bottom[x];
-      dst[stride+x] = isTff ? bottom[x] : top[x];
-    }
-    top += stride;
-    bottom += stride;
-    dst += stride*2;
-  }
-}
-
-
-Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime )
-{
-#if  H_MV
+
+  cscd.destroy();
+}
+
+Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgFirstField, TComPic* pcPicOrgSecondField,
+                                           TComPicYuv* pcPicRecFirstField, TComPicYuv* pcPicRecSecondField,
+                                           const InputColourSpaceConversion conversion, const Bool printFrameMSE )
+{
+
+#if  NH_MV
   assert( 0 ); // Field coding and MV need to be aligned. 
 #else
-  Int     x, y;
-  
-  UInt64 uiSSDY_in  = 0;
-  UInt64 uiSSDU_in  = 0;
-  UInt64 uiSSDV_in  = 0;
-  
-  Double  dYPSNR_in  = 0.0;
-  Double  dUPSNR_in  = 0.0;
-  Double  dVPSNR_in  = 0.0;
-  
-  /*------ INTERLACED PSNR -----------*/
-  
-  /* Luma */
-  
-  Pel*  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getLumaAddr();
-  Pel*  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getLumaAddr();
-  Pel*  pRecTop = pcPicRecTop->getLumaAddr();
-  Pel*  pRecBottom = pcPicRecBottom->getLumaAddr();
-  
-  Int   iWidth;
-  Int   iHeight;
-  Int iStride;
-  
-  iWidth  = pcPicOrgTop->getPicYuvOrg()->getWidth () - m_pcEncTop->getPad(0);
-  iHeight = pcPicOrgTop->getPicYuvOrg()->getHeight() - m_pcEncTop->getPad(1);
-  iStride = pcPicOrgTop->getPicYuvOrg()->getStride();
-  Int   iSize   = iWidth*iHeight;
-  bool isTff = pcPicOrgTop->isTopField();
-  
-  TComPicYuv* pcOrgInterlaced = new TComPicYuv;
-  pcOrgInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
-  
-  TComPicYuv* pcRecInterlaced = new TComPicYuv;
-  pcRecInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
-  
-  Pel* pOrgInterlaced = pcOrgInterlaced->getLumaAddr();
-  Pel* pRecInterlaced = pcRecInterlaced->getLumaAddr();
-  
-  //=== Interlace fields ====
-  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
-  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
-  
+
+  const TComSPS &sps=pcPicOrgFirstField->getPicSym()->getSPS();
+  Double  dPSNR[MAX_NUM_COMPONENT];
+  TComPic    *apcPicOrgFields[2]={pcPicOrgFirstField, pcPicOrgSecondField};
+  TComPicYuv *apcPicRecFields[2]={pcPicRecFirstField, pcPicRecSecondField};
+
+  for(Int i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    dPSNR[i]=0.0;
+  }
+
+  TComPicYuv cscd[2 /* first/second field */];
+  if (conversion!=IPCOLOURSPACE_UNCHANGED)
+  {
+    for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+    {
+      TComPicYuv &reconField=*(apcPicRecFields[fieldNum]);
+      cscd[fieldNum].create(reconField.getWidth(COMPONENT_Y), reconField.getHeight(COMPONENT_Y), reconField.getChromaFormat(), reconField.getWidth(COMPONENT_Y), reconField.getHeight(COMPONENT_Y), 0, false);
+      TVideoIOYuv::ColourSpaceConvert(reconField, cscd[fieldNum], conversion, false);
+      apcPicRecFields[fieldNum]=cscd+fieldNum;
+    }
+  }
+
   //===== calculate PSNR =====
-  for( y = 0; y < iHeight << 1; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
-      uiSSDY_in   += iDiff * iDiff;
-    }
-    pOrgInterlaced += iStride;
-    pRecInterlaced += iStride;
-  }
-  
-  /*Chroma*/
-  
-  iHeight >>= 1;
-  iWidth  >>= 1;
-  iStride >>= 1;
-  
-  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCbAddr();
-  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCbAddr();
-  pRecTop = pcPicRecTop->getCbAddr();
-  pRecBottom = pcPicRecBottom->getCbAddr();
-  pOrgInterlaced = pcOrgInterlaced->getCbAddr();
-  pRecInterlaced = pcRecInterlaced->getCbAddr();
-  
-  //=== Interlace fields ====
-  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
-  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
-  
-  //===== calculate PSNR =====
-  for( y = 0; y < iHeight << 1; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
-      uiSSDU_in   += iDiff * iDiff;
-    }
-    pOrgInterlaced += iStride;
-    pRecInterlaced += iStride;
-  }
-  
-  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCrAddr();
-  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCrAddr();
-  pRecTop = pcPicRecTop->getCrAddr();
-  pRecBottom = pcPicRecBottom->getCrAddr();
-  pOrgInterlaced = pcOrgInterlaced->getCrAddr();
-  pRecInterlaced = pcRecInterlaced->getCrAddr();
-  
-  //=== Interlace fields ====
-  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
-  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
-  
-  //===== calculate PSNR =====
-  for( y = 0; y < iHeight << 1; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
-      uiSSDV_in   += iDiff * iDiff;
-    }
-    pOrgInterlaced += iStride;
-    pRecInterlaced += iStride;
-  }
-  
-  Int maxvalY = 255 << (g_bitDepthY-8);
-  Int maxvalC = 255 << (g_bitDepthC-8);
-  Double fRefValueY = (Double) maxvalY * maxvalY * iSize*2;
-  Double fRefValueC = (Double) maxvalC * maxvalC * iSize*2 / 4.0;
-  dYPSNR_in            = ( uiSSDY_in ? 10.0 * log10( fRefValueY / (Double)uiSSDY_in ) : 99.99 );
-  dUPSNR_in            = ( uiSSDU_in ? 10.0 * log10( fRefValueC / (Double)uiSSDU_in ) : 99.99 );
-  dVPSNR_in            = ( uiSSDV_in ? 10.0 * log10( fRefValueC / (Double)uiSSDV_in ) : 99.99 );
-  
-  /* calculate the size of the access unit, excluding:
-   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
-   *  - SEI NAL units
-   */
-  UInt numRBSPBytes = 0;
-  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
-  {
-    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
-    
-    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
-      numRBSPBytes += numRBSPBytes_nal;
-  }
-  
-  UInt uibits = numRBSPBytes * 8 ;
-  
+  Double MSEyuvframe[MAX_NUM_COMPONENT] = {0, 0, 0};
+
+  assert(apcPicRecFields[0]->getChromaFormat()==apcPicRecFields[1]->getChromaFormat());
+  const UInt numValidComponents=apcPicRecFields[0]->getNumberValidComponents();
+
+  for(Int chan=0; chan<numValidComponents; chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    assert(apcPicRecFields[0]->getWidth(ch)==apcPicRecFields[1]->getWidth(ch));
+    assert(apcPicRecFields[0]->getHeight(ch)==apcPicRecFields[1]->getHeight(ch));
+
+    UInt64 uiSSDtemp=0;
+    const Int   iWidth  = apcPicRecFields[0]->getWidth (ch) - (m_pcEncTop->getPad(0) >> apcPicRecFields[0]->getComponentScaleX(ch));
+    const Int   iHeight = apcPicRecFields[0]->getHeight(ch) - ((m_pcEncTop->getPad(1) >> 1) >> apcPicRecFields[0]->getComponentScaleY(ch));
+
+    Int   iSize   = iWidth*iHeight;
+
+    for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+    {
+      TComPic *pcPic=apcPicOrgFields[fieldNum];
+      TComPicYuv *pcPicD=apcPicRecFields[fieldNum];
+
+      const Pel*  pOrg    = (conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg()->getAddr(ch) : pcPic ->getPicYuvOrg()->getAddr(ch);
+      Pel*  pRec    = pcPicD->getAddr(ch);
+      const Int   iStride = pcPicD->getStride(ch);
+
+
+      for(Int y = 0; y < iHeight; y++ )
+      {
+        for(Int x = 0; x < iWidth; x++ )
+        {
+          Intermediate_Int iDiff = (Intermediate_Int)( pOrg[x] - pRec[x] );
+          uiSSDtemp   += iDiff * iDiff;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+    const Int maxval = 255 << (sps.getBitDepth(toChannelType(ch)) - 8);
+    const Double fRefValue = (Double) maxval * maxval * iSize*2;
+    dPSNR[ch]         = ( uiSSDtemp ? 10.0 * log10( fRefValue / (Double)uiSSDtemp ) : 999.99 );
+    MSEyuvframe[ch]   = (Double)uiSSDtemp/(iSize*2);
+  }
+
+  UInt uibits = 0; // the number of bits for the pair is not calculated here - instead the overall total is used elsewhere.
+
   //===== add PSNR =====
-  m_gcAnalyzeAll_in.addResult (dYPSNR_in, dUPSNR_in, dVPSNR_in, (Double)uibits);
-  
-  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgBottom->getPOC()/2 , dYPSNR_in, dUPSNR_in, dVPSNR_in );
-  
-  pcOrgInterlaced->destroy();
-  delete pcOrgInterlaced;
-  pcRecInterlaced->destroy();
-  delete pcRecInterlaced;
-#endif
-}
+  m_gcAnalyzeAll_in.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+
+  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgSecondField->getPOC()/2 , dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+  if (printFrameMSE)
+  {
+    printf(" [Y MSE %6.4lf  U MSE %6.4lf  V MSE %6.4lf]", MSEyuvframe[COMPONENT_Y], MSEyuvframe[COMPONENT_Cb], MSEyuvframe[COMPONENT_Cr] );
+  }
+
+  for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+  {
+    cscd[fieldNum].destroy();
+  }
+#endif
+}
+
 /** Function for deciding the nal_unit_type.
  * \param pocCurr POC of the current picture
- * \returns the nal unit type of the picture
+ * \param lastIDR  POC of the last IDR picture
+ * \param isField  true to indicate field coding
+ * \returns the NAL unit type of the picture
  * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
  */
@@ -3023,17 +2641,12 @@
     return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
   }
-#if EFFICIENT_FIELD_IRAP
-  if(isField && pocCurr == 1)
+
+  if(m_pcCfg->getEfficientFieldIRAPEnabled() && isField && pocCurr == 1)
   {
     // to avoid the picture becoming an IRAP
     return NAL_UNIT_CODED_SLICE_TRAIL_R;
   }
-#endif
-
-#if ALLOW_RECOVERY_POINT_AS_RAP
+
   if(m_pcCfg->getDecodingRefreshType() != 3 && (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
-#else
-  if ((pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
-#endif
   {
     if (m_pcCfg->getDecodingRefreshType() == 1)
@@ -3050,8 +2663,8 @@
     if(pocCurr<m_pocCRA)
     {
-      // All leading pictures are being marked as TFD pictures here since current encoder uses all 
-      // reference pictures while encoding leading pictures. An encoder can ensure that a leading 
-      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by 
-      // controlling the reference pictures used for encoding that leading picture. Such a leading 
+      // All leading pictures are being marked as TFD pictures here since current encoder uses all
+      // reference pictures while encoding leading pictures. An encoder can ensure that a leading
+      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by
+      // controlling the reference pictures used for encoding that leading picture. Such a leading
       // picture need not be marked as a TFD picture.
       return NAL_UNIT_CODED_SLICE_RASL_R;
@@ -3068,8 +2681,9 @@
 }
 
+
 Double TEncGOP::xCalculateRVM()
 {
   Double dRVM = 0;
-  
+
   if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFramesToBeEncoded() > RVM_VCEGAM10_M * 2 )
   {
@@ -3079,5 +2693,5 @@
     vRL.resize( N );
     vB.resize( N );
-    
+
     Int i;
     Double dRavg = 0 , dBavg = 0;
@@ -3087,5 +2701,7 @@
       vRL[i] = 0;
       for( Int j = i - RVM_VCEGAM10_M ; j <= i + RVM_VCEGAM10_M - 1 ; j++ )
+      {
         vRL[i] += m_vRVM_RP[j];
+      }
       vRL[i] /= ( 2 * RVM_VCEGAM10_M );
       vB[i] = vB[i-1] + m_vRVM_RP[i] - vRL[i];
@@ -3093,8 +2709,8 @@
       dBavg += vB[i];
     }
-    
+
     dRavg /= ( N - 2 * RVM_VCEGAM10_M );
     dBavg /= ( N - 2 * RVM_VCEGAM10_M );
-    
+
     Double dSigamB = 0;
     for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
@@ -3104,13 +2720,12 @@
     }
     dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
-    
+
     Double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
-    
+
     dRVM = dSigamB / dRavg * f;
   }
-  
+
   return( dRVM );
 }
-
 /** Attaches the input bitstream to the stream in the output NAL unit
     Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
@@ -3118,5 +2733,5 @@
  *  \param rNalu          target NAL unit
  */
-Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& codedSliceData)
+Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream* codedSliceData)
 {
   // Byte-align
@@ -3125,5 +2740,5 @@
   // Perform bitstream concatenation
   if (codedSliceData->getNumberOfWrittenBits() > 0)
-    {
+  {
     rNalu.m_Bitstream.addSubstream(codedSliceData);
   }
@@ -3134,5 +2749,5 @@
 }
 
-// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt, 
+// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt,
 // and among the pictures with the same lsb, it arranges them in increasing delta_poc_msb_cycle_lt value
 Void TEncGOP::arrangeLongtermPicturesInRPS(TComSlice *pcSlice, TComList<TComPic*>& rcListPic)
@@ -3155,5 +2770,5 @@
   ::memset(mSBPresentFlag , 0, sizeof(mSBPresentFlag));     // Indicate if MSB needs to be present
 
-  // Get the long-term reference pictures 
+  // Get the long-term reference pictures
   Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
   Int i, ctr = 0;
@@ -3163,5 +2778,5 @@
     longtermPicsPoc[ctr] = rps->getPOC(i);                                  // LTRP POC
     longtermPicsLSB[ctr] = getLSB(longtermPicsPoc[ctr], maxPicOrderCntLSB); // LTRP POC LSB
-    indices[ctr]      = i; 
+    indices[ctr]      = i;
     longtermPicsMSB[ctr] = longtermPicsPoc[ctr] - longtermPicsLSB[ctr];
   }
@@ -3169,5 +2784,5 @@
   assert(ctr == numLongPics);
 
-  // Arrange pictures in decreasing order of MSB; 
+  // Arrange pictures in decreasing order of MSB;
   for(i = 0; i < numLongPics; i++)
   {
@@ -3188,5 +2803,5 @@
     // Check if MSB present flag should be enabled.
     // Check if the buffer contains any pictures that have the same LSB.
-    TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+    TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
     TComPic*                      pcPic;
     while ( iterPic != rcListPic.end() )
@@ -3200,5 +2815,5 @@
         break;
       }
-      iterPic++;      
+      iterPic++;
     }
   }
@@ -3214,5 +2829,5 @@
   Int currMSB = 0, currLSB = 0;
   // currPicPoc = currMSB + currLSB
-  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB);  
+  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB);
   currMSB = pcSlice->getPOC() - currLSB;
 
@@ -3224,5 +2839,5 @@
     rps->setPocLSBLT              (i, longtermPicsLSB[ctr]);
     rps->setDeltaPocMSBCycleLT    (i, (currMSB - (longtermPicsPoc[ctr] - longtermPicsLSB[ctr])) / maxPicOrderCntLSB);
-    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);     
+    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);
 
     assert(rps->getDeltaPocMSBCycleLT(i) >= 0);   // Non-negative value
@@ -3232,5 +2847,5 @@
     for(Int j = rps->getNumberOfPictures() - 1 - ctr; j >= offset; j--)
     {
-      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we 
+      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we
       // don't have to check the MSB present flag values for this constraint.
       assert( rps->getPOC(i) != rps->getPOC(j) ); // If assert fails, LTRP entry repeated in RPS!!!
@@ -3239,35 +2854,15 @@
 }
 
-/** Function for finding the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
- * \param accessUnit Access Unit of the current picture
- * This function finds the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
- */
-Int TEncGOP::xGetFirstSeiLocation(AccessUnit &accessUnit)
-{
-  // Find the location of the first SEI message
-  AccessUnit::iterator it;
-  Int seiStartPos = 0;
-  for(it = accessUnit.begin(); it != accessUnit.end(); it++, seiStartPos++)
-  {
-     if ((*it)->isSei() || (*it)->isVcl())
-     {
-       break;
-     }               
-  }
-//  assert(it != accessUnit.end());  // Triggers with some legit configurations
-  return seiStartPos;
-}
-
-Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
+Void TEncGOP::applyDeblockingFilterMetric( TComPic* pcPic, UInt uiNumSlices )
 {
   TComPicYuv* pcPicYuvRec = pcPic->getPicYuvRec();
-  Pel* Rec    = pcPicYuvRec->getLumaAddr( 0 );
+  Pel* Rec    = pcPicYuvRec->getAddr(COMPONENT_Y);
   Pel* tempRec = Rec;
-  Int  stride = pcPicYuvRec->getStride();
+  Int  stride = pcPicYuvRec->getStride(COMPONENT_Y);
   UInt log2maxTB = pcPic->getSlice(0)->getSPS()->getQuadtreeTULog2MaxSize();
   UInt maxTBsize = (1<<log2maxTB);
   const UInt minBlockArtSize = 8;
-  const UInt picWidth = pcPicYuvRec->getWidth();
-  const UInt picHeight = pcPicYuvRec->getHeight();
+  const UInt picWidth = pcPicYuvRec->getWidth(COMPONENT_Y);
+  const UInt picHeight = pcPicYuvRec->getHeight(COMPONENT_Y);
   const UInt noCol = (picWidth>>log2maxTB);
   const UInt noRows = (picHeight>>log2maxTB);
@@ -3279,15 +2874,16 @@
   UInt rowIdx = 0;
   Pel p0, p1, p2, q0, q1, q2;
-  
+
   Int qp = pcPic->getSlice(0)->getSliceQp();
-  Int bitdepthScale = 1 << (g_bitDepthY-8);
+  const Int bitDepthLuma=pcPic->getSlice(0)->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA);
+  Int bitdepthScale = 1 << (bitDepthLuma-8);
   Int beta = TComLoopFilter::getBeta( qp ) * bitdepthScale;
   const Int thr2 = (beta>>2);
   const Int thr1 = 2*bitdepthScale;
   UInt a = 0;
-  
+
   memset(colSAD, 0, noCol*sizeof(UInt64));
   memset(rowSAD, 0, noRows*sizeof(UInt64));
-  
+
   if (maxTBsize > minBlockArtSize)
   {
@@ -3313,5 +2909,5 @@
       Rec = tempRec;
     }
-    
+
     // Analyze horizontal artifact edges
     for(Int r = maxTBsize; r < picHeight; r += maxTBsize)
@@ -3334,5 +2930,5 @@
     }
   }
-  
+
   UInt64 colSADsum = 0;
   UInt64 rowSADsum = 0;
@@ -3345,5 +2941,5 @@
     rowSADsum += rowSAD[r];
   }
-  
+
   colSADsum <<= 10;
   rowSADsum <<= 10;
@@ -3352,8 +2948,8 @@
   rowSADsum /= (noRows-1);
   rowSADsum /= picWidth;
-  
+
   UInt64 avgSAD = ((colSADsum + rowSADsum)>>1);
-  avgSAD >>= (g_bitDepthY-8);
-  
+  avgSAD >>= (bitDepthLuma-8);
+
   if ( avgSAD > 2048 )
   {
@@ -3378,10 +2974,10 @@
     }
   }
-  
+
   free(colSAD);
   free(rowSAD);
 }
 
-#if H_MV
+#if NH_MV
 Void TEncGOP::xSetRefPicListModificationsMv( std::vector<TComPic*> tempPicLists[2], TComSlice* pcSlice, UInt iGOPid )
 { 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncGOP.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncGOP.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -54,4 +54,5 @@
 #include "TEncSbac.h"
 #include "SEIwrite.h"
+#include "SEIEncoder.h"
 
 #include "TEncAnalyze.h"
@@ -71,22 +72,37 @@
 // ====================================================================================================================
 
-/// GOP encoder class
 class TEncGOP
 {
+  class DUData
+  {
+  public:
+    DUData()
+    :accumBitsDU(0)
+    ,accumNalsDU(0) {};
+
+    Int accumBitsDU;
+    Int accumNalsDU;
+  };
+
 private:
+
+  TEncAnalyze             m_gcAnalyzeAll;
+  TEncAnalyze             m_gcAnalyzeI;
+  TEncAnalyze             m_gcAnalyzeP;
+  TEncAnalyze             m_gcAnalyzeB;
+
+  TEncAnalyze             m_gcAnalyzeAll_in;
   //  Data
   Bool                    m_bLongtermTestPictureHasBeenCoded;
   Bool                    m_bLongtermTestPictureHasBeenCoded2;
-  UInt            m_numLongTermRefPicSPS;
-  UInt            m_ltRefPicPocLsbSps[33];
-  Bool            m_ltRefPicUsedByCurrPicFlag[33];
+  UInt                    m_numLongTermRefPicSPS;
+  UInt                    m_ltRefPicPocLsbSps[MAX_NUM_LONG_TERM_REF_PICS];
+  Bool                    m_ltRefPicUsedByCurrPicFlag[MAX_NUM_LONG_TERM_REF_PICS];
   Int                     m_iLastIDR;
   Int                     m_iGopSize;
   Int                     m_iNumPicCoded;
   Bool                    m_bFirst;
-#if ALLOW_RECOVERY_POINT_AS_RAP
   Int                     m_iLastRecoveryPicPOC;
-#endif
-  
+
   //  Access channel
   TEncTop*                m_pcEncTop;
@@ -94,5 +110,5 @@
   TEncSlice*              m_pcSliceEncoder;
   TComList<TComPic*>*     m_pcListPic;
-  
+
   TEncEntropy*            m_pcEntropyCoder;
   TEncCavlc*              m_pcCavlcCoder;
@@ -102,6 +118,6 @@
 
   SEIWriter               m_seiWriter;
-  
-#if H_MV
+
+#if NH_MV
   TComPicLists*           m_ivPicLists;
   std::vector<TComPic*>   m_refPicSetInterLayer0; 
@@ -111,5 +127,5 @@
   Int                     m_layerId;  
   Int                     m_viewId;
-#if H_3D
+#if NH_3D
   Int                     m_viewIndex; 
   Bool                    m_isDepth;
@@ -122,51 +138,43 @@
   //--Adaptive Loop filter
   TEncSampleAdaptiveOffset*  m_pcSAO;
-  TComBitCounter*         m_pcBitCounter;
   TEncRateCtrl*           m_pcRateCtrl;
   // indicate sequence first
   Bool                    m_bSeqFirst;
-  
+
   // clean decoding refresh
   Bool                    m_bRefreshPending;
   Int                     m_pocCRA;
-  std::vector<Int>        m_storedStartCUAddrForEncodingSlice;
-  std::vector<Int>        m_storedStartCUAddrForEncodingSliceSegment;
-#if FIX1172
   NalUnitType             m_associatedIRAPType;
   Int                     m_associatedIRAPPOC;
-#endif
 
   std::vector<Int> m_vRVM_RP;
   UInt                    m_lastBPSEI;
   UInt                    m_totalCoded;
-  UInt                    m_cpbRemovalDelay;
-  UInt                    m_tl0Idx;
-  UInt                    m_rapIdx;
-  Bool                    m_activeParameterSetSEIPresentInAU;
   Bool                    m_bufferingPeriodSEIPresentInAU;
-  Bool                    m_pictureTimingSEIPresentInAU;
-  Bool                    m_nestedBufferingPeriodSEIPresentInAU;
-  Bool                    m_nestedPictureTimingSEIPresentInAU;
+  SEIEncoder              m_seiEncoder;
+
 public:
   TEncGOP();
   virtual ~TEncGOP();
-  
+
   Void  create      ();
   Void  destroy     ();
-  
+
   Void  init        ( TEncTop* pcTEncTop );
-#if H_MV
-  Void  initGOP     ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP);
-  Void  compressPicInGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, Bool isField, Bool isTff  );
+#if NH_MV
+  Void  initGOP     ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP);  
+  Void  compressPicInGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec,
+    std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Int iGOPid );
 #else
-  Void  compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff  );
-#endif
-  Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect);
-
-#if H_MV
+  Void  compressGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec,
+                      std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+#endif
+  Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream* pcBitstreamRedirect);
+
+#if NH_MV
   Int       getPocLastCoded  ()                 { return m_pocLastCoded; }  
   Int       getLayerId       ()                 { return m_layerId;    }  
   Int       getViewId        ()                 { return m_viewId;    }
-#if H_3D
+#if NH_3D
   Int       getViewIndex     ()                 { return m_viewIndex;    }
   Bool      getIsDepth       ()                 { return m_isDepth; }
@@ -175,14 +183,11 @@
 
   Int   getGOPSize()          { return  m_iGopSize;  }
-  
+
   TComList<TComPic*>*   getListPic()      { return m_pcListPic; }
-
-#if !H_MV
-  Void  printOutSummary      ( UInt uiNumAllPicCoded , bool isField);
-#endif
-#if H_3D_VSO
-  Void  preLoopFilterPicAll  ( TComPic* pcPic, Dist64& ruiDist, UInt64& ruiBits );
+  Void  printOutSummary      ( UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths );
+#if NH_3D_VSO
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, Dist64& ruiDist);
 #else
-  Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits );
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist );
 #endif
 
@@ -194,4 +199,5 @@
   NalUnitType getNalUnitType( Int pocCurr, Int lastIdr, Bool isField );
   Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
+
 protected:
   TEncRateCtrl* getRateCtrl()       { return m_pcRateCtrl;  }
@@ -199,62 +205,48 @@
 protected:
 
-  Void xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField );
-  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, bool isField );
-  
-  Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime );
-  Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime );
-
-#if H_3D_VSO
-  Dist64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
+  Void  xInitGOP          ( Int iPOCLast, Int iNumPicRcvd, Bool isField );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, Bool isField );
+
+  Void  xCalculateAddPSNRs         ( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+  Void  xCalculateAddPSNR          ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+  Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgFirstField, TComPic* pcPicOrgSecondField,
+                                     TComPicYuv* pcPicRecFirstField, TComPicYuv* pcPicRecSecondField,
+                                     const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+#if NH_3D_VSO
+  Dist64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1, const BitDepths &bitDepths);
 #else  
-  UInt64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
-#endif
-
+  UInt64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1, const BitDepths &bitDepths);
+#endif
   Double xCalculateRVM();
 
-  SEIActiveParameterSets* xCreateSEIActiveParameterSets (TComSPS *sps);
-  SEIFramePacking*        xCreateSEIFramePacking();
-  SEIDisplayOrientation*  xCreateSEIDisplayOrientation();
-
-  SEIToneMappingInfo*     xCreateSEIToneMappingInfo();
-#if H_MV
-  SEISubBitstreamProperty *xCreateSEISubBitstreamProperty( TComSPS *sps);
-#endif
-
-  Void xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps);
-  Int xGetFirstSeiLocation (AccessUnit &accessUnit);
-  Void xResetNonNestedSEIPresentFlags()
-  {
-    m_activeParameterSetSEIPresentInAU = false;
-    m_bufferingPeriodSEIPresentInAU    = false;
-    m_pictureTimingSEIPresentInAU      = false;
-  }
-  Void xResetNestedSEIPresentFlags()
-  {
-    m_nestedBufferingPeriodSEIPresentInAU    = false;
-    m_nestedPictureTimingSEIPresentInAU      = false;
-  }
-#if H_MV
+  Void xCreateIRAPLeadingSEIMessages (SEIMessages& seiMessages, const TComSPS *sps, const TComPPS *pps);
+  Void xCreatePerPictureSEIMessages (Int picInGOP, SEIMessages& seiMessages, SEIMessages& nestedSeiMessages, TComSlice *slice);
+  Void xCreatePictureTimingSEI  (Int IRAPGOPid, SEIMessages& seiMessages, SEIMessages& nestedSeiMessages, SEIMessages& duInfoSeiMessages, TComSlice *slice, Bool isField, std::deque<DUData> &duData);
+  Void xUpdateDuData(AccessUnit &testAU, std::deque<DUData> &duData);
+  Void xUpdateTimingSEI(SEIPictureTiming *pictureTimingSEI, std::deque<DUData> &duData, const TComSPS *sps);
+  Void xUpdateDuInfoSEI(SEIMessages &duInfoSeiMessages, SEIPictureTiming *pictureTimingSEI);
+
+  Void xCreateScalableNestingSEI (SEIMessages& seiMessages, SEIMessages& nestedSeiMessages);
+  Void xWriteSEI (NalUnitType naluType, SEIMessages& seiMessages, AccessUnit &accessUnit, AccessUnit::iterator &auPos, Int temporalId, const TComSPS *sps);
+  Void xWriteSEISeparately (NalUnitType naluType, SEIMessages& seiMessages, AccessUnit &accessUnit, AccessUnit::iterator &auPos, Int temporalId, const TComSPS *sps);
+  Void xClearSEIs(SEIMessages& seiMessages, Bool deleteMessages);
+  Void xWriteLeadingSEIOrdered (SEIMessages& seiMessages, SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, Bool testWrite);
+  Void xWriteLeadingSEIMessages  (SEIMessages& seiMessages, SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, std::deque<DUData> &duData);
+  Void xWriteTrailingSEIMessages (SEIMessages& seiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps);
+  Void xWriteDuSEIMessages       (SEIMessages& duInfoSeiMessages, AccessUnit &accessUnit, Int temporalId, const TComSPS *sps, std::deque<DUData> &duData);
+
+  Int xWriteVPS (AccessUnit &accessUnit, const TComVPS *vps);
+  Int xWriteSPS (AccessUnit &accessUnit, const TComSPS *sps);
+  Int xWritePPS (AccessUnit &accessUnit, const TComPPS *pps);
+  Int xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice);
+
+#if NH_MV
    Void  xSetRefPicListModificationsMv( std::vector<TComPic*> tempPicLists[2], TComSlice* pcSlice, UInt iGOPid );
 #endif
-  Void dblMetric( TComPic* pcPic, UInt uiNumSlices );
+
+
+  Void applyDeblockingFilterMetric( TComPic* pcPic, UInt uiNumSlices );
 };// END CLASS DEFINITION TEncGOP
 
-// ====================================================================================================================
-// Enumeration
-// ====================================================================================================================
-enum PROCESSING_STATE
-{
-  EXECUTE_INLOOPFILTER,
-  ENCODE_SLICE
-};
-
-enum SCALING_LIST_PARAMETER
-{
-  SCALING_LIST_OFF,
-  SCALING_LIST_DEFAULT,
-  SCALING_LIST_FILE_READ
-};
-
 //! \}
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPic.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPic.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -117,22 +117,20 @@
 
 /** Initialize member variables
- * \param iWidth Picture width
- * \param iHeight Picture height
- * \param uiMaxWidth Maximum CU width
- * \param uiMaxHeight Maximum CU height
- * \param uiMaxDepth Maximum CU depth
- * \param uiMaxAQDepth Maximum depth of unit block for assigning QP adaptive to local image characteristics
+ * \param sps reference to used SPS
+ * \param pps reference to used PPS
+ * \param uiMaxAdaptiveQPDepth Maximum depth of unit block for assigning QP adaptive to local image characteristics
  * \param bIsVirtual
- * \return Void
  */
-Void TEncPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth,  
-                      Window &conformanceWindow, Window &defaultDisplayWindow, Int *numReorderPics, Bool bIsVirtual )
+Void TEncPic::create( const TComSPS &sps, const TComPPS &pps, UInt uiMaxAdaptiveQPDepth, Bool bIsVirtual )
 {
-  TComPic::create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth,  
-                   conformanceWindow, defaultDisplayWindow, numReorderPics, bIsVirtual );
-  m_uiMaxAQDepth = uiMaxAQDepth;
-  if ( uiMaxAQDepth > 0 )
+  TComPic::create( sps, pps, bIsVirtual );
+  const Int  iWidth      = sps.getPicWidthInLumaSamples();
+  const Int  iHeight     = sps.getPicHeightInLumaSamples();
+  const UInt uiMaxWidth  = sps.getMaxCUWidth();
+  const UInt uiMaxHeight = sps.getMaxCUHeight();
+  m_uiMaxAQDepth = uiMaxAdaptiveQPDepth;
+  if ( uiMaxAdaptiveQPDepth > 0 )
   {
-    m_acAQLayer = new TEncPicQPAdaptationLayer[ m_uiMaxAQDepth ]; 
+    m_acAQLayer = new TEncPicQPAdaptationLayer[ m_uiMaxAQDepth ];
     for (UInt d = 0; d < m_uiMaxAQDepth; d++)
     {
@@ -142,7 +140,5 @@
 }
 
-/** Clean up
- * \return Void
- */
+//! Clean up
 Void TEncPic::destroy()
 {
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPic.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPic.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -103,6 +103,5 @@
   virtual ~TEncPic();
 
-  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth,   
-                        Window &conformanceWindow, Window &defaultDisplayWindow, Int *numReorderPics, Bool bIsVirtual = false );
+  Void          create( const TComSPS &sps, const TComPPS &pps, UInt uiMaxAdaptiveQPDepth, Bool bIsVirtual /* = false*/ );
   virtual Void  destroy();
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -65,11 +65,11 @@
 {
   TComPicYuv* pcPicYuv = pcEPic->getPicYuvOrg();
-  const Int iWidth = pcPicYuv->getWidth();
-  const Int iHeight = pcPicYuv->getHeight();
-  const Int iStride = pcPicYuv->getStride();
+  const Int iWidth = pcPicYuv->getWidth(COMPONENT_Y);
+  const Int iHeight = pcPicYuv->getHeight(COMPONENT_Y);
+  const Int iStride = pcPicYuv->getStride(COMPONENT_Y);
 
   for ( UInt d = 0; d < pcEPic->getMaxAQDepth(); d++ )
   {
-    const Pel* pLineY = pcPicYuv->getLumaAddr();
+    const Pel* pLineY = pcPicYuv->getAddr(COMPONENT_Y);
     TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer(d);
     const UInt uiAQPartWidth = pcAQLayer->getAQPartWidth();
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,4 +37,5 @@
 #include "TEncRateCtrl.h"
 #include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComChromaFormat.h"
 
 #include <cmath>
@@ -116,4 +117,5 @@
     m_betaUpdate  = 0.2;
   }
+
   m_averageBits     = (Int)(m_targetBits / totalFrames);
   Int picWidthInBU  = ( m_picWidth  % m_LCUWidth  ) == 0 ? m_picWidth  / m_LCUWidth  : m_picWidth  / m_LCUWidth  + 1;
@@ -222,5 +224,5 @@
       else
       {
-        m_picPara[i].m_alpha = ALPHA;   
+        m_picPara[i].m_alpha = ALPHA;
         m_picPara[i].m_beta  = BETA2;
       }
@@ -402,5 +404,5 @@
   Double maxNumber = 10000.0;
   for ( Int i=0; i<g_RCIterationNum; i++ )
-  { 
+  {
     Double fx = 0.0;
     for ( Int j=0; j<GOPSize; j++ )
@@ -698,5 +700,5 @@
   if (eSliceType == I_SLICE)
   {
-    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp); 
+    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp);
   }
   else
@@ -704,5 +706,5 @@
     estLambda = alpha * pow( bpp, beta );
   }
-  
+
   Double lastLevelLambda = -1.0;
   Double lastPicLambda   = -1.0;
@@ -786,5 +788,5 @@
 Int TEncRCPic::estimatePicQP( Double lambda, list<TEncRCPic*>& listPreviousPictures )
 {
-  Int QP = Int( 4.2005 * log( lambda ) + 13.7122 + 0.5 ); 
+  Int QP = Int( 4.2005 * log( lambda ) + 13.7122 + 0.5 );
 
   Int lastLevelQP = g_RCInvalidQPValue;
@@ -889,5 +891,5 @@
 
 
-Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)  
+Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)
 {
   Int   LCUIdx    = getLCUCoded();
@@ -914,11 +916,11 @@
   else
   {
-  Double totalWeight = 0;
-  for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
-  {
-    totalWeight += m_LCUs[i].m_bitWeight;
-  }
-  Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
-  avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
+    Double totalWeight = 0;
+    for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
+    {
+      totalWeight += m_LCUs[i].m_bitWeight;
+    }
+    Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
+    avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
   }
 
@@ -1073,5 +1075,5 @@
   //for Lambda clip, LCU level clip
   Double clipNeighbourLambda = -1.0;
-  for ( int i=LCUIdx - 1; i>=0; i-- )
+  for ( Int i=LCUIdx - 1; i>=0; i-- )
   {
     if ( m_LCUs[i].m_lambda > 0 )
@@ -1085,5 +1087,5 @@
   {
     estLambda = Clip3( clipNeighbourLambda * pow( 2.0, -1.0/3.0 ), clipNeighbourLambda * pow( 2.0, 1.0/3.0 ), estLambda );
-  }  
+  }
 
   if ( clipPicLambda > 0.0 )
@@ -1111,5 +1113,5 @@
   //for Lambda clip, LCU level clip
   Int clipNeighbourQP = g_RCInvalidQPValue;
-  for ( int i=LCUIdx - 1; i>=0; i-- )
+  for ( Int i=LCUIdx - 1; i>=0; i-- )
   {
     if ( (getLCU(i)).m_QP > g_RCInvalidQPValue )
@@ -1130,5 +1132,5 @@
 }
 
-Void TEncRCPic::updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter )
+Void TEncRCPic::updateAfterCTU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter )
 {
   m_LCUs[LCUIdx].m_actualBits = bits;
@@ -1177,5 +1179,5 @@
   calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
   alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
-  double lnbpp = log( bpp );
+  Double lnbpp = log( bpp );
   lnbpp = Clip3( -5.0, -0.1, lnbpp );
   beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
@@ -1183,4 +1185,5 @@
   alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
   beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+
   TRCParameter rcPara;
   rcPara.m_alpha = alpha;
@@ -1232,5 +1235,5 @@
   }
 
-  Double avgLambda; 
+  Double avgLambda;
   if( numTotalLCUs == 0 )
   {
@@ -1243,4 +1246,5 @@
   return avgLambda;
 }
+
 
 Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
@@ -1267,4 +1271,5 @@
   Double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
   Double beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+
   if (eSliceType == I_SLICE)
   {
@@ -1273,33 +1278,35 @@
   else
   {
-  // update parameters
-  Double picActualBits = ( Double )m_picActualBits;
-  Double picActualBpp  = picActualBits/(Double)m_numberOfPixel;
-  Double calLambda     = alpha * pow( picActualBpp, beta );
-  Double inputLambda   = m_picLambda;
-
-  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
-  {
-    alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
-    beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
+    // update parameters
+    Double picActualBits = ( Double )m_picActualBits;
+    Double picActualBpp  = picActualBits/(Double)m_numberOfPixel;
+    Double calLambda     = alpha * pow( picActualBpp, beta );
+    Double inputLambda   = m_picLambda;
+
+    if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
+    {
+      alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
+      beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
+
+      alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+      beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+
+      TRCParameter rcPara;
+      rcPara.m_alpha = alpha;
+      rcPara.m_beta  = beta;
+      m_encRCSeq->setPicPara( m_frameLevel, rcPara );
+
+      return;
+    }
+
+    calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
+    alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
+    Double lnbpp = log( picActualBpp );
+    lnbpp = Clip3( -5.0, -0.1, lnbpp );
+
+    beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
 
     alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
     beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
-    TRCParameter rcPara;
-    rcPara.m_alpha = alpha;
-    rcPara.m_beta  = beta;
-    m_encRCSeq->setPicPara( m_frameLevel, rcPara );
-
-    return;
-  }
-
-  calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
-  alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
-  double lnbpp = log( picActualBpp );
-  lnbpp = Clip3( -5.0, -0.1, lnbpp );
-  beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
-
-  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
-  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
   }
 
@@ -1333,14 +1340,14 @@
 
   iIntraBits = (Int)(alpha* pow(m_totalCostIntra*4.0/(Double)orgBits, beta)*(Double)orgBits+0.5);
-  
+
   return iIntraBits;
 }
 
-Double TEncRCPic::calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel)
+Double TEncRCPic::calculateLambdaIntra(Double alpha, Double beta, Double MADPerPixel, Double bitsPerPixel)
 {
   return ( (alpha/256.0) * pow( MADPerPixel/bitsPerPixel, beta ) );
 }
 
-Void TEncRCPic::updateAlphaBetaIntra(double *alpha, double *beta)
+Void TEncRCPic::updateAlphaBetaIntra(Double *alpha, Double *beta)
 {
   Double lnbpp = log(pow(m_totalCostIntra / (Double)m_numberOfPixel, BETA1));
@@ -1353,5 +1360,5 @@
 
 
-Void TEncRCPic::getLCUInitTargetBits()  
+Void TEncRCPic::getLCUInitTargetBits()
 {
   Int iAvgBits     = 0;
@@ -1366,5 +1373,5 @@
 
 
-Double TEncRCPic::getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP) 
+Double TEncRCPic::getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP)
 {
   Int   LCUIdx = getLCUCoded();
@@ -1378,5 +1385,5 @@
 
   Int clipNeighbourQP = g_RCInvalidQPValue;
-  for (int i=LCUIdx-1; i>=0; i--)
+  for (Int i=LCUIdx-1; i>=0; i--)
   {
     if ((getLCU(i)).m_QP > g_RCInvalidQPValue)
@@ -1392,6 +1399,6 @@
   if ( clipNeighbourQP > g_RCInvalidQPValue )
   {
-    maxQP = min(clipNeighbourQP + 1, maxQP); 
-    minQP = max(clipNeighbourQP - 1, minQP); 
+    maxQP = min(clipNeighbourQP + 1, maxQP);
+    minQP = max(clipNeighbourQP - 1, minQP);
   }
 
@@ -1515,4 +1522,5 @@
         bitsRatio[3] = 14;
       }
+
       if ( keepHierBits == 2 )
       {
@@ -1566,4 +1574,5 @@
         bitsRatio[7] = 1;
       }
+
       if ( keepHierBits == 2 )
       {
@@ -1577,6 +1586,6 @@
   }
 
-  Int* GOPID2Level = new int[ GOPSize ];
-  for ( int i=0; i<GOPSize; i++ )
+  Int* GOPID2Level = new Int[ GOPSize ];
+  for ( Int i=0; i<GOPSize; i++ )
   {
     GOPID2Level[i] = 1;
@@ -1586,4 +1595,5 @@
     }
   }
+
   if ( keepHierBits > 0 )
   {
@@ -1659,3 +1669,2 @@
   m_encRCGOP = NULL;
 }
-
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,6 +36,6 @@
 */
 
-#ifndef _HM_TENCRATECTRL_H_
-#define _HM_TENCRATECTRL_H_
+#ifndef __TENCRATECTRL__
+#define __TENCRATECTRL__
 
 #if _MSC_VER > 1000
@@ -123,5 +123,5 @@
   Int  getGOPSize()                     { return m_GOPSize; }
   Int  getPicWidth()                    { return m_picWidth; }
-  Int  getPicHeight()                   { return m_picHeight; } 
+  Int  getPicHeight()                   { return m_picHeight; }
   Int  getLCUWidth()                    { return m_LCUWidth; }
   Int  getLCUHeight()                   { return m_LCUHeight; }
@@ -160,5 +160,5 @@
   Int m_totalFrames;
   Int m_targetRate;
-  Int m_frameRate; 
+  Int m_frameRate;
   Int m_GOPSize;
   Int m_picWidth;
@@ -240,8 +240,8 @@
   Int    estimatePicQP    ( Double lambda, list<TEncRCPic*>& listPreviousPictures );
   Int    getRefineBitsForIntra(Int orgBits);
-  Double calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel);
+  Double calculateLambdaIntra(Double alpha, Double beta, Double MADPerPixel, Double bitsPerPixel);
   Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType);
 
-  Void   updateAlphaBetaIntra(double *alpha, double *beta);
+  Void   updateAlphaBetaIntra(Double *alpha, Double *beta);
 
   Double getLCUTargetBpp(SliceType eSliceType);
@@ -253,5 +253,5 @@
   Int    getLCUEstQP( Double lambda, Int clipPicQP );
 
-  Void updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
+  Void updateAfterCTU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
   Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType);
 
@@ -326,5 +326,5 @@
   TRCLCU* m_LCUs;
   Int m_picActualHeaderBits;    // only SH and potential APS
-  Double m_totalCostIntra; 
+  Double m_totalCostIntra;
   Double m_remainingCostIntra;
   Int m_picActualBits;          // the whole picture, including header
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1200)
@@ -2,5 +2,5 @@
  * 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.  
+ * granted under this license.
  *
  * Copyright (c) 2010-2015, ITU/ISO/IEC
@@ -32,5 +32,5 @@
  */
 
-/** 
+/**
  \file     TEncSampleAdaptiveOffset.cpp
  \brief       estimation part of sample adaptive offset class
@@ -46,7 +46,5 @@
 
 
-/** rounding with IBDI
- * \param  x
- */
+//! rounding with IBDI
 inline Double xRoundIbdi2(Int bitDepth, Double x)
 {
@@ -62,11 +60,9 @@
 TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
 {
-  m_pppcRDSbacCoder = NULL;           
+  m_pppcRDSbacCoder = NULL;
   m_pcRDGoOnSbacCoder = NULL;
-  m_pppcBinCoderCABAC = NULL;    
+  m_pppcBinCoderCABAC = NULL;
   m_statData = NULL;
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
   m_preDBFstatData = NULL;
-#endif
 }
 
@@ -76,19 +72,23 @@
 }
 
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
 Void TEncSampleAdaptiveOffset::createEncData(Bool isPreDBFSamplesUsed)
-#else
-Void TEncSampleAdaptiveOffset::createEncData()
-#endif
 {
 
   //cabac coder for RDO
   m_pppcRDSbacCoder = new TEncSbac* [NUM_SAO_CABACSTATE_LABELS];
+#if FAST_BIT_EST
   m_pppcBinCoderCABAC = new TEncBinCABACCounter* [NUM_SAO_CABACSTATE_LABELS];
+#else
+  m_pppcBinCoderCABAC = new TEncBinCABAC* [NUM_SAO_CABACSTATE_LABELS];
+#endif
 
   for(Int cs=0; cs < NUM_SAO_CABACSTATE_LABELS; cs++)
   {
     m_pppcRDSbacCoder[cs] = new TEncSbac;
+#if FAST_BIT_EST
     m_pppcBinCoderCABAC[cs] = new TEncBinCABACCounter;
+#else
+    m_pppcBinCoderCABAC[cs] = new TEncBinCABAC;
+#endif
     m_pppcRDSbacCoder   [cs]->init( m_pppcBinCoderCABAC [cs] );
   }
@@ -99,11 +99,10 @@
   for(Int i=0; i< m_numCTUsPic; i++)
   {
-    m_statData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
-    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    m_statData[i] = new SAOStatData*[MAX_NUM_COMPONENT];
+    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
     {
       m_statData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
     }
   }
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
   if(isPreDBFSamplesUsed)
   {
@@ -111,6 +110,6 @@
     for(Int i=0; i< m_numCTUsPic; i++)
     {
-      m_preDBFstatData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
-      for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+      m_preDBFstatData[i] = new SAOStatData*[MAX_NUM_COMPONENT];
+      for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
       {
         m_preDBFstatData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
@@ -119,19 +118,15 @@
 
   }
-#endif
-
-#if SAO_ENCODING_CHOICE
+
   ::memset(m_saoDisabledRate, 0, sizeof(m_saoDisabledRate));
-#endif
 
   for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
   {
-    m_skipLinesR[SAO_Y ][typeIdc]= 5;
-    m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
-
-    m_skipLinesB[SAO_Y ][typeIdc]= 4;
-    m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
-
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
+    m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
+
+    m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
+    m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
+
     if(isPreDBFSamplesUsed)
     {
@@ -140,18 +135,18 @@
       case SAO_TYPE_EO_0:
         {
-          m_skipLinesR[SAO_Y ][typeIdc]= 5;
-          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
-
-          m_skipLinesB[SAO_Y ][typeIdc]= 3;
-          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+          m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
+          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
+
+          m_skipLinesB[COMPONENT_Y ][typeIdc]= 3;
+          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 1;
         }
         break;
       case SAO_TYPE_EO_90:
         {
-          m_skipLinesR[SAO_Y ][typeIdc]= 4;
-          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
-
-          m_skipLinesB[SAO_Y ][typeIdc]= 4;
-          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+          m_skipLinesR[COMPONENT_Y ][typeIdc]= 4;
+          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 2;
+
+          m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
+          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
         }
         break;
@@ -159,18 +154,18 @@
       case SAO_TYPE_EO_45:
         {
-          m_skipLinesR[SAO_Y ][typeIdc]= 5;
-          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
-
-          m_skipLinesB[SAO_Y ][typeIdc]= 4;
-          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+          m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
+          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
+
+          m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
+          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
         }
         break;
       case SAO_TYPE_BO:
         {
-          m_skipLinesR[SAO_Y ][typeIdc]= 4;
-          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
-
-          m_skipLinesB[SAO_Y ][typeIdc]= 3;
-          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+          m_skipLinesR[COMPONENT_Y ][typeIdc]= 4;
+          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 2;
+
+          m_skipLinesB[COMPONENT_Y ][typeIdc]= 3;
+          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 1;
         }
         break;
@@ -183,5 +178,4 @@
       }
     }
-#endif    
   }
 
@@ -212,5 +206,5 @@
     for(Int i=0; i< m_numCTUsPic; i++)
     {
-      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      for(Int compIdx=0; compIdx< MAX_NUM_COMPONENT; compIdx++)
       {
         delete[] m_statData[i][compIdx];
@@ -220,10 +214,9 @@
     delete[] m_statData; m_statData = NULL;
   }
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
   if(m_preDBFstatData != NULL)
   {
     for(Int i=0; i< m_numCTUsPic; i++)
     {
-      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      for(Int compIdx=0; compIdx< MAX_NUM_COMPONENT; compIdx++)
       {
         delete[] m_preDBFstatData[i][compIdx];
@@ -233,13 +226,10 @@
     delete[] m_preDBFstatData; m_preDBFstatData = NULL;
   }
-
-#endif
-}
-
-Void TEncSampleAdaptiveOffset::initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) 
+}
+
+Void TEncSampleAdaptiveOffset::initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice)
 {
   m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
-  m_pcRDGoOnSbacCoder->setSlice(pcSlice);
-  m_pcRDGoOnSbacCoder->resetEntropy();
+  m_pcRDGoOnSbacCoder->resetEntropy(pcSlice);
   m_pcRDGoOnSbacCoder->resetBits();
 
@@ -249,13 +239,9 @@
 
 
-Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-                                         , Bool isPreDBFSamplesUsed
-#endif
-                                          )
+Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma, Bool isPreDBFSamplesUsed )
 {
   TComPicYuv* orgYuv= pPic->getPicYuvOrg();
   TComPicYuv* resYuv= pPic->getPicYuvRec();
-  m_lambda[SAO_Y]= lambdas[0]; m_lambda[SAO_Cb]= lambdas[1]; m_lambda[SAO_Cr]= lambdas[2];
+  memcpy(m_lambda, lambdas, sizeof(m_lambda));
   TComPicYuv* srcYuv = m_tempPicYuv;
   resYuv->copyToPic(srcYuv);
@@ -265,21 +251,17 @@
   //collect statistics
   getStatistics(m_statData, orgYuv, srcYuv, pPic);
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
   if(isPreDBFSamplesUsed)
   {
     addPreDBFStatistics(m_statData);
   }
-#endif
-  //slice on/off 
-  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth()); 
-
-  //block on/off 
+  //slice on/off
+  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth(), saoEncodingRate, saoEncodingRateChroma);
+
+  //block on/off
   SAOBlkParam* reconParams = new SAOBlkParam[m_numCTUsPic]; //temporary parameter buffer for storing reconstructed SAO parameters
-  decideBlkParams(pPic, sliceEnabled, m_statData, srcYuv, resYuv, reconParams, pPic->getPicSym()->getSAOBlkParam());
+  decideBlkParams(pPic, sliceEnabled, m_statData, srcYuv, resYuv, reconParams, pPic->getPicSym()->getSAOBlkParam(), bTestSAODisableAtPictureLevel, saoEncodingRate, saoEncodingRateChroma);
   delete[] reconParams;
-
-}
-
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+}
+
 Void TEncSampleAdaptiveOffset::getPreDBFStatistics(TComPic* pPic)
 {
@@ -291,5 +273,5 @@
   for(Int n=0; n< m_numCTUsPic; n++)
   {
-    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
     {
       for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
@@ -301,22 +283,18 @@
 }
 
-#endif
-
-Void TEncSampleAdaptiveOffset::getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv, TComPic* pPic
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-                          , Bool isCalculatePreDeblockSamples
-#endif
-                          )
+Void TEncSampleAdaptiveOffset::getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv, TComPic* pPic, Bool isCalculatePreDeblockSamples)
 {
   Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
 
-  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
-  {
-    Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
-    Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+
+  for(Int ctuRsAddr= 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
+  {
+    Int yPos   = (ctuRsAddr / m_numCTUInWidth)*m_maxCUHeight;
+    Int xPos   = (ctuRsAddr % m_numCTUInWidth)*m_maxCUWidth;
     Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
     Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
 
-    pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+    pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctuRsAddr, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
 
     //NOTE: The number of skipped lines during gathering CTU statistics depends on the slice boundary availabilities.
@@ -329,21 +307,21 @@
     isAboveRightAvail = ((yPos > 0) && (isRightAvail));
 
-    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
-    {
-      Bool isLuma     = (compIdx == SAO_Y);
-      Int  formatShift= isLuma?0:1;
-
-      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
-      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
-
-      Int  orgStride  = isLuma?orgYuv->getStride():orgYuv->getCStride();
-      Pel* orgBlk     = getPicBuf(orgYuv, compIdx)+ (yPos >> formatShift)*orgStride+ (xPos >> formatShift);
-
-      getBlkStats(compIdx, blkStats[ctu][compIdx]  
-                , srcBlk, orgBlk, srcStride, orgStride, (width  >> formatShift), (height >> formatShift)
-                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail, isBelowLeftAvail, isBelowRightAvail
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+    {
+      const ComponentID component = ComponentID(compIdx);
+
+      const UInt componentScaleX = getComponentScaleX(component, pPic->getChromaFormat());
+      const UInt componentScaleY = getComponentScaleY(component, pPic->getChromaFormat());
+
+      Int  srcStride  = srcYuv->getStride(component);
+      Pel* srcBlk     = srcYuv->getAddr(component) + ((yPos >> componentScaleY) * srcStride) + (xPos >> componentScaleX);
+
+      Int  orgStride  = orgYuv->getStride(component);
+      Pel* orgBlk     = orgYuv->getAddr(component) + ((yPos >> componentScaleY) * orgStride) + (xPos >> componentScaleX);
+
+      getBlkStats(component, pPic->getPicSym()->getSPS().getBitDepth(toChannelType(component)), blkStats[ctuRsAddr][component]
+                , srcBlk, orgBlk, srcStride, orgStride, (width  >> componentScaleX), (height >> componentScaleY)
+                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail
                 , isCalculatePreDeblockSamples
-#endif
                 );
 
@@ -352,37 +330,46 @@
 }
 
-Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer)
+Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer, const Double saoEncodingRate, const Double saoEncodingRateChroma)
 {
   //decide sliceEnabled[compIdx]
-  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  for (Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+  {
+    sliceEnabled[compIdx] = false;
+  }
+
+  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
   {
     // reset flags & counters
     sliceEnabled[compIdx] = true;
 
-#if SAO_ENCODING_CHOICE
-#if SAO_ENCODING_CHOICE_CHROMA
+    if (saoEncodingRate>0.0)
+    {
+      if (saoEncodingRateChroma>0.0)
+      {
     // decide slice-level on/off based on previous results
-    if( (picTempLayer > 0) 
-      && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==SAO_Y) ? SAO_ENCODING_RATE : SAO_ENCODING_RATE_CHROMA)) )
+    if( (picTempLayer > 0)
+          && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==COMPONENT_Y) ? saoEncodingRate : saoEncodingRateChroma)) )
     {
       sliceEnabled[compIdx] = false;
     }
-#else
+      }
+      else
+      {
     // decide slice-level on/off based on previous results
-    if( (picTempLayer > 0) 
-      && (m_saoDisabledRate[SAO_Y][0] > SAO_ENCODING_RATE) )
+    if( (picTempLayer > 0)
+          && (m_saoDisabledRate[COMPONENT_Y][0] > saoEncodingRate) )
     {
       sliceEnabled[compIdx] = false;
     }
-#endif
-#endif
-  }
-}
-
-Int64 TEncSampleAdaptiveOffset::getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
-{
-  Int64 dist=0;
-  Int inputBitDepth    = (compIdx == SAO_Y) ? g_bitDepthY : g_bitDepthC ;
-  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(inputBitDepth-8);
+      }
+    }
+  }
+}
+
+Int64 TEncSampleAdaptiveOffset::getDistortion(const Int channelBitDepth, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
+{
+  Int64 dist        = 0;
+  Int shift         = 2 * DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth - 8);
 
   switch(typeIdc)
@@ -396,5 +383,5 @@
         {
           dist += estSaoDist( statData.count[offsetIdx], invQuantOffset[offsetIdx], statData.diff[offsetIdx], shift);
-        }        
+        }
       }
       break;
@@ -403,5 +390,5 @@
         for (Int offsetIdx=typeAuxInfo; offsetIdx<typeAuxInfo+4; offsetIdx++)
         {
-          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ; 
+          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ;
           dist += estSaoDist( statData.count[bandIdx], invQuantOffset[bandIdx], statData.diff[bandIdx], shift);
         }
@@ -425,5 +412,5 @@
 
 
-inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
+inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
 {
   Int iterOffset, tempOffset;
@@ -432,12 +419,12 @@
   Int offsetOutput = 0;
   iterOffset = offsetInput;
-  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here. 
-  tempMinCost = lambda; 
+  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here.
+  tempMinCost = lambda;
   while (iterOffset != 0)
   {
     // Calculate the bits required for signaling the offset
-    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1); 
-    if (abs((Int)iterOffset)==offsetTh) //inclusive 
-    {  
+    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1);
+    if (abs((Int)iterOffset)==offsetTh) //inclusive
+    {
       tempRate --;
     }
@@ -458,18 +445,17 @@
 }
 
-
-Void TEncSampleAdaptiveOffset::deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
-{
-  Int bitDepth = (compIdx== SAO_Y) ? g_bitDepthY : g_bitDepthC;
-  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
-  Int offsetTh = g_saoMaxOffsetQVal[compIdx];  //inclusive
+Void TEncSampleAdaptiveOffset::deriveOffsets(ComponentID compIdx, const Int channelBitDepth, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
+{
+  Int bitDepth = channelBitDepth;
+  Int shift    = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+  Int offsetTh = TComSampleAdaptiveOffset::getMaxOffsetQVal(channelBitDepth);  //inclusive
 
   ::memset(quantOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
 
-  //derive initial offsets 
+  //derive initial offsets
   Int numClasses = (typeIdc == SAO_TYPE_BO)?((Int)NUM_SAO_BO_CLASSES):((Int)NUM_SAO_EO_CLASSES);
   for(Int classIdx=0; classIdx< numClasses; classIdx++)
   {
-    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  ) 
+    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  )
     {
       continue; //offset will be zero
@@ -481,6 +467,6 @@
     }
 
-    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8)) 
-                                                                  / 
+    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8))
+                                                                  /
                                                           (Double)( statData.count[classIdx]<< m_offsetStepLog2[compIdx])
                                                );
@@ -498,17 +484,29 @@
         Int64 classDist;
         Double classCost;
-        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)  
-        {         
-          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
-          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
-          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
-          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)
+        {
+          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0)
+          {
+            quantOffsets[classIdx] =0;
+          }
+          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0)
+          {
+            quantOffsets[classIdx] =0;
+          }
+          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0)
+          {
+            quantOffsets[classIdx] =0;
+          }
+          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0)
+          {
+            quantOffsets[classIdx] =0;
+          }
 
           if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
           {
-            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
-          }
-        }
-      
+            quantOffsets[classIdx] = estIterOffset( typeIdc, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
+          }
+        }
+
         typeAuxInfo =0;
       }
@@ -520,9 +518,9 @@
         ::memset(distBOClasses, 0, sizeof(Int64)*NUM_SAO_BO_CLASSES);
         for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
-        {         
+        {
           costBOClasses[classIdx]= m_lambda[compIdx];
           if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
           {
-            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
+            quantOffsets[classIdx] = estIterOffset( typeIdc, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
           }
         }
@@ -530,5 +528,5 @@
         //decide the starting band index
         Double minCost = MAX_DOUBLE, cost;
-        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++) 
+        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++)
         {
           cost  = costBOClasses[band  ];
@@ -546,10 +544,10 @@
         Int clearQuantOffset[NUM_SAO_BO_CLASSES];
         ::memset(clearQuantOffset, 0, sizeof(Int)*NUM_SAO_BO_CLASSES);
-        for(Int i=0; i< 4; i++) 
+        for(Int i=0; i< 4; i++)
         {
           Int band = (typeAuxInfo+i)%NUM_SAO_BO_CLASSES;
           clearQuantOffset[band] = quantOffsets[band];
         }
-        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);        
+        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);
       }
       break;
@@ -566,78 +564,82 @@
 }
 
-
-Void TEncSampleAdaptiveOffset::deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+Void TEncSampleAdaptiveOffset::deriveModeNewRDO(const BitDepths &bitDepths, Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
 {
   Double minCost, cost;
-  Int rate;
   UInt previousWrittenBits;
-  Int64 dist[NUM_SAO_COMPONENTS], modeDist[NUM_SAO_COMPONENTS];
-  SAOOffset testOffset[NUM_SAO_COMPONENTS];
-  Int compIdx;
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+
+  Int64 dist[MAX_NUM_COMPONENT], modeDist[MAX_NUM_COMPONENT];
+  SAOOffset testOffset[MAX_NUM_COMPONENT];
   Int invQuantOffset[MAX_NUM_SAO_CLASSES];
-
-  modeDist[SAO_Y]= modeDist[SAO_Cb] = modeDist[SAO_Cr] = 0;
+  for(Int comp=0; comp < MAX_NUM_COMPONENT; comp++)
+  {
+    modeDist[comp] = 0;
+  }
 
   //pre-encode merge flags
-  modeParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
+  modeParam[COMPONENT_Y].modeIdc = SAO_MODE_OFF;
   m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
-  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
   m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
 
-  //------ luma --------//
-  compIdx = SAO_Y;
-  //"off" case as initial cost
-  modeParam[compIdx].modeIdc = SAO_MODE_OFF;
-  m_pcRDGoOnSbacCoder->resetBits();
-  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx]);
-  modeDist[compIdx] = 0;
-  minCost= m_lambda[compIdx]*((Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits());
-  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
-  if(sliceEnabled[compIdx])
-  {
-    for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
-    {
-      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
-      testOffset[compIdx].typeIdc = typeIdc;
-
-      //derive coded offset
-      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
-
-      //inversed quantized offsets
-      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
-
-      //get distortion
-      dist[compIdx] = getDistortion(ctu, compIdx, testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
-
-      //get rate
-      m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
-      m_pcRDGoOnSbacCoder->resetBits();
-      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
-      rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
-      cost = (Double)dist[compIdx] + m_lambda[compIdx]*((Double)rate);
-      if(cost < minCost)
-      {
-        minCost = cost;
-        modeDist[compIdx] = dist[compIdx];
-        modeParam[compIdx]= testOffset[compIdx];
-        m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
-      }
-    }
-  }
-  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
-  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+    //------ luma --------//
+  {
+    const ComponentID compIdx = COMPONENT_Y;
+    //"off" case as initial cost
+    modeParam[compIdx].modeIdc = SAO_MODE_OFF;
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx], bitDepths.recon[CHANNEL_TYPE_LUMA]);
+    modeDist[compIdx] = 0;
+    minCost= m_lambda[compIdx]*((Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits());
+    m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    if(sliceEnabled[compIdx])
+    {
+      for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+      {
+        testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+        testOffset[compIdx].typeIdc = typeIdc;
+
+        //derive coded offset
+        deriveOffsets(compIdx, bitDepths.recon[CHANNEL_TYPE_LUMA], typeIdc, blkStats[ctuRsAddr][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+
+        //inversed quantized offsets
+        invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+
+        //get distortion
+        dist[compIdx] = getDistortion(bitDepths.recon[CHANNEL_TYPE_LUMA], testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctuRsAddr][compIdx][typeIdc]);
+
+        //get rate
+        m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+        m_pcRDGoOnSbacCoder->resetBits();
+        m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx], bitDepths.recon[CHANNEL_TYPE_LUMA]);
+        Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+        cost = (Double)dist[compIdx] + m_lambda[compIdx]*((Double)rate);
+        if(cost < minCost)
+        {
+          minCost = cost;
+          modeDist[compIdx] = dist[compIdx];
+          modeParam[compIdx]= testOffset[compIdx];
+          m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+        }
+      }
+    }
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+  }
 
   //------ chroma --------//
-  //"off" case as initial cost
+//"off" case as initial cost
   cost = 0;
   previousWrittenBits = 0;
   m_pcRDGoOnSbacCoder->resetBits();
-  for (Int component = SAO_Cb; component < NUM_SAO_COMPONENTS; component++)
-  {
-    modeParam[component].modeIdc = SAO_MODE_OFF; 
-    modeDist [component] = 0;
-
-    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component]);
-
+  for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
+  {
+    const ComponentID component = ComponentID(componentIndex);
+
+    modeParam[component].modeIdc = SAO_MODE_OFF;
+    modeDist [component]         = 0;
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component], bitDepths.recon[CHANNEL_TYPE_CHROMA]);
+    
     const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
     cost += m_lambda[component] * (currentWrittenBits - previousWrittenBits);
@@ -656,24 +658,25 @@
     cost = 0;
 
-    for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
-    {
-      if(!sliceEnabled[compIdx])
-      {
-        testOffset[compIdx].modeIdc = SAO_MODE_OFF;
-        dist[compIdx]= 0;
+    for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
+    {
+      const ComponentID component = ComponentID(componentIndex);
+      if(!sliceEnabled[component])
+      {
+        testOffset[component].modeIdc = SAO_MODE_OFF;
+        dist[component]= 0;
         continue;
       }
-      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
-      testOffset[compIdx].typeIdc = typeIdc;
+      testOffset[component].modeIdc = SAO_MODE_NEW;
+      testOffset[component].typeIdc = typeIdc;
 
       //derive offset & get distortion
-      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
-      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
-      dist[compIdx]= getDistortion(ctu, compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
-      
-      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+      deriveOffsets(component, bitDepths.recon[CHANNEL_TYPE_CHROMA], typeIdc, blkStats[ctuRsAddr][component][typeIdc], testOffset[component].offset, testOffset[component].typeAuxInfo);
+      invertQuantOffsets(component, typeIdc, testOffset[component].typeAuxInfo, invQuantOffset, testOffset[component].offset);
+      dist[component] = getDistortion(bitDepths.recon[CHANNEL_TYPE_CHROMA], typeIdc, testOffset[component].typeAuxInfo, invQuantOffset, blkStats[ctuRsAddr][component][typeIdc]);
+
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, testOffset[component], sliceEnabled[component], bitDepths.recon[CHANNEL_TYPE_CHROMA]);
 
       const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
-      cost += dist[compIdx] + (m_lambda[compIdx] * (currentWrittenBits - previousWrittenBits));
+      cost += dist[component] + (m_lambda[component] * (currentWrittenBits - previousWrittenBits));
       previousWrittenBits = currentWrittenBits;
     }
@@ -682,35 +685,35 @@
     {
       minCost = cost;
-      for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
-      {
-        modeDist [compIdx] = dist      [compIdx];
-        modeParam[compIdx] = testOffset[compIdx];
-      }
-    }
-  }
-
+      for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
+      {
+        modeDist[componentIndex]  = dist[componentIndex];
+        modeParam[componentIndex] = testOffset[componentIndex];
+      }
+    }
+
+  } // SAO_TYPE loop
 
   //----- re-gen rate & normalized cost----//
   modeNormCost = 0;
-  for(UInt component = SAO_Y; component < NUM_SAO_COMPONENTS; component++)
-  {
-    modeNormCost += (Double)modeDist[component] / m_lambda[component];
-  }
+  for(UInt componentIndex = COMPONENT_Y; componentIndex < numberOfComponents; componentIndex++)
+  {
+    modeNormCost += (Double)modeDist[componentIndex] / m_lambda[componentIndex];
+  }
+
   m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
   m_pcRDGoOnSbacCoder->resetBits();
-  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
   modeNormCost += (Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
-
-}
-
-Void TEncSampleAdaptiveOffset::deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
-{
-  Int mergeListSize = (Int)mergeList.size();
+}
+
+Void TEncSampleAdaptiveOffset::deriveModeMergeRDO(const BitDepths &bitDepths, Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
   modeNormCost = MAX_DOUBLE;
 
   Double cost;
   SAOBlkParam testBlkParam;
-
-  for(Int mergeType=0; mergeType< mergeListSize; mergeType++)
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+
+  for(Int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++)
   {
     if(mergeList[mergeType] == NULL)
@@ -722,5 +725,5 @@
     //normalized distortion
     Double normDist=0;
-    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
     {
       testBlkParam[compIdx].modeIdc = SAO_MODE_MERGE;
@@ -732,5 +735,5 @@
       {
         //offsets have been reconstructed. Don't call inversed quantization function.
-        normDist += (((Double)getDistortion(ctu, compIdx, mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctu][compIdx][mergedOffsetParam.typeIdc]))
+        normDist += (((Double)getDistortion(bitDepths.recon[toChannelType(ComponentID(compIdx))], mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctuRsAddr][compIdx][mergedOffsetParam.typeIdc]))
                        /m_lambda[compIdx]
                     );
@@ -742,5 +745,5 @@
     m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
     m_pcRDGoOnSbacCoder->resetBits();
-    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
     Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
 
@@ -756,14 +759,18 @@
 
   m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
-
-
-}
-
-Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams)
-{
-  Bool isAllBlksDisabled = false;
-  if(!sliceEnabled[SAO_Y] && !sliceEnabled[SAO_Cb] && !sliceEnabled[SAO_Cr])
-  {
-    isAllBlksDisabled = true;
+}
+
+Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv,
+                                               SAOBlkParam* reconParams, SAOBlkParam* codedParams, const Bool bTestSAODisableAtPictureLevel,
+                                               const Double saoEncodingRate, const Double saoEncodingRateChroma)
+{
+  Bool allBlksDisabled = true;
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  for(Int compId = COMPONENT_Y; compId < numberOfComponents; compId++)
+  {
+    if (sliceEnabled[compId])
+    {
+      allBlksDisabled = false;
+    }
   }
 
@@ -773,9 +780,12 @@
   Double minCost, modeCost;
 
-  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
-  {
-    if(isAllBlksDisabled)
-    {
-      codedParams[ctu].reset();
+
+  Double totalCost = 0; // Used if bTestSAODisableAtPictureLevel==true
+
+  for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
+  {
+    if(allBlksDisabled)
+    {
+      codedParams[ctuRsAddr].reset();
       continue;
     }
@@ -784,6 +794,6 @@
 
     //get merge list
-    std::vector<SAOBlkParam*> mergeList;
-    getMergeList(pic, ctu, reconParams, mergeList);
+    SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES] = { NULL };
+    getMergeList(pic, ctuRsAddr, reconParams, mergeList);
 
     minCost = MAX_DOUBLE;
@@ -799,5 +809,5 @@
       case SAO_MODE_NEW:
         {
-          deriveModeNewRDO(ctu, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+          deriveModeNewRDO(pic->getPicSym()->getSPS().getBitDepths(), ctuRsAddr, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
 
         }
@@ -805,5 +815,5 @@
       case SAO_MODE_MERGE:
         {
-          deriveModeMergeRDO(ctu, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+          deriveModeMergeRDO(pic->getPicSym()->getSPS().getBitDepths(), ctuRsAddr, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
         }
         break;
@@ -819,53 +829,69 @@
       {
         minCost = modeCost;
-        codedParams[ctu] = modeParam;
+        codedParams[ctuRsAddr] = modeParam;
         m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
-
       }
     } //mode
+
+    totalCost += minCost;
+
     m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
 
     //apply reconstructed offsets
-    reconParams[ctu] = codedParams[ctu];
-    reconstructBlkSAOParam(reconParams[ctu], mergeList);
-    offsetCTU(ctu, srcYuv, resYuv, reconParams[ctu], pic);
-  } //ctu
-
-#if SAO_ENCODING_CHOICE 
+    reconParams[ctuRsAddr] = codedParams[ctuRsAddr];
+    reconstructBlkSAOParam(reconParams[ctuRsAddr], mergeList);
+    offsetCTU(ctuRsAddr, srcYuv, resYuv, reconParams[ctuRsAddr], pic);
+  } //ctuRsAddr
+
+  if (!allBlksDisabled && (totalCost >= 0) && bTestSAODisableAtPictureLevel) //SAO has not beneficial in this case - disable it
+  {
+    for(Int ctuRsAddr = 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
+    {
+      codedParams[ctuRsAddr].reset();
+    }
+
+    for (UInt componentIndex = 0; componentIndex < MAX_NUM_COMPONENT; componentIndex++)
+    {
+      sliceEnabled[componentIndex] = false;
+    }
+
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
+  }
+
+  if (saoEncodingRate > 0.0)
+  {
   Int picTempLayer = pic->getSlice(0)->getDepth();
-  Int numLcusForSAOOff[NUM_SAO_COMPONENTS];
-  numLcusForSAOOff[SAO_Y ] = numLcusForSAOOff[SAO_Cb]= numLcusForSAOOff[SAO_Cr]= 0;
-
-  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
-  {
-    for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
-    {
-      if( reconParams[ctu][compIdx].modeIdc == SAO_MODE_OFF)
-      {
-        numLcusForSAOOff[compIdx]++;
-      }
-    }
-  }
-#if SAO_ENCODING_CHOICE_CHROMA
-  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
-  {
-    m_saoDisabledRate[compIdx][picTempLayer] = (Double)numLcusForSAOOff[compIdx]/(Double)m_numCTUsPic;
-  }
-#else
-  if (picTempLayer == 0)
-  {
-    m_saoDisabledRate[SAO_Y][0] = (Double)(numLcusForSAOOff[SAO_Y]+numLcusForSAOOff[SAO_Cb]+numLcusForSAOOff[SAO_Cr])/(Double)(m_numCTUsPic*3);
-  }
-#endif                                              
-#endif
-}
-
-
-Void TEncSampleAdaptiveOffset::getBlkStats(Int compIdx, SAOStatData* statsDataTypes  
+  Int numCtusForSAOOff[MAX_NUM_COMPONENT];
+
+  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    numCtusForSAOOff[compIdx] = 0;
+    for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
+    {
+      if( reconParams[ctuRsAddr][compIdx].modeIdc == SAO_MODE_OFF)
+      {
+        numCtusForSAOOff[compIdx]++;
+      }
+    }
+  }
+    if (saoEncodingRateChroma > 0.0)
+    {
+  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    m_saoDisabledRate[compIdx][picTempLayer] = (Double)numCtusForSAOOff[compIdx]/(Double)m_numCTUsPic;
+  }
+    }
+    else if (picTempLayer == 0)
+  {
+    m_saoDisabledRate[COMPONENT_Y][0] = (Double)(numCtusForSAOOff[COMPONENT_Y]+numCtusForSAOOff[COMPONENT_Cb]+numCtusForSAOOff[COMPONENT_Cr])/(Double)(m_numCTUsPic*3);
+  }
+  }
+}
+
+
+Void TEncSampleAdaptiveOffset::getBlkStats(const ComponentID compIdx, const Int channelBitDepth, SAOStatData* statsDataTypes
                         , Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height
-                        , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                        , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail
                         , Bool isCalculatePreDeblockSamples
-#endif
                         )
 {
@@ -874,8 +900,16 @@
     m_lineBufWidth = m_maxCUWidth;
 
-    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
-    m_signLineBuf1 = new Char[m_lineBufWidth+1]; 
-
-    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    if (m_signLineBuf1)
+    {
+      delete[] m_signLineBuf1;
+      m_signLineBuf1 = NULL;
+    }
+    m_signLineBuf1 = new Char[m_lineBufWidth+1];
+
+    if (m_signLineBuf2)
+    {
+      delete[] m_signLineBuf2;
+      m_signLineBuf2 = NULL;
+    }
     m_signLineBuf2 = new Char[m_lineBufWidth+1];
   }
@@ -904,32 +938,16 @@
         count+=2;
         endY   = (isBelowAvail) ? (height - skipLinesB[typeIdx]) : height;
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
                                                  : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
                                                  ;
-#else
-        startX = isLeftAvail ? 0 : 1;
-#endif
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
                                                  : (isRightAvail ? width : (width - 1))
                                                  ;
-#else
-        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
-#endif
         for (y=0; y<endY; y++)
         {
-#if SAO_SGN_FUNC
           signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
-#else
-          signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
-#endif
           for (x=startX; x<endX; x++)
           {
-#if SAO_SGN_FUNC
             signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
-#else
-            signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
-#endif
             edgeType  =  signRight + signLeft;
             signLeft  = -signRight;
@@ -941,5 +959,4 @@
           orgLine  += orgStride;
         }
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         if(isCalculatePreDeblockSamples)
         {
@@ -951,16 +968,8 @@
             for(y=0; y<skipLinesB[typeIdx]; y++)
             {
-#if SAO_SGN_FUNC
               signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
-#else
-              signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
-#endif
               for (x=startX; x<endX; x++)
               {
-#if SAO_SGN_FUNC
                 signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
-#else
-                signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
-#endif
                 edgeType  =  signRight + signLeft;
                 signLeft  = -signRight;
@@ -974,5 +983,4 @@
           }
         }
-#endif
       }
       break;
@@ -983,17 +991,11 @@
         Char *signUpLine = m_signLineBuf1;
 
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         startX = (!isCalculatePreDeblockSamples) ? 0
                                                  : (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
                                                  ;
-#endif
         startY = isAboveAvail ? 0 : 1;
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width) 
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
                                                  : width
                                                  ;
-#else
-        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : width ;
-#endif
         endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
         if (!isAboveAvail)
@@ -1004,15 +1006,7 @@
 
         Pel* srcLineAbove = srcLine - srcStride;
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-        for (x=startX; x<endX; x++) 
-#else
-        for (x=0; x< endX; x++) 
-#endif
-        {
-#if SAO_SGN_FUNC
+        for (x=startX; x<endX; x++)
+        {
           signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
-#else
-          signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
-#endif
         }
 
@@ -1022,15 +1016,7 @@
           srcLineBelow = srcLine + srcStride;
 
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
           for (x=startX; x<endX; x++)
-#else
-          for (x=0; x<endX; x++)
-#endif
-          {
-#if SAO_SGN_FUNC
+          {
             signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]); 
-#else
-            signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
-#endif
             edgeType  = signDown + signUpLine[x];
             signUpLine[x]= -signDown;
@@ -1042,5 +1028,4 @@
           orgLine += orgStride;
         }
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         if(isCalculatePreDeblockSamples)
         {
@@ -1057,9 +1042,5 @@
               for (x=startX; x<endX; x++)
               {
-#if SAO_SGN_FUNC
                 edgeType = sgn(srcLine[x] - srcLineBelow[x]) + sgn(srcLine[x] - srcLineAbove[x]);
-#else
-                edgeType = m_sign[srcLine[x] - srcLineBelow[x]] + m_sign[srcLine[x] - srcLineAbove[x]];
-#endif
                 diff [edgeType] += (orgLine[x] - srcLine[x]);
                 count[edgeType] ++;
@@ -1070,5 +1051,4 @@
           }
         }
-#endif
 
       }
@@ -1083,19 +1063,11 @@
         signDownLine= m_signLineBuf2;
 
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
                                                  : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
                                                  ;
-#else
-        startX = isLeftAvail ? 0 : 1 ;
-#endif
-
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+
         endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1))
                                                  : (isRightAvail ? width : (width - 1))
                                                  ;
-#else
-        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
-#endif
         endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
 
@@ -1104,27 +1076,14 @@
         for (x=startX; x<endX+1; x++)
         {
-#if SAO_SGN_FUNC
           signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x-1]);
-#else
-          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x-1]];
-#endif
         }
 
         //1st line
         Pel* srcLineAbove = srcLine - srcStride;
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveLeftAvail ? 0    : 1) : startX;
         firstLineEndX   = (!isCalculatePreDeblockSamples) ? (isAboveAvail     ? endX : 1) : endX;
-#else
-        firstLineStartX = isAboveLeftAvail ? 0    : 1;
-        firstLineEndX   = isAboveAvail     ? endX : 1;
-#endif
         for(x=firstLineStartX; x<firstLineEndX; x++)
         {
-#if SAO_SGN_FUNC
           edgeType = sgn(srcLine[x] - srcLineAbove[x-1]) - signUpLine[x+1];
-#else
-          edgeType = m_sign[srcLine[x] - srcLineAbove[x-1]] - signUpLine[x+1];
-#endif
           diff [edgeType] += (orgLine[x] - srcLine[x]);
           count[edgeType] ++;
@@ -1141,20 +1100,12 @@
           for (x=startX; x<endX; x++)
           {
-#if SAO_SGN_FUNC
             signDown = (Char)sgn(srcLine[x] - srcLineBelow[x+1]);
-#else
-            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x+1]] ;
-#endif
             edgeType = signDown + signUpLine[x];
             diff [edgeType] += (orgLine[x] - srcLine[x]);
             count[edgeType] ++;
 
-            signDownLine[x+1] = -signDown; 
-          }
-#if SAO_SGN_FUNC
+            signDownLine[x+1] = -signDown;
+          }
           signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
-#else
-          signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
-#endif
 
           signTmpLine  = signUpLine;
@@ -1165,5 +1116,4 @@
           orgLine += orgStride;
         }
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         if(isCalculatePreDeblockSamples)
         {
@@ -1180,9 +1130,5 @@
               for (x=startX; x< endX; x++)
               {
-#if SAO_SGN_FUNC
                 edgeType = sgn(srcLine[x] - srcLineBelow[x+1]) + sgn(srcLine[x] - srcLineAbove[x-1]);
-#else
-                edgeType = m_sign[srcLine[x] - srcLineBelow[x+1]] + m_sign[srcLine[x] - srcLineAbove[x-1]];
-#endif
                 diff [edgeType] += (orgLine[x] - srcLine[x]);
                 count[edgeType] ++;
@@ -1193,5 +1139,4 @@
           }
         }
-#endif
       }
       break;
@@ -1202,18 +1147,10 @@
         Char *signUpLine = m_signLineBuf1+1;
 
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
                                                  : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
                                                  ;
-#else
-        startX = isLeftAvail ? 0 : 1;
-#endif
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
                                                  : (isRightAvail ? width : (width - 1))
                                                  ;
-#else
-        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1);
-#endif
         endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
 
@@ -1222,9 +1159,5 @@
         for (x=startX-1; x<endX; x++)
         {
-#if SAO_SGN_FUNC
           signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
-#else
-          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
-#endif
         }
 
@@ -1232,5 +1165,4 @@
         //first line
         Pel* srcLineAbove = srcLine - srcStride;
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveAvail ? startX : endX)
                                                           : startX
@@ -1239,15 +1171,7 @@
                                                           : endX
                                                           ;
-#else
-        firstLineStartX = isAboveAvail ? startX : endX;
-        firstLineEndX   = (!isRightAvail && isAboveRightAvail) ? width : endX;
-#endif
         for(x=firstLineStartX; x<firstLineEndX; x++)
         {
-#if SAO_SGN_FUNC
           edgeType = sgn(srcLine[x] - srcLineAbove[x+1]) - signUpLine[x-1];
-#else
-          edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] - signUpLine[x-1];
-#endif
           diff [edgeType] += (orgLine[x] - srcLine[x]);
           count[edgeType] ++;
@@ -1264,9 +1188,5 @@
           for(x=startX; x<endX; x++)
           {
-#if SAO_SGN_FUNC
             signDown = (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
-#else
-            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
-#endif
             edgeType = signDown + signUpLine[x];
 
@@ -1274,15 +1194,10 @@
             count[edgeType] ++;
 
-            signUpLine[x-1] = -signDown; 
-          }
-#if SAO_SGN_FUNC
+            signUpLine[x-1] = -signDown;
+          }
           signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
-#else
-          signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
-#endif
           srcLine  += srcStride;
           orgLine  += orgStride;
         }
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         if(isCalculatePreDeblockSamples)
         {
@@ -1299,9 +1214,5 @@
               for (x=startX; x<endX; x++)
               {
-#if SAO_SGN_FUNC
                 edgeType = sgn(srcLine[x] - srcLineBelow[x-1]) + sgn(srcLine[x] - srcLineAbove[x+1]);
-#else
-                edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + m_sign[srcLine[x] - srcLineAbove[x+1]];
-#endif
                 diff [edgeType] += (orgLine[x] - srcLine[x]);
                 count[edgeType] ++;
@@ -1312,10 +1223,8 @@
           }
         }
-#endif
       }
       break;
     case SAO_TYPE_BO:
       {
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         startX = (!isCalculatePreDeblockSamples)?0
                                                 :( isRightAvail?(width- skipLinesR[typeIdx]):width)
@@ -1324,19 +1233,12 @@
                                                 :width
                                                 ;
-#else
-        endX = isRightAvail ? (width- skipLinesR[typeIdx]) : width;
-#endif
         endY = isBelowAvail ? (height- skipLinesB[typeIdx]) : height;
-        Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+        Int shiftBits = channelBitDepth - NUM_SAO_BO_CLASSES_LOG2;
         for (y=0; y< endY; y++)
         {
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
           for (x=startX; x< endX; x++)
-#else
-          for (x=0; x< endX; x++)
-#endif
-          {
-
-            Int bandIdx= srcLine[x] >> shiftBits; 
+          {
+
+            Int bandIdx= srcLine[x] >> shiftBits;
             diff [bandIdx] += (orgLine[x] - srcLine[x]);
             count[bandIdx] ++;
@@ -1345,5 +1247,4 @@
           orgLine += orgStride;
         }
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
         if(isCalculatePreDeblockSamples)
         {
@@ -1357,5 +1258,5 @@
               for (x=startX; x< endX; x++)
               {
-                Int bandIdx= srcLine[x] >> shiftBits; 
+                Int bandIdx= srcLine[x] >> shiftBits;
                 diff [bandIdx] += (orgLine[x] - srcLine[x]);
                 count[bandIdx] ++;
@@ -1368,5 +1269,4 @@
           }
         }
-#endif
       }
       break;
@@ -1381,3 +1281,4 @@
 }
 
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 1200)
@@ -2,5 +2,5 @@
  * 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.  
+ * granted under this license.
  *
  * Copyright (c) 2010-2015, ITU/ISO/IEC
@@ -32,5 +32,5 @@
  */
 
-/** 
+/**
  \file     TEncSampleAdaptiveOffset.h
  \brief    estimation part of sample adaptive offset class (header)
@@ -82,5 +82,4 @@
     return *this;
   }
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
   const SAOStatData& operator+= (const SAOStatData& src)
   {
@@ -92,5 +91,4 @@
     return *this;
   }
-#endif
 };
 
@@ -102,60 +100,42 @@
 
   //interface
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
   Void createEncData(Bool isPreDBFSamplesUsed);
-#else
-  Void createEncData();
-#endif
   Void destroyEncData();
   Void initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) ;
-  Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-                , Bool isPreDBFSamplesUsed
-#endif
-                ); 
+  Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma, Bool isPreDBFSamplesUsed);
 public: //methods
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-  Void getPreDBFStatistics(TComPic* pPic); 
-#endif
+  Void getPreDBFStatistics(TComPic* pPic);
 private: //methods
-  Void getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv,TComPic* pPic
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-                   , Bool isCalculatePreDeblockSamples = false
-#endif
-                   );
-  Void decidePicParams(Bool* sliceEnabled, Int picTempLayer);
-  Void decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams);
-  Void getBlkStats(Int compIdx, SAOStatData* statsDataTypes, Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height, Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-                  , Bool isCalculatePreDeblockSamples
-#endif
-                  );
-  Void deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
-  Void deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
-  Int64 getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* offsetVal, SAOStatData& statData);
-  Void deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo);
+  Void getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv,TComPic* pPic, Bool isCalculatePreDeblockSamples = false);
+  Void decidePicParams(Bool* sliceEnabled, Int picTempLayer, const Double saoEncodingRate, const Double saoEncodingRateChroma);
+  Void decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma);
+  Void getBlkStats(const ComponentID compIdx, const Int channelBitDepth, SAOStatData* statsDataTypes, Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height, Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isCalculatePreDeblockSamples);
+  Void deriveModeNewRDO(const BitDepths &bitDepths, Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Void deriveModeMergeRDO(const BitDepths &bitDepths, Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Int64 getDistortion(const Int channelBitDepth, Int typeIdc, Int typeAuxInfo, Int* offsetVal, SAOStatData& statData);
+  Void deriveOffsets(ComponentID compIdx, const Int channelBitDepth, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo);
   inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift);
-  inline Int estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh );
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  inline Int estIterOffset(Int typeIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh );
   Void addPreDBFStatistics(SAOStatData*** blkStats);
-#endif
 private: //members
   //for RDO
-  TEncSbac**             m_pppcRDSbacCoder;           
+  TEncSbac**             m_pppcRDSbacCoder;
   TEncSbac*              m_pcRDGoOnSbacCoder;
-  TEncBinCABACCounter**  m_pppcBinCoderCABAC;    
-  Double                 m_lambda[NUM_SAO_COMPONENTS];
+#if FAST_BIT_EST
+  TEncBinCABACCounter**  m_pppcBinCoderCABAC;
+#else
+  TEncBinCABAC**         m_pppcBinCoderCABAC;
+#endif
+  Double                 m_lambda[MAX_NUM_COMPONENT];
 
   //statistics
   SAOStatData***         m_statData; //[ctu][comp][classes]
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
   SAOStatData***         m_preDBFstatData;
-#endif
-#if SAO_ENCODING_CHOICE
-  Double                 m_saoDisabledRate[NUM_SAO_COMPONENTS][MAX_TLAYER];
-#endif
-  Int                    m_skipLinesR[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
-  Int                    m_skipLinesB[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+  Double                 m_saoDisabledRate[MAX_NUM_COMPONENT][MAX_TLAYER];
+  Int                    m_skipLinesR[MAX_NUM_COMPONENT][NUM_SAO_NEW_TYPES];
+  Int                    m_skipLinesB[MAX_NUM_COMPONENT][NUM_SAO_NEW_TYPES];
 };
+
+
 //! \}
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,7 +38,13 @@
 #include "TEncTop.h"
 #include "TEncSbac.h"
+#include "TLibCommon/TComTU.h"
 
 #include <map>
 #include <algorithm>
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+#include "../TLibCommon/Debug.h"
+#endif
+
 
 //! \ingroup TLibEncoder
@@ -51,60 +57,63 @@
 TEncSbac::TEncSbac()
 // new structure here
-: m_pcBitIf                   ( NULL )
-, m_pcSlice                   ( NULL )
-, m_pcBinIf                   ( NULL )
-, m_uiCoeffCost               ( 0 )
-, m_numContextModels          ( 0 )
-, m_cCUSplitFlagSCModel       ( 1,             1,               NUM_SPLIT_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels )
-, m_cCUSkipFlagSCModel        ( 1,             1,               NUM_SKIP_FLAG_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+: m_pcBitIf                            ( NULL )
+, m_pcBinIf                            ( NULL )
+, m_numContextModels                   ( 0 )
+, m_cCUSplitFlagSCModel                ( 1,             1,                      NUM_SPLIT_FLAG_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSkipFlagSCModel                 ( 1,             1,                      NUM_SKIP_FLAG_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
 #if H_3D
-, m_cCUDISFlagSCModel         ( 1,             1,               NUM_DIS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUDISTypeSCModel         ( 1,             1,               NUM_DIS_TYPE_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-, m_cCUMergeFlagExtSCModel    ( 1,             1,               NUM_MERGE_FLAG_EXT_CTX        , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUMergeIdxExtSCModel     ( 1,             1,               NUM_MERGE_IDX_EXT_CTX         , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUDISFlagSCModel                  ( 1,             1,                      NUM_DIS_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUDISTypeSCModel                  ( 1,             1,                      NUM_DIS_TYPE_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, m_cCUMergeFlagExtSCModel             ( 1,             1,                      NUM_MERGE_FLAG_EXT_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMergeIdxExtSCModel              ( 1,             1,                      NUM_MERGE_IDX_EXT_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
 #if H_3D_ARP
-, m_cCUPUARPWSCModel          ( 1,             1,               NUM_ARPW_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#if H_3D_IC
-, m_cCUICFlagSCModel          ( 1,             1,               NUM_IC_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-, m_cCUPartSizeSCModel        ( 1,             1,               NUM_PART_SIZE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUPredModeSCModel        ( 1,             1,               NUM_PRED_MODE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUIntraPredSCModel       ( 1,             1,               NUM_ADI_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUChromaPredSCModel      ( 1,             1,               NUM_CHROMA_PRED_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUDeltaQpSCModel         ( 1,             1,               NUM_DELTA_QP_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUInterDirSCModel        ( 1,             1,               NUM_INTER_DIR_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCURefPicSCModel          ( 1,             1,               NUM_REF_NO_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUMvdSCModel             ( 1,             1,               NUM_MV_RES_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUQtCbfSCModel           ( 1,             2,               NUM_QT_CBF_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUTransSubdivFlagSCModel ( 1,             1,               NUM_TRANS_SUBDIV_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUQtRootCbfSCModel       ( 1,             1,               NUM_QT_ROOT_CBF_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUSigCoeffGroupSCModel   ( 1,             2,               NUM_SIG_CG_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUSigSCModel             ( 1,             1,               NUM_SIG_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCuCtxLastX               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCuCtxLastY               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUOneSCModel             ( 1,             1,               NUM_ONE_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cSaoMergeSCModel          ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cTransformSkipSCModel     ( 1,             2,               NUM_TRANSFORMSKIP_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
-, m_CUTransquantBypassFlagSCModel( 1,          1,               NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX, m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPUARPWSCModel                   ( 1,             1,                      NUM_ARPW_CTX                         , m_contextModels + m_numContextModels, m_numContextModels)
+#endif                                                                                                               
+#if H_3D_IC                                                                                                          
+, m_cCUICFlagSCModel                   ( 1,             1,                      NUM_IC_FLAG_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, m_cCUPartSizeSCModel                 ( 1,             1,                      NUM_PART_SIZE_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPredModeSCModel                 ( 1,             1,                      NUM_PRED_MODE_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUIntraPredSCModel                ( 1,             1,                      NUM_INTRA_PREDICT_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUChromaPredSCModel               ( 1,             1,                      NUM_CHROMA_PRED_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUDeltaQpSCModel                  ( 1,             1,                      NUM_DELTA_QP_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUInterDirSCModel                 ( 1,             1,                      NUM_INTER_DIR_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCURefPicSCModel                   ( 1,             1,                      NUM_REF_NO_CTX                       , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMvdSCModel                      ( 1,             1,                      NUM_MV_RES_CTX                       , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtCbfSCModel                    ( 1,             NUM_QT_CBF_CTX_SETS,    NUM_QT_CBF_CTX_PER_SET               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUTransSubdivFlagSCModel          ( 1,             1,                      NUM_TRANS_SUBDIV_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtRootCbfSCModel                ( 1,             1,                      NUM_QT_ROOT_CBF_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigCoeffGroupSCModel            ( 1,             2,                      NUM_SIG_CG_FLAG_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigSCModel                      ( 1,             1,                      NUM_SIG_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastX                        ( 1,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastY                        ( 1,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUOneSCModel                      ( 1,             1,                      NUM_ONE_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAbsSCModel                      ( 1,             1,                      NUM_ABS_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cMVPIdxSCModel                     ( 1,             1,                      NUM_MVP_IDX_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeSCModel                   ( 1,             1,                      NUM_SAO_MERGE_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel                 ( 1,             1,                      NUM_SAO_TYPE_IDX_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cTransformSkipSCModel              ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_TRANSFORMSKIP_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_CUTransquantBypassFlagSCModel      ( 1,             1,                      NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_explicitRdpcmFlagSCModel           ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_FLAG_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_explicitRdpcmDirSCModel            ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_DIR_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCrossComponentPredictionSCModel   ( 1,             1,                      NUM_CROSS_COMPONENT_PREDICTION_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_ChromaQpAdjFlagSCModel             ( 1,             1,                      NUM_CHROMA_QP_ADJ_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_ChromaQpAdjIdcSCModel              ( 1,             1,                      NUM_CHROMA_QP_ADJ_IDC_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
 #if H_3D_DIM
-, m_cDepthIntraModeSCModel    ( 1,             1,               NUM_DEPTH_INTRA_MODE_CTX      , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cDdcFlagSCModel           ( 1,             1,               NUM_DDC_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cDdcDataSCModel           ( 1,             1,               NUM_DDC_DATA_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cAngleFlagSCModel         ( 1,             1,               NUM_ANGLE_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDepthIntraModeSCModel             ( 1,             1,                      NUM_DEPTH_INTRA_MODE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDdcFlagSCModel                    ( 1,             1,                      NUM_DDC_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDdcDataSCModel                    ( 1,             1,                      NUM_DDC_DATA_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cAngleFlagSCModel                  ( 1,             1,                      NUM_ANGLE_FLAG_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
+#if H_3D_DIM_SDC                                                                                                     
+, m_cSDCResidualFlagSCModel            ( 1,             1,                      SDC_NUM_RESIDUAL_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCResidualSCModel                ( 1,             1,                      SDC_NUM_RESIDUAL_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#endif
 #if H_3D_DIM_SDC
-, m_cSDCResidualFlagSCModel   ( 1,             1,               SDC_NUM_RESIDUAL_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cSDCResidualSCModel       ( 1,             1,               SDC_NUM_RESIDUAL_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#endif
-#if H_3D_DIM_SDC
-, m_cSDCFlagSCModel                  ( 1,             1,  NUM_SDC_FLAG_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#if H_3D_DBBP
-, m_cDBBPFlagSCModel             ( 1,             1,                 DBBP_NUM_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSDCFlagSCModel                    ( 1,             1,                       NUM_SDC_FLAG_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
+#endif                                                                                                          
+#if H_3D_DBBP                                                                                                  
+, m_cDBBPFlagSCModel                   ( 1,             1,                       DBBP_NUM_FLAG_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
 {
@@ -120,24 +129,177 @@
 // ====================================================================================================================
 
-Void TEncSbac::resetEntropy           ()
-{
-  Int  iQp              = m_pcSlice->getSliceQp();
-  SliceType eSliceType  = m_pcSlice->getSliceType();
-  
-  Int  encCABACTableIdx = m_pcSlice->getPPS()->getEncCABACTableIdx();
-  if (!m_pcSlice->isIntra() && (encCABACTableIdx==B_SLICE || encCABACTableIdx==P_SLICE) && m_pcSlice->getPPS()->getCabacInitPresentFlag())
-  {
-    eSliceType = (SliceType) encCABACTableIdx;
-  }
-
-  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
-  
-  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+Void TEncSbac::resetEntropy           (const TComSlice *pSlice)
+{
+  Int  iQp              = pSlice->getSliceQp();
+  SliceType eSliceType  = pSlice->getSliceType();
+
+  SliceType encCABACTableIdx = pSlice->getEncCABACTableIdx();
+  if (!pSlice->isIntra() && (encCABACTableIdx==B_SLICE || encCABACTableIdx==P_SLICE) && pSlice->getPPS()->getCabacInitPresentFlag())
+  {
+    eSliceType = encCABACTableIdx;
+  }
+
+  m_cCUSplitFlagSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+#if H_3D
+  m_cCUDISFlagSCModel.initBuffer                  ( eSliceType, iQp, (UChar*)INIT_DIS_FLAG );
+  m_cCUDISTypeSCModel.initBuffer                  ( eSliceType, iQp, (UChar*)INIT_DIS_TYPE );
+#endif
+  m_cCUMergeFlagExtSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
+  m_cCUMergeIdxExtSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
+#if H_3D_ARP
+  m_cCUPUARPWSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_ARPW );
+#endif
+#if H_3D_IC
+  m_cCUICFlagSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUPartSizeSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer               ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer                  ( eSliceType, iQp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer                        ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer                        ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer                     ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cSaoMergeSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cTransformSkipSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  m_explicitRdpcmFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_EXPLICIT_RDPCM_FLAG);
+  m_explicitRdpcmDirSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_EXPLICIT_RDPCM_DIR);
+  m_cCrossComponentPredictionSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_CROSS_COMPONENT_PREDICTION  );
+  m_ChromaQpAdjFlagSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
+  m_ChromaQpAdjIdcSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
+#if H_3D_DIM
+  m_cDepthIntraModeSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_DEPTH_INTRA_MODE );
+  m_cDdcFlagSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_DDC_FLAG );
+  m_cDdcDataSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_DDC_DATA );
+  m_cAngleFlagSCModel.initBuffer                  ( eSliceType, iQp, (UChar*)INIT_ANGLE_FLAG );
+#if H_3D_DIM_SDC                                 
+  m_cSDCResidualFlagSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
+#endif                                           
+#endif                                           
+#if H_3D_DIM_SDC                                 
+  m_cSDCFlagSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
+#endif                                           
+#if H_3D_DBBP                                    
+  m_cDBBPFlagSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_DBBP_FLAG );
+#endif
+
+  for (UInt statisticIndex = 0; statisticIndex < RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS ; statisticIndex++)
+  {
+    m_golombRiceAdaptationStatistics[statisticIndex] = 0;
+  }
+
+  m_pcBinIf->start();
+
+  return;
+}
+
+/** The function does the following:
+ * If current slice type is P/B then it determines the distance of initialisation type 1 and 2 from the current CABAC states and
+ * stores the index of the closest table.  This index is used for the next P/B slice when cabac_init_present_flag is true.
+ */
+SliceType TEncSbac::determineCabacInitIdx(const TComSlice *pSlice)
+{
+  Int  qp              = pSlice->getSliceQp();
+
+  if (!pSlice->isIntra())
+  {
+    SliceType aSliceTypeChoices[] = {B_SLICE, P_SLICE};
+
+    UInt bestCost             = MAX_UINT;
+    SliceType bestSliceType   = aSliceTypeChoices[0];
+    for (UInt idx=0; idx<2; idx++)
+    {
+      UInt curCost          = 0;
+      SliceType curSliceType  = aSliceTypeChoices[idx];
+
+      curCost  = m_cCUSplitFlagSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_SPLIT_FLAG );
+      curCost += m_cCUSkipFlagSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_SKIP_FLAG );
+#if H_3D
+      curCost += m_cCUDISFlagSCModel.calcCost                  ( curSliceType, qp, (UChar*)INIT_DIS_FLAG );
+      curCost += m_cCUDISTypeSCModel.calcCost                  ( curSliceType, qp, (UChar*)INIT_DIS_TYPE );
+#endif
+      curCost += m_cCUMergeFlagExtSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT);
+      curCost += m_cCUMergeIdxExtSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT);
+#if H_3D_ARP
+      curCost += m_cCUPUARPWSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_ARPW );
+#endif                                                     
+#if H_3D_IC                                                
+      curCost += m_cCUICFlagSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_IC_FLAG );
+#endif                                                     
+#if H_3D_DIM_SDC                                           
+      curCost += m_cSDCFlagSCModel.calcCost                    ( curSliceType, qp, (UChar*)INIT_SDC_FLAG );
+#endif                                                     
+#if H_3D_DBBP                                              
+      curCost += m_cDBBPFlagSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_DBBP_FLAG );
+#endif
+      curCost += m_cCUPartSizeSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
+      curCost += m_cCUPredModeSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
+      curCost += m_cCUIntraPredSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+      curCost += m_cCUChromaPredSCModel.calcCost               ( curSliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
+      curCost += m_cCUInterDirSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_INTER_DIR );
+      curCost += m_cCUMvdSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_MVD );
+      curCost += m_cCURefPicSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_REF_PIC );
+      curCost += m_cCUDeltaQpSCModel.calcCost                  ( curSliceType, qp, (UChar*)INIT_DQP );
+      curCost += m_cCUQtCbfSCModel.calcCost                    ( curSliceType, qp, (UChar*)INIT_QT_CBF );
+      curCost += m_cCUQtRootCbfSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
+      curCost += m_cCUSigCoeffGroupSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
+      curCost += m_cCUSigSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_SIG_FLAG );
+      curCost += m_cCuCtxLastX.calcCost                        ( curSliceType, qp, (UChar*)INIT_LAST );
+      curCost += m_cCuCtxLastY.calcCost                        ( curSliceType, qp, (UChar*)INIT_LAST );
+      curCost += m_cCUOneSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_ONE_FLAG );
+      curCost += m_cCUAbsSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_ABS_FLAG );
+      curCost += m_cMVPIdxSCModel.calcCost                     ( curSliceType, qp, (UChar*)INIT_MVP_IDX );
+      curCost += m_cCUTransSubdivFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+      curCost += m_cSaoMergeSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
+      curCost += m_cSaoTypeIdxSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+      curCost += m_cTransformSkipSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+      curCost += m_CUTransquantBypassFlagSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+      curCost += m_explicitRdpcmFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_FLAG);
+      curCost += m_explicitRdpcmDirSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_DIR);
+      curCost += m_cCrossComponentPredictionSCModel.calcCost   ( curSliceType, qp, (UChar*)INIT_CROSS_COMPONENT_PREDICTION );
+      curCost += m_ChromaQpAdjFlagSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
+      curCost += m_ChromaQpAdjIdcSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
+#if H_3D_DIM
+      if( m_pcSlice->getIntraSdcWedgeFlag() || m_pcSlice->getIntraContourFlag() )
+      {
+        curCost += m_cDepthIntraModeSCModel.calcCost    ( curSliceType, qp, (UChar*)INIT_DEPTH_INTRA_MODE );
+        curCost += m_cDdcFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_DDC_FLAG );
+        curCost += m_cDdcDataSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_DDC_DATA );
+        curCost += m_cAngleFlagSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_ANGLE_FLAG );  
+      }
+#endif
+
+      if (curCost < bestCost)
+      {
+        bestSliceType = curSliceType;
+        bestCost      = curCost;
+      }
+    }
+    return bestSliceType;
+  }
+  else
+  {
+    return I_SLICE;
+  }
+}
+
 #if H_3D
   m_cCUDISFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DIS_FLAG );
   m_cCUDISTypeSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DIS_TYPE );
 #endif
-  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
-  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
 #if H_3D_ARP
   m_cCUPUARPWSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_ARPW );
@@ -146,27 +308,4 @@
   m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
 #endif
-  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
-  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
-  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
-  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
-  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
-  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
-  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
-  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
-  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
-  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
-  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
-  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
-  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
-  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
-  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
-  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
-  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
-  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
-  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
-  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
-  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
-  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
-
 #if H_3D_DIM
   m_cDepthIntraModeSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_DEPTH_INTRA_MODE );
@@ -185,160 +324,7 @@
   m_cDBBPFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_DBBP_FLAG );
 #endif
-  // new structure
-  m_uiLastQp = iQp;
-  
-  m_pcBinIf->start();
-  
-  return;
-}
-
-/** The function does the following: 
- * If current slice type is P/B then it determines the distance of initialisation type 1 and 2 from the current CABAC states and 
- * stores the index of the closest table.  This index is used for the next P/B slice when cabac_init_present_flag is true.
- */
-Void TEncSbac::determineCabacInitIdx()
-{
-  Int  qp              = m_pcSlice->getSliceQp();
-
-  if (!m_pcSlice->isIntra())
-  {
-    SliceType aSliceTypeChoices[] = {B_SLICE, P_SLICE};
-
-    UInt bestCost             = MAX_UINT;
-    SliceType bestSliceType   = aSliceTypeChoices[0];
-    for (UInt idx=0; idx<2; idx++)
-    {
-      UInt curCost          = 0;
-      SliceType curSliceType  = aSliceTypeChoices[idx];
-
-      curCost  = m_cCUSplitFlagSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_SPLIT_FLAG );
-      curCost += m_cCUSkipFlagSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SKIP_FLAG );
-#if H_3D
-      curCost += m_cCUDISFlagSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_DIS_FLAG );
-      curCost += m_cCUDISTypeSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_DIS_TYPE );
-#endif
-      curCost += m_cCUMergeFlagExtSCModel.calcCost    ( curSliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT);
-      curCost += m_cCUMergeIdxExtSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT);
-#if H_3D_ARP
-      curCost += m_cCUPUARPWSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_ARPW );
-#endif
-#if H_3D_IC
-      curCost += m_cCUICFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_IC_FLAG );
-#endif
-#if H_3D_DIM_SDC
-      curCost += m_cSDCFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_SDC_FLAG );
-#endif
-#if H_3D_DBBP
-      curCost += m_cDBBPFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_DBBP_FLAG );
-#endif
-      curCost += m_cCUPartSizeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
-      curCost += m_cCUPredModeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
-      curCost += m_cCUIntraPredSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
-      curCost += m_cCUChromaPredSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
-      curCost += m_cCUInterDirSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_INTER_DIR );
-      curCost += m_cCUMvdSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_MVD );
-      curCost += m_cCURefPicSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_REF_PIC );
-      curCost += m_cCUDeltaQpSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_DQP );
-      curCost += m_cCUQtCbfSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_QT_CBF );
-      curCost += m_cCUQtRootCbfSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
-      curCost += m_cCUSigCoeffGroupSCModel.calcCost   ( curSliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
-      curCost += m_cCUSigSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_SIG_FLAG );
-      curCost += m_cCuCtxLastX.calcCost               ( curSliceType, qp, (UChar*)INIT_LAST );
-      curCost += m_cCuCtxLastY.calcCost               ( curSliceType, qp, (UChar*)INIT_LAST );
-      curCost += m_cCUOneSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_ONE_FLAG );
-      curCost += m_cCUAbsSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_ABS_FLAG );
-      curCost += m_cMVPIdxSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_MVP_IDX );
-      curCost += m_cCUTransSubdivFlagSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
-      curCost += m_cSaoMergeSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
-      curCost += m_cSaoTypeIdxSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
-      curCost += m_cTransformSkipSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
-      curCost += m_CUTransquantBypassFlagSCModel.calcCost( curSliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
-#if H_3D_DIM
-      if( m_pcSlice->getIntraSdcWedgeFlag() || m_pcSlice->getIntraContourFlag() )
-      {
-        curCost += m_cDepthIntraModeSCModel.calcCost    ( curSliceType, qp, (UChar*)INIT_DEPTH_INTRA_MODE );
-        curCost += m_cDdcFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_DDC_FLAG );
-        curCost += m_cDdcDataSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_DDC_DATA );
-        curCost += m_cAngleFlagSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_ANGLE_FLAG );  
-      }
-#endif
-      if (curCost < bestCost)
-      {
-        bestSliceType = curSliceType;
-        bestCost      = curCost;
-      }
-    }
-    m_pcSlice->getPPS()->setEncCABACTableIdx( bestSliceType );
-  }
-  else
-  {
-    m_pcSlice->getPPS()->setEncCABACTableIdx( I_SLICE );
-  }  
-}
-
-
-/** The function does the followng: Write out terminate bit. Flush CABAC. Intialize CABAC states. Start CABAC.
- */
-Void TEncSbac::updateContextTables( SliceType eSliceType, Int iQp, Bool bExecuteFinish )
-{
-  m_pcBinIf->encodeBinTrm(1);
-  if (bExecuteFinish) m_pcBinIf->finish();
-  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
-  
-  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
-#if H_3D
-  m_cCUDISFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DIS_FLAG );
-  m_cCUDISTypeSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DIS_TYPE );
-#endif
-  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
-  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
-#if H_3D_ARP
-  m_cCUPUARPWSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_ARPW );
-#endif
-#if H_3D_IC
-  m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
-#endif
-  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
-  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
-  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
-  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
-  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
-  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
-  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
-  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
-  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
-  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
-  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
-  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
-  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
-  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
-  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
-  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
-  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
-  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
-  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
-  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
-  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
-  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
-#if H_3D_DIM
-  m_cDepthIntraModeSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_DEPTH_INTRA_MODE );
-  m_cDdcFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DDC_FLAG );
-  m_cDdcDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DDC_DATA );
-  m_cAngleFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_ANGLE_FLAG );
-#if H_3D_DIM_SDC
-  m_cSDCResidualFlagSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
-  m_cSDCResidualSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
-#endif
-#endif
-#if H_3D_DIM_SDC
-  m_cSDCFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
-#endif
-#if H_3D_DBBP
-  m_cDBBPFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_DBBP_FLAG );
-#endif
-  m_pcBinIf->start();
-}
-
-Void TEncSbac::codeVPS( TComVPS* pcVPS )
+
+
+Void TEncSbac::codeVPS( const TComVPS* /*pcVPS*/ )
 {
   assert (0);
@@ -346,5 +332,5 @@
 }
 
-Void TEncSbac::codeSPS( TComSPS* pcSPS )
+Void TEncSbac::codeSPS( const TComSPS* /*pcSPS*/ )
 {
   assert (0);
@@ -352,5 +338,5 @@
 }
 
-Void TEncSbac::codePPS( TComPPS* pcPPS )
+Void TEncSbac::codePPS( const TComPPS* /*pcPPS*/ )
 {
   assert (0);
@@ -358,5 +344,5 @@
 }
 
-Void TEncSbac::codeSliceHeader( TComSlice* pcSlice )
+Void TEncSbac::codeSliceHeader( TComSlice* /*pcSlice*/ )
 {
   assert (0);
@@ -364,5 +350,5 @@
 }
 
-Void TEncSbac::codeTilesWPPEntryPoint( TComSlice* pSlice )
+Void TEncSbac::codeTilesWPPEntryPoint( TComSlice* /*pSlice*/ )
 {
   assert (0);
@@ -383,15 +369,15 @@
 {
   m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[0] );
-  
+
   if( 0 == uiSymbol)
   {
     return;
   }
-  
+
   while( uiSymbol-- )
   {
     m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ iOffset ] );
   }
-  
+
   return;
 }
@@ -403,14 +389,14 @@
     return;
   }
-  
+
   m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ 0 ] );
-  
+
   if ( uiSymbol == 0 )
   {
     return;
   }
-  
+
   Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
-  
+
   while( --uiSymbol )
   {
@@ -421,5 +407,5 @@
     m_pcBinIf->encodeBin( 0, pcSCModel[ iOffset ] );
   }
-  
+
   return;
 }
@@ -429,5 +415,5 @@
   UInt bins = 0;
   Int numBins = 0;
-  
+
   while( uiSymbol >= (UInt)(1<<uiCount) )
   {
@@ -439,11 +425,12 @@
   bins = 2 * bins + 0;
   numBins++;
-  
+
   bins = (bins << uiCount) | uiSymbol;
   numBins += uiCount;
-  
+
   assert( numBins <= 32 );
   m_pcBinIf->encodeBinsEP( bins, numBins );
 }
+
 #if H_3D
 Void TEncSbac::codeDIS( TComDataCU* pcCU, UInt uiAbsPartIdx )
@@ -478,13 +465,17 @@
 }
 #endif
+
+
 /** Coding of coeff_abs_level_minus3
- * \param uiSymbol value of coeff_abs_level_minus3
- * \param ruiGoRiceParam reference to Rice parameter
- * \returns Void
+ * \param symbol                  value of coeff_abs_level_minus3
+ * \param rParam                  reference to Rice parameter
+ * \param useLimitedPrefixLength
+ * \param maxLog2TrDynamicRange 
  */
-Void TEncSbac::xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam )
+Void TEncSbac::xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange )
 {
   Int codeNumber  = (Int)symbol;
   UInt length;
+
   if (codeNumber < (COEF_REMAIN_BIN_REDUCTION << rParam))
   {
@@ -493,17 +484,50 @@
     m_pcBinIf->encodeBinsEP((codeNumber%(1<<rParam)),rParam);
   }
+  else if (useLimitedPrefixLength)
+  {
+    const UInt maximumPrefixLength = (32 - (COEF_REMAIN_BIN_REDUCTION + maxLog2TrDynamicRange));
+
+    UInt prefixLength = 0;
+    UInt suffixLength = MAX_UINT;
+    UInt codeValue    = (symbol >> rParam) - COEF_REMAIN_BIN_REDUCTION;
+
+    if (codeValue >= ((1 << maximumPrefixLength) - 1))
+    {
+      prefixLength = maximumPrefixLength;
+      suffixLength = maxLog2TrDynamicRange - rParam;
+    }
+    else
+    {
+      while (codeValue > ((2 << prefixLength) - 2))
+      {
+        prefixLength++;
+      }
+
+      suffixLength = prefixLength + 1; //+1 for the separator bit
+    }
+
+    const UInt suffix = codeValue - ((1 << prefixLength) - 1);
+
+    const UInt totalPrefixLength = prefixLength + COEF_REMAIN_BIN_REDUCTION;
+    const UInt prefix            = (1 << totalPrefixLength) - 1;
+    const UInt rParamBitMask     = (1 << rParam) - 1;
+
+    m_pcBinIf->encodeBinsEP(  prefix,                                        totalPrefixLength      ); //prefix
+    m_pcBinIf->encodeBinsEP(((suffix << rParam) | (symbol & rParamBitMask)), (suffixLength + rParam)); //separator, suffix, and rParam bits
+  }
   else
   {
     length = rParam;
     codeNumber  = codeNumber - ( COEF_REMAIN_BIN_REDUCTION << rParam);
+
     while (codeNumber >= (1<<length))
     {
-      codeNumber -=  (1<<(length++));    
-    }
+      codeNumber -=  (1<<(length++));
+    }
+
     m_pcBinIf->encodeBinsEP((1<<(COEF_REMAIN_BIN_REDUCTION+length+1-rParam))-2,COEF_REMAIN_BIN_REDUCTION+length+1-rParam);
     m_pcBinIf->encodeBinsEP(codeNumber,length);
   }
 }
-
 #if H_3D_DIM
 Void TEncSbac::xWriteExGolombLevel( UInt uiSymbol, ContextModel& rcSCModel  )
@@ -558,17 +582,23 @@
 #endif
 
-
 // SBAC RD
-Void  TEncSbac::load ( TEncSbac* pSrc)
+Void  TEncSbac::load ( const TEncSbac* pSrc)
 {
   this->xCopyFrom(pSrc);
 }
 
-Void  TEncSbac::loadIntraDirModeLuma( TEncSbac* pSrc)
+Void  TEncSbac::loadIntraDirMode( const TEncSbac* pSrc, const ChannelType chType )
 {
   m_pcBinIf->copyState( pSrc->m_pcBinIf );
-  
-  this->m_cCUIntraPredSCModel      .copyFrom( &pSrc->m_cCUIntraPredSCModel       );
-}
+  if (isLuma(chType))
+  {
+    this->m_cCUIntraPredSCModel      .copyFrom( &pSrc->m_cCUIntraPredSCModel       );
+  }
+  else
+  {
+    this->m_cCUChromaPredSCModel     .copyFrom( &pSrc->m_cCUChromaPredSCModel      );
+  }
+}
+
 #if H_3D_DIM
 Void TEncSbac::loadIntraDepthMode( TEncSbac* pSrc)
@@ -582,5 +612,6 @@
 #endif
 
-Void  TEncSbac::store( TEncSbac* pDest)
+
+Void  TEncSbac::store( TEncSbac* pDest) const
 {
   pDest->xCopyFrom( this );
@@ -588,12 +619,8 @@
 
 
-Void TEncSbac::xCopyFrom( TEncSbac* pSrc )
+Void TEncSbac::xCopyFrom( const TEncSbac* pSrc )
 {
   m_pcBinIf->copyState( pSrc->m_pcBinIf );
-  
-  this->m_uiCoeffCost = pSrc->m_uiCoeffCost;
-  this->m_uiLastQp    = pSrc->m_uiLastQp;
-  
-  memcpy( m_contextModels, pSrc->m_contextModels, m_numContextModels * sizeof( ContextModel ) );
+  xCopyContextsFrom(pSrc);
 }
 
@@ -653,7 +680,9 @@
   }
 #endif
+  const UInt log2DiffMaxMinCodingBlockSize = pcCU->getSlice()->getSPS()->getLog2DiffMaxMinCodingBlockSize();
+
   if ( pcCU->isIntra( uiAbsPartIdx ) )
   {
-    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    if( uiDepth == log2DiffMaxMinCodingBlockSize )
     {
       m_pcBinIf->encodeBin( eSize == SIZE_2Nx2N? 1 : 0, m_cCUPartSizeSCModel.get( 0, 0, 0 ) );
@@ -661,8 +690,8 @@
       DTRACE_CU("part_mode", eSize == SIZE_2Nx2N? 1 : 0)
 #endif        
+
     }
     return;
   }
-
 #if H_MV_ENC_DEC_TRAC          
   DTRACE_CU("part_mode", eSize )
@@ -672,70 +701,74 @@
     {
 #endif
-      switch(eSize)
-      {
-      case SIZE_2Nx2N:
+
+  switch(eSize)
+  {
+    case SIZE_2Nx2N:
+    {
+      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      break;
+    }
+    case SIZE_2NxN:
+    case SIZE_2NxnU:
+    case SIZE_2NxnD:
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+      if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
+      {
+        if (eSize == SIZE_2NxN)
         {
-          m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
-          break;
+          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
         }
-      case SIZE_2NxN:
-      case SIZE_2NxnU:
-      case SIZE_2NxnD:
+        else
         {
-          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
-          m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
-          if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
-          {
-            if (eSize == SIZE_2NxN)
-            {
-              m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-            }
-            else
-            {
-              m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-              m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
-            }
-          }
-          break;
+          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+          m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
         }
-      case SIZE_Nx2N:
-      case SIZE_nLx2N:
-      case SIZE_nRx2N:
+      }
+      break;
+    }
+    case SIZE_Nx2N:
+    case SIZE_nLx2N:
+    case SIZE_nRx2N:
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+
+      if( uiDepth == log2DiffMaxMinCodingBlockSize && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+      {
+        m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+      }
+
+      if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
+      {
+        if (eSize == SIZE_Nx2N)
         {
-          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
-          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
-          if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
-          {
-            m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
-          }
-          if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
-          {
-            if (eSize == SIZE_Nx2N)
-            {
-              m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-            }
-            else
-            {
-              m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-              m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
-            }
-          }
-          break;
+          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
         }
-      case SIZE_NxN:
+        else
         {
-          if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
-          {
-            m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
-            m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
-            m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
-          }
-          break;
+          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+          m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
         }
-      default:
-        {
-          assert(0);
-        }
-      }
+      }
+      break;
+    }
+    case SIZE_NxN:
+    {
+      if( uiDepth == log2DiffMaxMinCodingBlockSize && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+      {
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+      }
+      break;
+    }
+    default:
+    {
+      assert(0);
+      break;
+    }
+  }
 #if H_3D_QTLPC
     }
@@ -816,9 +849,11 @@
     }
 #endif
-}
+
+}
+
 
 /** code prediction mode
  * \param pcCU
- * \param uiAbsPartIdx  
+ * \param uiAbsPartIdx
  * \returns Void
  */
@@ -834,9 +869,9 @@
   
   // get context function is here
-  Int iPredMode = pcCU->getPredictionMode( uiAbsPartIdx );
-  m_pcBinIf->encodeBin( iPredMode == MODE_INTER ? 0 : 1, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+  m_pcBinIf->encodeBin( pcCU->isIntra( uiAbsPartIdx ) ? 1 : 0, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
 #if H_MV_ENC_DEC_TRAC
-  DTRACE_CU("pred_mode_flag", iPredMode == MODE_INTER ? 0 : 1); 
-#endif
+  DTRACE_CU("pred_mode_flag", pcCU->isIntra( uiAbsPartIdx ) ? 1 : 0); 
+#endif
+
 }
 
@@ -848,9 +883,10 @@
   DTRACE_CU("cu_transquant_bypass_flag", uiSymbol); 
 #endif
+
 }
 
 /** code skip flag
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \returns Void
  */
@@ -876,5 +912,5 @@
 /** code merge flag
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \returns Void
  */
@@ -891,5 +927,5 @@
   DTRACE_CABAC_V( uiSymbol );
   DTRACE_CABAC_T( "\tAddress: " );
-  DTRACE_CABAC_V( pcCU->getAddr() );
+  DTRACE_CABAC_V( pcCU->getCtuRsAddr() );
   DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
   DTRACE_CABAC_V( uiAbsPartIdx );
@@ -900,5 +936,5 @@
 /** code merge index
  * \param pcCU
- * \param uiAbsPartIdx 
+ * \param uiAbsPartIdx
  * \returns Void
  */
@@ -984,10 +1020,12 @@
 Void TEncSbac::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
-  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+  if( uiDepth == pcCU->getSlice()->getSPS()->getLog2DiffMaxMinCodingBlockSize() )
+  {
     return;
-  
+  }
+
   UInt uiCtx           = pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth );
   UInt uiCurrSplitFlag = ( pcCU->getDepth( uiAbsPartIdx ) > uiDepth ) ? 1 : 0;
-  
+
   assert( uiCtx < 3 );
 #if H_3D_QTLPC
@@ -1020,4 +1058,5 @@
   }
 #endif
+
   m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) );
 #if !H_MV_ENC_DEC_TRAC
@@ -1047,15 +1086,16 @@
 }
 
+
 Void TEncSbac::codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple)
 {
   UInt dir[4],j;
-  Int preds[4][3] = {{-1, -1, -1},{-1, -1, -1},{-1, -1, -1},{-1, -1, -1}};
-  Int predNum[4], predIdx[4] ={ -1,-1,-1,-1};
+  Int preds[4][NUM_MOST_PROBABLE_MODES] = {{-1, -1, -1},{-1, -1, -1},{-1, -1, -1},{-1, -1, -1}};
+  Int predIdx[4] ={ -1,-1,-1,-1};
   PartSize mode = pcCU->getPartitionSize( absPartIdx );
   UInt partNum = isMultiple?(mode==SIZE_NxN?4:1):1;
-  UInt partOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
+  UInt partOffset = ( pcCU->getPic()->getNumPartitionsInCtu() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
   for (j=0;j<partNum;j++)
   {
-    dir[j] = pcCU->getLumaIntraDir( absPartIdx+partOffset*j );
+    dir[j] = pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx+partOffset*j );
 #if H_3D_DIM
     if( pcCU->getSlice()->getIntraSdcWedgeFlag() ||  pcCU->getSlice()->getIntraContourFlag() )
@@ -1066,13 +1106,13 @@
     {
 #endif
-      predNum[j] = pcCU->getIntraDirLumaPredictor(absPartIdx+partOffset*j, preds[j]);  
-      for(UInt i = 0; i < predNum[j]; i++)
-      {
-        if(dir[j] == preds[j][i])
-        {
-          predIdx[j] = i;
-        }
-      }
-      m_pcBinIf->encodeBin((predIdx[j] != -1)? 1 : 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+    pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds[j], COMPONENT_Y);
+    for(UInt i = 0; i < NUM_MOST_PROBABLE_MODES; i++)
+    {
+      if(dir[j] == preds[j][i])
+      {
+        predIdx[j] = i;
+      }
+    }
+    m_pcBinIf->encodeBin((predIdx[j] != -1)? 1 : 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
 #if H_MV_ENC_DEC_TRAC
       DTRACE_CU("prev_intra_luma_pred_flag", (predIdx[j] != -1)? 1 : 0); 
@@ -1082,5 +1122,5 @@
 #endif
 
-  }  
+  }
   for (j=0;j<partNum;j++)
   {
@@ -1089,38 +1129,38 @@
     {
 #endif
-      if(predIdx[j] != -1)
-      {
-        m_pcBinIf->encodeBinEP( predIdx[j] ? 1 : 0 );
-        if (predIdx[j])
-        {
-          m_pcBinIf->encodeBinEP( predIdx[j]-1 );
-        }
+    if(predIdx[j] != -1)
+    {
+      m_pcBinIf->encodeBinEP( predIdx[j] ? 1 : 0 );
+      if (predIdx[j])
+      {
+        m_pcBinIf->encodeBinEP( predIdx[j]-1 );
+      }
 #if H_MV_ENC_DEC_TRAC
         DTRACE_CU("mpm_idx", predIdx[j] ); 
 #endif
-      }
-      else
-      {
-        if (preds[j][0] > preds[j][1])
-        { 
-          std::swap(preds[j][0], preds[j][1]); 
-        }
-        if (preds[j][0] > preds[j][2])
-        {
-          std::swap(preds[j][0], preds[j][2]);
-        }
-        if (preds[j][1] > preds[j][2])
-        {
-          std::swap(preds[j][1], preds[j][2]);
-        }
-        for(Int i = (predNum[j] - 1); i >= 0; i--)
-        {
-          dir[j] = dir[j] > preds[j][i] ? dir[j] - 1 : dir[j];
-        }
-        m_pcBinIf->encodeBinsEP( dir[j], 5 );
+    }
+    else
+    {
+      if (preds[j][0] > preds[j][1])
+      {
+        std::swap(preds[j][0], preds[j][1]);
+      }
+      if (preds[j][0] > preds[j][2])
+      {
+        std::swap(preds[j][0], preds[j][2]);
+      }
+      if (preds[j][1] > preds[j][2])
+      {
+        std::swap(preds[j][1], preds[j][2]);
+      }
+      for(Int i = (Int(NUM_MOST_PROBABLE_MODES) - 1); i >= 0; i--)
+      {
+        dir[j] = dir[j] > preds[j][i] ? dir[j] - 1 : dir[j];
+      }
+      m_pcBinIf->encodeBinsEP( dir[j], 5 );
 #if H_MV_ENC_DEC_TRAC
         DTRACE_CU("rem_intra_luma_pred_mode", dir[j] ); 
 #endif
-      }
+    }
 #if H_3D_DIM
     }
@@ -1132,7 +1172,7 @@
 Void TEncSbac::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
-  UInt uiIntraDirChroma = pcCU->getChromaIntraDir( uiAbsPartIdx );
-
-  if( uiIntraDirChroma == DM_CHROMA_IDX ) 
+  UInt uiIntraDirChroma = pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx );
+
+  if( uiIntraDirChroma == DM_CHROMA_IDX )
   {
     m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
@@ -1142,5 +1182,7 @@
   }
   else
-  { 
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+
     UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
     pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
@@ -1154,5 +1196,4 @@
       }
     }
-    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
 
     m_pcBinIf->encodeBinsEP( uiIntraDirChroma, 2 );
@@ -1162,4 +1203,5 @@
 
   }
+
   return;
 }
@@ -1213,5 +1255,4 @@
 #endif
 
-
 Void TEncSbac::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
@@ -1219,8 +1260,10 @@
   const UInt uiCtx      = pcCU->getCtxInterDir( uiAbsPartIdx );
   ContextModel *pCtx    = m_cCUInterDirSCModel.get( 0 );
+
   if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N || pcCU->getHeight(uiAbsPartIdx) != 8 )
   {
     m_pcBinIf->encodeBin( uiInterDir == 2 ? 1 : 0, *( pCtx + uiCtx ) );
   }
+
   if (uiInterDir < 2)
   {
@@ -1236,31 +1279,30 @@
 Void TEncSbac::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
 {
-  {
-    Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
-    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
-    m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), *pCtx );
-    
-    if( iRefFrame > 0 )
-    {
-      UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
-      pCtx++;
-      iRefFrame--;
-      for( UInt ui = 0; ui < uiRefNum; ++ui )
-      {
-        const UInt uiSymbol = ui == iRefFrame ? 0 : 1;
-        if( ui == 0 )
-        {
-          m_pcBinIf->encodeBin( uiSymbol, *pCtx );       
-        }
-        else
-        {
-          m_pcBinIf->encodeBinEP( uiSymbol );
-        }
-        if( uiSymbol == 0 )
-        {
-          break;
-        }
-      }
-    }
+  Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
+  ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+  m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), *pCtx );
+
+  if( iRefFrame > 0 )
+  {
+    UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
+    pCtx++;
+    iRefFrame--;
+    for( UInt ui = 0; ui < uiRefNum; ++ui )
+    {
+      const UInt uiSymbol = ui == iRefFrame ? 0 : 1;
+      if( ui == 0 )
+      {
+        m_pcBinIf->encodeBin( uiSymbol, *pCtx );
+      }
+      else
+      {
+        m_pcBinIf->encodeBinEP( uiSymbol );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+  }
 #if H_MV_ENC_DEC_TRAC
 #if ENC_DEC_TRACE
@@ -1276,5 +1318,4 @@
 #endif
 #endif
-  }
   return;
 }
@@ -1330,13 +1371,59 @@
     m_pcBinIf->encodeBinEP( 0 > iVer ? 1 : 0 );
   }
-  
+
   return;
 }
 
+Void TEncSbac::codeCrossComponentPrediction( TComTU &rTu, ComponentID compID )
+{
+  TComDataCU *pcCU = rTu.getCU();
+
+  if( isLuma(compID) || !pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag() )
+  {
+    return;
+  }
+
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+
+  if (!pcCU->isIntra(uiAbsPartIdx) || (pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx ) == DM_CHROMA_IDX))
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T("\tparseCrossComponentPrediction()")
+    DTRACE_CABAC_T( "\tAddr=" )
+    DTRACE_CABAC_V( compID )
+    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+    DTRACE_CABAC_V( uiAbsPartIdx )
+
+    Int alpha = pcCU->getCrossComponentPredictionAlpha( uiAbsPartIdx, compID );
+    ContextModel *pCtx = m_cCrossComponentPredictionSCModel.get(0, 0) + ((compID == COMPONENT_Cr) ? (NUM_CROSS_COMPONENT_PREDICTION_CTX >> 1) : 0);
+    m_pcBinIf->encodeBin(((alpha != 0) ? 1 : 0), pCtx[0]);
+
+    if (alpha != 0)
+    {
+      static const Int log2AbsAlphaMinus1Table[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
+      assert(abs(alpha) <= 8);
+
+      if (abs(alpha)>1)
+      {
+        m_pcBinIf->encodeBin(1, pCtx[1]);
+        xWriteUnaryMaxSymbol( log2AbsAlphaMinus1Table[abs(alpha) - 1] - 1, (pCtx + 2), 1, 2 );
+      }
+      else
+      {
+        m_pcBinIf->encodeBin(0, pCtx[1]);
+      }
+      m_pcBinIf->encodeBin( ((alpha < 0) ? 1 : 0), pCtx[4] );
+    }
+    DTRACE_CABAC_T( "\tAlpha=" )
+    DTRACE_CABAC_V( pcCU->getCrossComponentPredictionAlpha( uiAbsPartIdx, compID ) )
+    DTRACE_CABAC_T( "\n" )
+  }
+}
+
 Void TEncSbac::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
   Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
-  
-  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
   iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
 
@@ -1358,50 +1445,143 @@
 }
 
-Void TEncSbac::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
-{
-  UInt uiCbf = pcCU->getCbf     ( uiAbsPartIdx, eType, uiTrDepth );
-  UInt uiCtx = pcCU->getCtxQtCbf( eType, uiTrDepth );
-  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) );
+/** code chroma qp adjustment, converting from the internal table representation
+ * \returns Void
+ */
+Void TEncSbac::codeChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx )
+{
+  Int internalIdc = cu->getChromaQpAdj( absPartIdx );
+  Int chromaQpOffsetListLen = cu->getSlice()->getPPS()->getPpsRangeExtension().getChromaQpOffsetListLen();
+  /* internal_idc == 0 => flag = 0
+   * internal_idc > 1 => code idc value (if table size warrents) */
+  m_pcBinIf->encodeBin( internalIdc > 0, m_ChromaQpAdjFlagSCModel.get( 0, 0, 0 ) );
+
+  if (internalIdc > 0 && chromaQpOffsetListLen > 1)
+  {
+    xWriteUnaryMaxSymbol( internalIdc - 1, &m_ChromaQpAdjIdcSCModel.get( 0, 0, 0 ), 0, chromaQpOffsetListLen - 1 );
+  }
+}
+
+Void TEncSbac::codeQtCbf( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
+{
+  TComDataCU* pcCU = rTu.getCU();
+
+  const UInt absPartIdx   = rTu.GetAbsPartIdxTU(compID);
+  const UInt TUDepth      = rTu.GetTransformDepthRel();
+        UInt uiCtx        = pcCU->getCtxQtCbf( rTu, toChannelType(compID) );
+  const UInt contextSet   = toChannelType(compID);
+
+  const UInt width        = rTu.getRect(compID).width;
+  const UInt height       = rTu.getRect(compID).height;
+  const Bool canQuadSplit = (width >= (MIN_TU_SIZE * 2)) && (height >= (MIN_TU_SIZE * 2));
+
+  //             Since the CBF for chroma is coded at the highest level possible, if sub-TUs are
+  //             to be coded for a 4x8 chroma TU, their CBFs must be coded at the highest 4x8 level
+  //             (i.e. where luma TUs are 8x8 rather than 4x4)
+  //    ___ ___
+  //   |   |   | <- 4 x (8x8 luma + 4x8 4:2:2 chroma)
+  //   |___|___|    each quadrant has its own chroma CBF
+  //   |   |   | _ _ _ _
+  //   |___|___|        |
+  //   <--16--->        V
+  //                   _ _
+  //                  |_|_| <- 4 x 4x4 luma + 1 x 4x8 4:2:2 chroma
+  //                  |_|_|    no chroma CBF is coded - instead the parent CBF is inherited
+  //                  <-8->    if sub-TUs are present, their CBFs had to be coded at the parent level
+
+  const UInt lowestTUDepth = TUDepth + ((!lowestLevel && !canQuadSplit) ? 1 : 0); //unsplittable TUs inherit their parent's CBF
+
+  if ((width != height) && (lowestLevel || !canQuadSplit)) //if sub-TUs are present
+  {
+    const UInt subTUDepth        = lowestTUDepth + 1;                      //if this is the lowest level of the TU-tree, the sub-TUs are directly below. Otherwise, this must be the level above the lowest level (as specified above)
+    const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
+
+    for (UInt subTU = 0; subTU < 2; subTU++)
+    {
+      const UInt subTUAbsPartIdx = absPartIdx + (subTU * partIdxesPerSubTU);
+      const UInt uiCbf           = pcCU->getCbf(subTUAbsPartIdx, compID, subTUDepth);
+
+      m_pcBinIf->encodeBin(uiCbf, m_cCUQtCbfSCModel.get(0, contextSet, uiCtx));
 #if !H_MV_ENC_DEC_TRAC
-  DTRACE_CABAC_VL( g_nSymbolCounter++ )
-  DTRACE_CABAC_T( "\tparseQtCbf()" )
-  DTRACE_CABAC_T( "\tsymbol=" )
-  DTRACE_CABAC_V( uiCbf )
-  DTRACE_CABAC_T( "\tctx=" )
-  DTRACE_CABAC_V( uiCtx )
-  DTRACE_CABAC_T( "\tetype=" )
-  DTRACE_CABAC_V( eType )
-  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
-  DTRACE_CABAC_V( uiAbsPartIdx )
-  DTRACE_CABAC_T( "\n" )
+      DTRACE_CABAC_VL( g_nSymbolCounter++ )
+      DTRACE_CABAC_T( "\tparseQtCbf()" )
+      DTRACE_CABAC_T( "\tsub-TU=" )
+      DTRACE_CABAC_V( subTU )
+      DTRACE_CABAC_T( "\tsymbol=" )
+      DTRACE_CABAC_V( uiCbf )
+      DTRACE_CABAC_T( "\tctx=" )
+      DTRACE_CABAC_V( uiCtx )
+      DTRACE_CABAC_T( "\tetype=" )
+      DTRACE_CABAC_V( compID )
+      DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+      DTRACE_CABAC_V( subTUAbsPartIdx )
+      DTRACE_CABAC_T( "\n" )
 #else
-  if ( eType == TEXT_CHROMA_U )
-  {
-    DTRACE_TU("cbf_cb", uiCbf )
-  }
-  else if ( eType == TEXT_CHROMA_V )
-  {
-    DTRACE_TU("cbf_cr", uiCbf )
+      if ( compID == COMPONENT_Cb )
+      {
+        DTRACE_TU("cbf_cb", uiCbf )
+      }
+      else if ( compID == COMPONENT_Cr )
+      {
+        DTRACE_TU("cbf_cr", uiCbf )
+      }
+      else
+      {
+        DTRACE_TU("cbf_luma", uiCbf )
+      }
+#endif
+    }
   }
   else
   {
-    DTRACE_TU("cbf_luma", uiCbf )
-  }
-#endif
-}
-
-void TEncSbac::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType )
-{
+    const UInt uiCbf = pcCU->getCbf( absPartIdx, compID, lowestTUDepth );
+    m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, contextSet, uiCtx ) );
+#if !H_MV_ENC_DEC_TRAC
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tparseQtCbf()" )
+    DTRACE_CABAC_T( "\tsymbol=" )
+    DTRACE_CABAC_V( uiCbf )
+    DTRACE_CABAC_T( "\tctx=" )
+    DTRACE_CABAC_V( uiCtx )
+    DTRACE_CABAC_T( "\tetype=" )
+    DTRACE_CABAC_V( compID )
+    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+    DTRACE_CABAC_V( rTu.GetAbsPartIdxTU(compID) )
+    DTRACE_CABAC_T( "\n" )
+#else
+    if ( compID == COMPONENT_Cb )
+    {
+      DTRACE_TU("cbf_cb", uiCbf )
+    }
+    else if ( compID == COMPONENT_Cr )
+    {
+      DTRACE_TU("cbf_cr", uiCbf )
+    }
+    else
+    {
+      DTRACE_TU("cbf_luma", uiCbf )
+    }
+#endif
+
+  }
+}
+
+
+Void TEncSbac::codeTransformSkipFlags (TComTU &rTu, ComponentID component )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
   if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
   {
     return;
   }
-  if(width != 4 || height != 4)
+
+  if (!TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(component), pcCU->getSlice()->getPPS()->getPpsRangeExtension().getLog2MaxTransformSkipBlockSize()))
   {
     return;
   }
 
-  UInt useTransformSkip = pcCU->getTransformSkip( uiAbsPartIdx,eTType);
-  m_pcBinIf->encodeBin( useTransformSkip, m_cTransformSkipSCModel.get( 0, eTType? TEXT_CHROMA: TEXT_LUMA, 0 ) );
+  UInt useTransformSkip = pcCU->getTransformSkip( uiAbsPartIdx,component);
+  m_pcBinIf->encodeBin( useTransformSkip, m_cTransformSkipSCModel.get( 0, toChannelType(component), 0 ) );
 #if !H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
@@ -1410,12 +1590,13 @@
   DTRACE_CABAC_V( useTransformSkip )
   DTRACE_CABAC_T( "\tAddr=" )
-  DTRACE_CABAC_V( pcCU->getAddr() )
+  DTRACE_CABAC_V( pcCU->getCtuRsAddr() )
   DTRACE_CABAC_T( "\tetype=" )
-  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_V( component )
   DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
-  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_V( rTu.GetAbsPartIdxTU() )
   DTRACE_CABAC_T( "\n" )
 #endif
 }
+
 
 /** Code I_PCM information.
@@ -1438,67 +1619,24 @@
     m_pcBinIf->encodePCMAlignBits();
 
-    UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
-    UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
-    UInt uiChromaOffset = uiLumaOffset>>2;
-    Pel* piPCMSample;
-    UInt uiWidth;
-    UInt uiHeight;
-    UInt uiSampleBits;
-    UInt uiX, uiY;
-
-    piPCMSample = pcCU->getPCMSampleY() + uiLumaOffset;
-    uiWidth = pcCU->getWidth(uiAbsPartIdx);
-    uiHeight = pcCU->getHeight(uiAbsPartIdx);
-    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
-
-    for(uiY = 0; uiY < uiHeight; uiY++)
-    {
-      for(uiX = 0; uiX < uiWidth; uiX++)
-      {
-        UInt uiSample = piPCMSample[uiX];
-
-        m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
-      }
-      piPCMSample += uiWidth;
-    }
-
-#if H_3D_DISABLE_CHROMA
-    if( pcCU->getSlice()->getSPS()->getChromaFormatIdc() != 0 )
-    {    
-#endif
-      piPCMSample = pcCU->getPCMSampleCb() + uiChromaOffset;
-      uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
-      uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
-      uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
-
-      for(uiY = 0; uiY < uiHeight; uiY++)
-      {
-        for(uiX = 0; uiX < uiWidth; uiX++)
+    const UInt minCoeffSizeY = pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight();
+    const UInt offsetY       = minCoeffSizeY * uiAbsPartIdx;
+    for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      const UInt offset = offsetY >> (pcCU->getPic()->getComponentScaleX(compID) + pcCU->getPic()->getComponentScaleY(compID));
+      Pel * pPCMSample  = pcCU->getPCMSample(compID) + offset;
+      const UInt width  = pcCU->getWidth (uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleX(compID);
+      const UInt height = pcCU->getHeight(uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleY(compID);
+      const UInt sampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
+      for (UInt y=0; y<height; y++)
+      {
+        for (UInt x=0; x<width; x++)
         {
-          UInt uiSample = piPCMSample[uiX];
-
-          m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
+          UInt sample = pPCMSample[x];
+          m_pcBinIf->xWritePCMCode(sample, sampleBits);
         }
-        piPCMSample += uiWidth;
-      }
-
-      piPCMSample = pcCU->getPCMSampleCr() + uiChromaOffset;
-      uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
-      uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
-      uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
-
-      for(uiY = 0; uiY < uiHeight; uiY++)
-      {
-        for(uiX = 0; uiX < uiWidth; uiX++)
-        {
-          UInt uiSample = piPCMSample[uiX];
-
-          m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
-        }
-        piPCMSample += uiWidth;
-      }
-#if H_3D_DISABLE_CHROMA
-    }
-#endif
+        pPCMSample += width;
+      }
+    }
     m_pcBinIf->resetBac();
   }
@@ -1525,14 +1663,15 @@
 }
 
-Void TEncSbac::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
+Void TEncSbac::codeQtCbfZero( TComTU & rTu, const ChannelType chType )
 {
   // this function is only used to estimate the bits when cbf is 0
   // and will never be called when writing the bistream. do not need to write log
   UInt uiCbf = 0;
-  UInt uiCtx = pcCU->getCtxQtCbf( eType, uiTrDepth );
-  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) );
-}
-
-Void TEncSbac::codeQtRootCbfZero( TComDataCU* pcCU )
+  UInt uiCtx = rTu.getCU()->getCtxQtCbf( rTu, chType );
+
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, chType, uiCtx ) );
+}
+
+Void TEncSbac::codeQtRootCbfZero( )
 {
   // this function is only used to estimate the bits when cbf is 0
@@ -1544,43 +1683,46 @@
 
 /** Encode (X,Y) position of the last significant coefficient
- * \param uiPosX X component of last coefficient
- * \param uiPosY Y component of last coefficient
- * \param width  Block width
- * \param height Block height
- * \param eTType plane type / luminance or chrominance
- * \param uiScanIdx scan type (zig-zag, hor, ver)
+ * \param uiPosX     X component of last coefficient
+ * \param uiPosY     Y component of last coefficient
+ * \param width      Block width
+ * \param height     Block height
+ * \param component  chroma component ID
+ * \param uiScanIdx  scan type (zig-zag, hor, ver)
  * This method encodes the X and Y component within a block of the last significant coefficient.
  */
-Void TEncSbac::codeLastSignificantXY( UInt uiPosX, UInt uiPosY, Int width, Int height, TextType eTType, UInt uiScanIdx )
-{  
+Void TEncSbac::codeLastSignificantXY( UInt uiPosX, UInt uiPosY, Int width, Int height, ComponentID component, UInt uiScanIdx )
+{
   // swap
   if( uiScanIdx == SCAN_VER )
   {
     swap( uiPosX, uiPosY );
+    swap( width,  height );
   }
 
   UInt uiCtxLast;
-  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType );
-  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType );
   UInt uiGroupIdxX    = g_uiGroupIdx[ uiPosX ];
   UInt uiGroupIdxY    = g_uiGroupIdx[ uiPosY ];
 
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, toChannelType(component) );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, toChannelType(component) );
 
   Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
-  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
-  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
-  shiftX= eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
-  shiftY= eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
+  getLastSignificantContextParameters(component, width, height, blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY);
+
+  //------------------
+
   // posX
+
   for( uiCtxLast = 0; uiCtxLast < uiGroupIdxX; uiCtxLast++ )
   {
-      m_pcBinIf->encodeBin( 1, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
+    m_pcBinIf->encodeBin( 1, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
   }
   if( uiGroupIdxX < g_uiGroupIdx[ width - 1 ])
   {
-      m_pcBinIf->encodeBin( 0, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
+    m_pcBinIf->encodeBin( 0, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
   }
 
   // posY
+
   for( uiCtxLast = 0; uiCtxLast < uiGroupIdxY; uiCtxLast++ )
   {
@@ -1591,6 +1733,9 @@
     m_pcBinIf->encodeBin( 0, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) );
   }
+
+  // EP-coded part
+
   if ( uiGroupIdxX > 3 )
-  {      
+  {
     UInt uiCount = ( uiGroupIdxX - 2 ) >> 1;
     uiPosX       = uiPosX - g_uiMinInGroup[ uiGroupIdxX ];
@@ -1601,5 +1746,5 @@
   }
   if ( uiGroupIdxY > 3 )
-  {      
+  {
     UInt uiCount = ( uiGroupIdxY - 2 ) >> 1;
     uiPosY       = uiPosY - g_uiMinInGroup[ uiGroupIdxY ];
@@ -1611,10 +1756,18 @@
 }
 
-Void TEncSbac::codeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
-{
+
+Void TEncSbac::codeCoeffNxN( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU(compID);
+  const TComRectangle &tuRect=rTu.getRect(compID);
+  const UInt uiWidth=tuRect.width;
+  const UInt uiHeight=tuRect.height;
+  const TComSPS &sps=*(pcCU->getSlice()->getSPS());
 #if !H_MV_ENC_DEC_TRAC
+
   DTRACE_CABAC_VL( g_nSymbolCounter++ )
   DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
-  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_V( compID )
   DTRACE_CABAC_T( "\twidth=" )
   DTRACE_CABAC_V( uiWidth )
@@ -1622,5 +1775,6 @@
   DTRACE_CABAC_V( uiHeight )
   DTRACE_CABAC_T( "\tdepth=" )
-  DTRACE_CABAC_V( uiDepth )
+//  DTRACE_CABAC_V( rTu.GetTransformDepthTotalAdj(compID) )
+  DTRACE_CABAC_V( rTu.GetTransformDepthTotal() )
   DTRACE_CABAC_T( "\tabspartidx=" )
   DTRACE_CABAC_V( uiAbsPartIdx )
@@ -1630,46 +1784,109 @@
   DTRACE_CABAC_V( pcCU->getCUPelY() )
   DTRACE_CABAC_T( "\tCU-addr=" )
-  DTRACE_CABAC_V(  pcCU->getAddr() )
+  DTRACE_CABAC_V(  pcCU->getCtuRsAddr() )
   DTRACE_CABAC_T( "\tinCU-X=" )
-  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+//  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
   DTRACE_CABAC_T( "\tinCU-Y=" )
-  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+// DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
   DTRACE_CABAC_T( "\tpredmode=" )
   DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
   DTRACE_CABAC_T( "\n" )
 #endif
-  if( uiWidth > m_pcSlice->getSPS()->getMaxTrSize() )
-  {
-    uiWidth  = m_pcSlice->getSPS()->getMaxTrSize();
-    uiHeight = m_pcSlice->getSPS()->getMaxTrSize();
-  }
-  
-  UInt uiNumSig = 0;
-  
+
+  //--------------------------------------------------------------------------------------------------
+
+  if( uiWidth > sps.getMaxTrSize() )
+  {
+    std::cerr << "ERROR: codeCoeffNxN was passed a TU with dimensions larger than the maximum allowed size" << std::endl;
+    assert(false);
+    exit(1);
+  }
+
   // compute number of significant coefficients
-  uiNumSig = TEncEntropy::countNonZeroCoeffs(pcCoef, uiWidth * uiHeight);
-  
+  UInt uiNumSig = TEncEntropy::countNonZeroCoeffs(pcCoef, uiWidth * uiHeight);
+
   if ( uiNumSig == 0 )
-    return;
+  {
+    std::cerr << "ERROR: codeCoeffNxN called for empty TU!" << std::endl;
+    assert(false);
+    exit(1);
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  //set parameters
+
+  const ChannelType  chType            = toChannelType(compID);
+  const UInt         uiLog2BlockWidth  = g_aucConvertToBit[ uiWidth  ] + 2;
+  const UInt         uiLog2BlockHeight = g_aucConvertToBit[ uiHeight ] + 2;
+
+  const ChannelType  channelType       = toChannelType(compID);
+  const Bool         extendedPrecision = sps.getSpsRangeExtension().getExtendedPrecisionProcessingFlag();
+
+  const Bool         alignCABACBeforeBypass = sps.getSpsRangeExtension().getCabacBypassAlignmentEnabledFlag();
+  const Int          maxLog2TrDynamicRange  = sps.getMaxLog2TrDynamicRange(channelType);
+
+  Bool beValid;
+
+  {
+    Int uiIntraMode = -1;
+    const Bool       bIsLuma = isLuma(compID);
+    Int isIntra = pcCU->isIntra(uiAbsPartIdx) ? 1 : 0;
+    if ( isIntra )
+    {
+      uiIntraMode = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
+
+      const UInt partsPerMinCU = 1<<(2*(sps.getMaxTotalCUDepth() - sps.getLog2DiffMaxMinCodingBlockSize()));
+      uiIntraMode = (uiIntraMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, rTu.GetChromaFormat(), partsPerMinCU)) : uiIntraMode;
+      uiIntraMode = ((rTu.GetChromaFormat() == CHROMA_422) && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiIntraMode] : uiIntraMode;
+    }
+
+    Int transformSkip = pcCU->getTransformSkip( uiAbsPartIdx,compID) ? 1 : 0;
+    Bool rdpcm_lossy = ( transformSkip && isIntra && ( (uiIntraMode == HOR_IDX) || (uiIntraMode == VER_IDX) ) ) && pcCU->isRDPCMEnabled(uiAbsPartIdx);
+
+    if ( (pcCU->getCUTransquantBypass(uiAbsPartIdx)) || rdpcm_lossy )
+    {
+      beValid = false;
+      if ( (!pcCU->isIntra(uiAbsPartIdx)) && pcCU->isRDPCMEnabled(uiAbsPartIdx))
+      {
+        codeExplicitRdpcmMode( rTu, compID);
+      }
+    }
+    else
+    {
+      beValid = pcCU->getSlice()->getPPS()->getSignHideFlag();
+    }
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
   if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
   {
-    codeTransformSkipFlags( pcCU,uiAbsPartIdx, uiWidth, uiHeight, eTType );
-  }
-  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : ( eTType == TEXT_NONE ? TEXT_NONE : TEXT_CHROMA );
-  
+    codeTransformSkipFlags(rTu, compID);
+    if(pcCU->getTransformSkip(uiAbsPartIdx, compID) && !pcCU->isIntra(uiAbsPartIdx) && pcCU->isRDPCMEnabled(uiAbsPartIdx))
+    {
+      //  This TU has coefficients and is transform skipped. Check whether is inter coded and if yes encode the explicit RDPCM mode
+      codeExplicitRdpcmMode( rTu, compID);
+
+      if(pcCU->getExplicitRdpcmMode(compID, uiAbsPartIdx) != RDPCM_OFF)
+      {
+        //  Sign data hiding is avoided for horizontal and vertical explicit RDPCM modes
+        beValid = false;
+      }
+    }
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  const Bool  bUseGolombRiceParameterAdaptation = sps.getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag();
+        UInt &currentGolombRiceStatistic        = m_golombRiceAdaptationStatistics[rTu.getGolombRiceStatisticsIndex(compID)];
+
+  //select scans
+  TUEntropyCodingParameters codingParameters;
+  getTUEntropyCodingParameters(codingParameters, rTu, compID);
+
   //----- encode significance map -----
-  const UInt   uiLog2BlockSize = g_aucConvertToBit[ uiWidth ] + 2;
-  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
-  const UInt *scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize - 1 ];
-  
-  Bool beValid;
-  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
-  {
-    beValid = false;
-  }
-  else 
-  {
-    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
-  }
 
   // Find position of last coefficient
@@ -1677,67 +1894,58 @@
   Int posLast;
 
-  const UInt * scanCG;
-  {
-    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0 ];
-    if( uiLog2BlockSize == 3 )
-    {
-      scanCG = g_sigLastScan8x8[ uiScanIdx ];
-    }
-    else if( uiLog2BlockSize == 5 )
-    {
-      scanCG = g_sigLastScanCG32x32;
-    }
-  }
+
   UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
-  static const UInt uiShift = MLS_CG_SIZE >> 1;
-  const UInt uiNumBlkSide = uiWidth >> uiShift;
-
-    ::memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
-
-    do
-    {
-      posLast = scan[ ++scanPosLast ];
-
+
+  memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
+  do
+  {
+    posLast = codingParameters.scan[ ++scanPosLast ];
+
+    if( pcCoef[ posLast ] != 0 )
+    {
       // get L1 sig map
-      UInt uiPosY    = posLast >> uiLog2BlockSize;
-      UInt uiPosX    = posLast - ( uiPosY << uiLog2BlockSize );
-      UInt uiBlkIdx  = uiNumBlkSide * (uiPosY >> uiShift) + (uiPosX >> uiShift);
-      if( pcCoef[ posLast ] )
-      {
-        uiSigCoeffGroupFlag[ uiBlkIdx ] = 1;
-      }
-
-      uiNumSig -= ( pcCoef[ posLast ] != 0 );
-    }
-    while ( uiNumSig > 0 );
+      UInt uiPosY   = posLast >> uiLog2BlockWidth;
+      UInt uiPosX   = posLast - ( uiPosY << uiLog2BlockWidth );
+
+      UInt uiBlkIdx = (codingParameters.widthInGroups * (uiPosY >> MLS_CG_LOG2_HEIGHT)) + (uiPosX >> MLS_CG_LOG2_WIDTH);
+      uiSigCoeffGroupFlag[ uiBlkIdx ] = 1;
+
+      uiNumSig--;
+    }
+  } while ( uiNumSig > 0 );
 
   // Code position of last coefficient
-  Int posLastY = posLast >> uiLog2BlockSize;
-  Int posLastX = posLast - ( posLastY << uiLog2BlockSize );
-  codeLastSignificantXY(posLastX, posLastY, uiWidth, uiHeight, eTType, uiScanIdx);
-  
+  Int posLastY = posLast >> uiLog2BlockWidth;
+  Int posLastX = posLast - ( posLastY << uiLog2BlockWidth );
+  codeLastSignificantXY(posLastX, posLastY, uiWidth, uiHeight, compID, codingParameters.scanType);
+
   //===== code significance flag =====
-  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, eTType );
-  ContextModel * const baseCtx = (eTType==TEXT_LUMA) ? m_cCUSigSCModel.get( 0, 0 ) : m_cCUSigSCModel.get( 0, 0 ) + NUM_SIG_FLAG_CTX_LUMA;
-
-
-  const Int  iLastScanSet      = scanPosLast >> LOG2_SCAN_SET_SIZE;
-  UInt c1 = 1;
-  UInt uiGoRiceParam           = 0;
-  Int  iScanPosSig             = scanPosLast;
+  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, chType );
+  ContextModel * const baseCtx = m_cCUSigSCModel.get( 0, 0 ) + getSignificanceMapContextOffset(compID);
+
+  const Int  iLastScanSet  = scanPosLast >> MLS_CG_SIZE;
+
+  UInt c1                  = 1;
+  UInt uiGoRiceParam       = 0;
+  Int  iScanPosSig         = scanPosLast;
 
   for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
   {
     Int numNonZero = 0;
-    Int  iSubPos     = iSubSet << LOG2_SCAN_SET_SIZE;
-    uiGoRiceParam    = 0;
-    Int absCoeff[16];
+    Int  iSubPos   = iSubSet << MLS_CG_SIZE;
+    uiGoRiceParam  = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+    Bool updateGolombRiceStatistics = bUseGolombRiceParameterAdaptation; //leave the statistics at 0 when not using the adaptation system
     UInt coeffSigns = 0;
 
-    Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE;
+    Int absCoeff[1 << MLS_CG_SIZE];
+
+    Int lastNZPosInCG  = -1;
+    Int firstNZPosInCG = 1 << MLS_CG_SIZE;
+
+    Bool escapeDataPresentInGroup = false;
 
     if( iScanPosSig == scanPosLast )
     {
-      absCoeff[ 0 ] = abs( pcCoef[ posLast ] );
+      absCoeff[ 0 ] = Int(abs( pcCoef[ posLast ] ));
       coeffSigns    = ( pcCoef[ posLast ] < 0 );
       numNonZero    = 1;
@@ -1747,65 +1955,62 @@
     }
 
-      // encode significant_coeffgroup_flag
-      Int iCGBlkPos = scanCG[ iSubSet ];
-      Int iCGPosY   = iCGBlkPos / uiNumBlkSide;
-      Int iCGPosX   = iCGBlkPos - (iCGPosY * uiNumBlkSide);
-      if( iSubSet == iLastScanSet || iSubSet == 0)
-      {
-        uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
-      }
-      else
-      {
-          UInt uiSigCoeffGroup   = (uiSigCoeffGroupFlag[ iCGBlkPos ] != 0);
-          UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
-          m_pcBinIf->encodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
-      }
-      
-      // encode significant_coeff_flag
-      if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
-      {
-        Int patternSigCtx = TComTrQuant::calcPatternSigCtx( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
-        UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig;
-        for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+    // encode significant_coeffgroup_flag
+    Int iCGBlkPos = codingParameters.scanCG[ iSubSet ];
+    Int iCGPosY   = iCGBlkPos / codingParameters.widthInGroups;
+    Int iCGPosX   = iCGBlkPos - (iCGPosY * codingParameters.widthInGroups);
+
+    if( iSubSet == iLastScanSet || iSubSet == 0)
+    {
+      uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+    }
+    else
+    {
+      UInt uiSigCoeffGroup   = (uiSigCoeffGroupFlag[ iCGBlkPos ] != 0);
+      UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups );
+      m_pcBinIf->encodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+    }
+
+    // encode significant_coeff_flag
+    if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+    {
+      const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups);
+
+      UInt uiBlkPos, uiSig, uiCtxSig;
+      for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+      {
+        uiBlkPos  = codingParameters.scan[ iScanPosSig ];
+        uiSig     = (pcCoef[ uiBlkPos ] != 0);
+        if( iScanPosSig > iSubPos || iSubSet == 0 || numNonZero )
         {
-          uiBlkPos  = scan[ iScanPosSig ]; 
-          uiPosY    = uiBlkPos >> uiLog2BlockSize;
-          uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
-          uiSig     = (pcCoef[ uiBlkPos ] != 0);
-          if( iScanPosSig > iSubPos || iSubSet == 0 || numNonZero )
+          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, codingParameters, iScanPosSig, uiLog2BlockWidth, uiLog2BlockHeight, chType );
+          m_pcBinIf->encodeBin( uiSig, baseCtx[ uiCtxSig ] );
+        }
+        if( uiSig )
+        {
+          absCoeff[ numNonZero ] = Int(abs( pcCoef[ uiBlkPos ] ));
+          coeffSigns = 2 * coeffSigns + ( pcCoef[ uiBlkPos ] < 0 );
+          numNonZero++;
+          if( lastNZPosInCG == -1 )
           {
-            uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, uiLog2BlockSize, eTType );
-            m_pcBinIf->encodeBin( uiSig, baseCtx[ uiCtxSig ] );
+            lastNZPosInCG = iScanPosSig;
           }
-          if( uiSig )
-          {
-            absCoeff[ numNonZero ] = abs( pcCoef[ uiBlkPos ] );
-            coeffSigns = 2 * coeffSigns + ( pcCoef[ uiBlkPos ] < 0 );
-            numNonZero++;
-            if( lastNZPosInCG == -1 )
-            {
-              lastNZPosInCG = iScanPosSig;
-            }
-            firstNZPosInCG = iScanPosSig;
-          }
+          firstNZPosInCG = iScanPosSig;
         }
       }
-      else
-      {
-        iScanPosSig = iSubPos - 1;
-      }
+    }
+    else
+    {
+      iScanPosSig = iSubPos - 1;
+    }
 
     if( numNonZero > 0 )
     {
       Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD );
-      UInt uiCtxSet = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0;
-      
-      if( c1 == 0 )
-      {
-        uiCtxSet++;
-      }
+
+      const UInt uiCtxSet = getContextSetIndex(compID, iSubSet, (c1 == 0));
       c1 = 1;
-      ContextModel *baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUOneSCModel.get( 0, 0 ) + 4 * uiCtxSet : m_cCUOneSCModel.get( 0, 0 ) + NUM_ONE_FLAG_CTX_LUMA + 4 * uiCtxSet;
-      
+
+      ContextModel *baseCtxMod = m_cCUOneSCModel.get( 0, 0 ) + (NUM_ONE_FLAG_CTX_PER_SET * uiCtxSet);
+
       Int numC1Flag = min(numNonZero, C1FLAG_NUMBER);
       Int firstC2FlagIdx = -1;
@@ -1821,4 +2026,8 @@
           {
             firstC2FlagIdx = idx;
+          }
+          else //if a greater-than-one has been encountered already this group
+          {
+            escapeDataPresentInGroup = true;
           }
         }
@@ -1828,16 +2037,26 @@
         }
       }
-      
+
       if (c1 == 0)
       {
-
-        baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUAbsSCModel.get( 0, 0 ) + uiCtxSet : m_cCUAbsSCModel.get( 0, 0 ) + NUM_ABS_FLAG_CTX_LUMA + uiCtxSet;
+        baseCtxMod = m_cCUAbsSCModel.get( 0, 0 ) + (NUM_ABS_FLAG_CTX_PER_SET * uiCtxSet);
         if ( firstC2FlagIdx != -1)
         {
           UInt symbol = absCoeff[ firstC2FlagIdx ] > 2;
           m_pcBinIf->encodeBin( symbol, baseCtxMod[0] );
+          if (symbol != 0)
+          {
+            escapeDataPresentInGroup = true;
+          }
         }
       }
-      
+
+      escapeDataPresentInGroup = escapeDataPresentInGroup || (numNonZero > C1FLAG_NUMBER);
+
+      if (escapeDataPresentInGroup && alignCABACBeforeBypass)
+      {
+        m_pcBinIf->align();
+      }
+
       if( beValid && signHidden )
       {
@@ -1848,7 +2067,7 @@
         m_pcBinIf->encodeBinsEP( coeffSigns, numNonZero );
       }
-      
-      Int iFirstCoeff2 = 1;    
-      if (c1 == 0 || numNonZero > C1FLAG_NUMBER)
+
+      Int iFirstCoeff2 = 1;
+      if (escapeDataPresentInGroup)
       {
         for ( Int idx = 0; idx < numNonZero; idx++ )
@@ -1858,18 +2077,41 @@
           if( absCoeff[ idx ] >= baseLevel)
           {
-            xWriteCoefRemainExGolomb( absCoeff[ idx ] - baseLevel, uiGoRiceParam );
-            if(absCoeff[idx] > 3*(1<<uiGoRiceParam))
+            const UInt escapeCodeValue = absCoeff[idx] - baseLevel;
+
+            xWriteCoefRemainExGolomb( escapeCodeValue, uiGoRiceParam, extendedPrecision, maxLog2TrDynamicRange );
+
+            if (absCoeff[idx] > (3 << uiGoRiceParam))
             {
-               uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+              uiGoRiceParam = bUseGolombRiceParameterAdaptation ? (uiGoRiceParam + 1) : (std::min<UInt>((uiGoRiceParam + 1), 4));
+            }
+
+            if (updateGolombRiceStatistics)
+            {
+              const UInt initialGolombRiceParameter = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+
+              if (escapeCodeValue >= (3 << initialGolombRiceParameter))
+              {
+                currentGolombRiceStatistic++;
+              }
+              else if (((escapeCodeValue * 2) < (1 << initialGolombRiceParameter)) && (currentGolombRiceStatistic > 0))
+              {
+                currentGolombRiceStatistic--;
+              }
+
+              updateGolombRiceStatistics = false;
             }
           }
-          if(absCoeff[ idx ] >= 2)  
+
+          if(absCoeff[ idx ] >= 2)
           {
             iFirstCoeff2 = 0;
           }
-        }        
-      }
-    }
-  }
+        }
+      }
+    }
+  }
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  printSBACCoeffData(posLastX, posLastY, uiWidth, uiHeight, compID, uiAbsPartIdx, codingParameters.scanType, pcCoef, pcCU->getSlice()->getFinalized());
+#endif
 
   return;
@@ -1912,30 +2154,19 @@
 }
 
-
-/** Code SAO EO class or BO band position 
- * \param uiLength
- * \param uiCode
+/** Code SAO EO class or BO band position
  */
 Void TEncSbac::codeSaoUflc       ( UInt uiLength, UInt uiCode )
 {
-   m_pcBinIf->encodeBinsEP ( uiCode, uiLength );
-}
+  m_pcBinIf->encodeBinsEP ( uiCode, uiLength );
+}
+
 /** Code SAO merge flags
- * \param uiCode
- * \param uiCompIdx
  */
 Void TEncSbac::codeSaoMerge       ( UInt uiCode )
 {
-  if (uiCode == 0)
-  {
-    m_pcBinIf->encodeBin(0,  m_cSaoMergeSCModel.get( 0, 0, 0 ));
-  }
-  else
-  {
-    m_pcBinIf->encodeBin(1,  m_cSaoMergeSCModel.get( 0, 0, 0 ));
-  }
-}
-/** Code SAO type index 
- * \param uiCode
+  m_pcBinIf->encodeBin(((uiCode == 0) ? 0 : 1),  m_cSaoMergeSCModel.get( 0, 0, 0 ));
+}
+
+/** Code SAO type index
  */
 Void TEncSbac::codeSaoTypeIdx       ( UInt uiCode)
@@ -1951,4 +2182,120 @@
   }
 }
+
+Void TEncSbac::codeSAOOffsetParam(ComponentID compIdx, SAOOffset& ctbParam, Bool sliceEnabled, const Int channelBitDepth)
+{
+  UInt uiSymbol;
+  if(!sliceEnabled)
+  {
+    assert(ctbParam.modeIdc == SAO_MODE_OFF);
+    return;
+  }
+  const Bool bIsFirstCompOfChType = (getFirstComponentOfChannel(toChannelType(compIdx)) == compIdx);
+
+  //type
+  if(bIsFirstCompOfChType)
+  {
+    //sao_type_idx_luma or sao_type_idx_chroma
+    if(ctbParam.modeIdc == SAO_MODE_OFF)
+    {
+      uiSymbol =0;
+    }
+    else if(ctbParam.typeIdc == SAO_TYPE_BO) //BO
+    {
+      uiSymbol = 1;
+    }
+    else
+    {
+      assert(ctbParam.typeIdc < SAO_TYPE_START_BO); //EO
+      uiSymbol = 2;
+    }
+    codeSaoTypeIdx(uiSymbol);
+  }
+
+  if(ctbParam.modeIdc == SAO_MODE_NEW)
+  {
+    Int numClasses = (ctbParam.typeIdc == SAO_TYPE_BO)?4:NUM_SAO_EO_CLASSES;
+    Int offset[4];
+    Int k=0;
+    for(Int i=0; i< numClasses; i++)
+    {
+      if(ctbParam.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN)
+      {
+        continue;
+      }
+      Int classIdx = (ctbParam.typeIdc == SAO_TYPE_BO)?(  (ctbParam.typeAuxInfo+i)% NUM_SAO_BO_CLASSES   ):i;
+      offset[k] = ctbParam.offset[classIdx];
+      k++;
+    }
+
+    const Int  maxOffsetQVal = TComSampleAdaptiveOffset::getMaxOffsetQVal(channelBitDepth);
+    for(Int i=0; i< 4; i++)
+    {
+      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  maxOffsetQVal ); //sao_offset_abs
+    }
+
+
+    if(ctbParam.typeIdc == SAO_TYPE_BO)
+    {
+      for(Int i=0; i< 4; i++)
+      {
+        if(offset[i] != 0)
+        {
+          codeSAOSign((offset[i]< 0)?1:0);
+        }
+      }
+
+      codeSaoUflc(NUM_SAO_BO_CLASSES_LOG2, ctbParam.typeAuxInfo ); //sao_band_position
+    }
+    else //EO
+    {
+      if(bIsFirstCompOfChType)
+      {
+        assert(ctbParam.typeIdc - SAO_TYPE_START_EO >=0);
+        codeSaoUflc(NUM_SAO_EO_TYPES_LOG2, ctbParam.typeIdc - SAO_TYPE_START_EO ); //sao_eo_class_luma or sao_eo_class_chroma
+      }
+    }
+
+  }
+}
+
+
+Void TEncSbac::codeSAOBlkParam(SAOBlkParam& saoBlkParam, const BitDepths &bitDepths
+                              , Bool* sliceEnabled
+                              , Bool leftMergeAvail
+                              , Bool aboveMergeAvail
+                              , Bool onlyEstMergeInfo // = false
+                              )
+{
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    isLeftMerge = ((saoBlkParam[COMPONENT_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[COMPONENT_Y].typeIdc == SAO_MERGE_LEFT));
+    codeSaoMerge( isLeftMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    isAboveMerge = ((saoBlkParam[COMPONENT_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[COMPONENT_Y].typeIdc == SAO_MERGE_ABOVE));
+    codeSaoMerge( isAboveMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if(onlyEstMergeInfo)
+  {
+    return; //only for RDO
+  }
+
+  if(!isLeftMerge && !isAboveMerge) //not merge mode
+  {
+    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+    {
+      codeSAOOffsetParam(ComponentID(compIdx), saoBlkParam[compIdx], sliceEnabled[compIdx], bitDepths.recon[toChannelType(ComponentID(compIdx))]);
+    }
+  }
+}
+
 /*!
  ****************************************************************************
@@ -1957,15 +2304,20 @@
  ****************************************************************************
  */
-Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType )
+Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
 {
   estCBFBit( pcEstBitsSbac );
 
-  estSignificantCoeffGroupMapBit( pcEstBitsSbac, eTType );
-  
+  estSignificantCoeffGroupMapBit( pcEstBitsSbac, chType );
+
   // encode significance map
-  estSignificantMapBit( pcEstBitsSbac, width, height, eTType );
-  
+  estSignificantMapBit( pcEstBitsSbac, width, height, chType );
+
+  // encode last significant position
+  estLastSignificantPositionBit( pcEstBitsSbac, width, height, chType );
+
   // encode significant coefficients
-  estSignificantCoefficientsBit( pcEstBitsSbac, eTType );
+  estSignificantCoefficientsBit( pcEstBitsSbac, chType );
+
+  memcpy(pcEstBitsSbac->golombRiceAdaptationStatistics, m_golombRiceAdaptationStatistics, (sizeof(UInt) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS));
 }
 
@@ -1980,5 +2332,5 @@
   ContextModel *pCtx = m_cCUQtCbfSCModel.get( 0 );
 
-  for( UInt uiCtxInc = 0; uiCtxInc < 3*NUM_QT_CBF_CTX; uiCtxInc++ )
+  for( UInt uiCtxInc = 0; uiCtxInc < (NUM_QT_CBF_CTX_SETS * NUM_QT_CBF_CTX_PER_SET); uiCtxInc++ )
   {
     pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
@@ -1987,5 +2339,5 @@
 
   pCtx = m_cCUQtRootCbfSCModel.get( 0 );
-  
+
   for( UInt uiCtxInc = 0; uiCtxInc < 4; uiCtxInc++ )
   {
@@ -2002,5 +2354,5 @@
  ****************************************************************************
  */
-Void TEncSbac::estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, TextType eTType )
+Void TEncSbac::estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType )
 {
   Int firstCtx = 0, numCtx = NUM_SIG_CG_FLAG_CTX;
@@ -2010,5 +2362,5 @@
     for( UInt uiBin = 0; uiBin < 2; uiBin++ )
     {
-      pcEstBitsSbac->significantCoeffGroupBits[ ctxIdx ][ uiBin ] = m_cCUSigCoeffGroupSCModel.get(  0, eTType, ctxIdx ).getEntropyBits( uiBin );
+      pcEstBitsSbac->significantCoeffGroupBits[ ctxIdx ][ uiBin ] = m_cCUSigCoeffGroupSCModel.get(  0, chType, ctxIdx ).getEntropyBits( uiBin );
     }
   }
@@ -2022,23 +2374,56 @@
  ****************************************************************************
  */
-Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType )
-{
-  Int firstCtx = 1, numCtx = 8;
-  if (max(width, height) >= 16)
-  {
-    firstCtx = (eTType == TEXT_LUMA) ? 21 : 12;
-    numCtx = (eTType == TEXT_LUMA) ? 6 : 3;
-  }
-  else if (width == 8)
-  {
-    firstCtx = 9;
-    numCtx = (eTType == TEXT_LUMA) ? 12 : 3;
-  }
-  
-  if (eTType == TEXT_LUMA )
-  {
+Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
+{
+  //--------------------------------------------------------------------------------------------------
+
+  //set up the number of channels and context variables
+
+  const UInt firstComponent = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
+  const UInt lastComponent  = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
+
+  //----------------------------------------------------------
+
+  Int firstCtx = MAX_INT;
+  Int numCtx   = MAX_INT;
+
+  if      ((width == 4) && (height == 4))
+  {
+    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_4x4];
+    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_4x4];
+  }
+  else if ((width == 8) && (height == 8))
+  {
+    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_8x8];
+    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_8x8];
+  }
+  else
+  {
+    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_NxN];
+    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_NxN];
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  //fill the data for the significace map
+
+  for (UInt component = firstComponent; component <= lastComponent; component++)
+  {
+    const UInt contextOffset = getSignificanceMapContextOffset(ComponentID(component));
+
+    if (firstCtx > 0)
+    {
+      for( UInt bin = 0; bin < 2; bin++ ) //always get the DC
+      {
+        pcEstBitsSbac->significantBits[ contextOffset ][ bin ] = m_cCUSigSCModel.get( 0, 0, contextOffset ).getEntropyBits( bin );
+      }
+    }
+
+    // This could be made optional, but would require this function to have knowledge of whether the
+    // TU is transform-skipped or transquant-bypassed and whether the SPS flag is set
     for( UInt bin = 0; bin < 2; bin++ )
     {
-      pcEstBitsSbac->significantBits[ 0 ][ bin ] = m_cCUSigSCModel.get(  0, 0, 0 ).getEntropyBits( bin );
+      const Int ctxIdx = significanceMapContextSetStart[chType][CONTEXT_TYPE_SINGLE];
+      pcEstBitsSbac->significantBits[ contextOffset + ctxIdx ][ bin ] = m_cCUSigSCModel.get( 0, 0, (contextOffset + ctxIdx) ).getEntropyBits( bin );
     }
 
@@ -2047,48 +2432,12 @@
       for( UInt uiBin = 0; uiBin < 2; uiBin++ )
       {
-        pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, ctxIdx ).getEntropyBits( uiBin );
-      }
-    }
-  }
-  else
-  {
-    for( UInt bin = 0; bin < 2; bin++ )
-    {
-      pcEstBitsSbac->significantBits[ 0 ][ bin ] = m_cCUSigSCModel.get(  0, 0, NUM_SIG_FLAG_CTX_LUMA + 0 ).getEntropyBits( bin );
-    }
-    for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
-    {
-      for( UInt uiBin = 0; uiBin < 2; uiBin++ )
-      {
-        pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, NUM_SIG_FLAG_CTX_LUMA + ctxIdx ).getEntropyBits( uiBin );
-      }
-    }
-  }
-  Int iBitsX = 0, iBitsY = 0;
-  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
-
-  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
-  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
-  shiftX = eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
-  shiftY = eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
-
-  Int ctx;
-  ContextModel *pCtxX      = m_cCuCtxLastX.get( 0, eTType );
-  for (ctx = 0; ctx < g_uiGroupIdx[ width - 1 ]; ctx++)
-  {
-    Int ctxOffset = blkSizeOffsetX + (ctx >>shiftX);
-    pcEstBitsSbac->lastXBits[ ctx ] = iBitsX + pCtxX[ ctxOffset ].getEntropyBits( 0 );
-    iBitsX += pCtxX[ ctxOffset ].getEntropyBits( 1 );
-  }
-  pcEstBitsSbac->lastXBits[ctx] = iBitsX;
-  ContextModel *pCtxY      = m_cCuCtxLastY.get( 0, eTType );
-  for (ctx = 0; ctx < g_uiGroupIdx[ height - 1 ]; ctx++)
-  {
-    Int ctxOffset = blkSizeOffsetY + (ctx >>shiftY);
-    pcEstBitsSbac->lastYBits[ ctx ] = iBitsY + pCtxY[ ctxOffset ].getEntropyBits( 0 );
-    iBitsY += pCtxY[ ctxOffset ].getEntropyBits( 1 );
-  }
-  pcEstBitsSbac->lastYBits[ctx] = iBitsY;
-}
+        pcEstBitsSbac->significantBits[ contextOffset + ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, (contextOffset + ctxIdx) ).getEntropyBits( uiBin );
+      }
+    }
+  }
+
+  //--------------------------------------------------------------------------------------------------
+}
+
 
 /*!
@@ -2098,39 +2447,94 @@
  ****************************************************************************
  */
-Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, TextType eTType )
-{
-  if (eTType==TEXT_LUMA)
-  {
-    ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0);
-    ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0);
-
-    for (Int ctxIdx = 0; ctxIdx < NUM_ONE_FLAG_CTX_LUMA; ctxIdx++)
-    {
-      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
-      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );    
-    }
-
-    for (Int ctxIdx = 0; ctxIdx < NUM_ABS_FLAG_CTX_LUMA; ctxIdx++)
-    {
-      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 );
-      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 );    
-    }
-  }
-  else
-  {
-    ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0) + NUM_ONE_FLAG_CTX_LUMA;
-    ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0) + NUM_ABS_FLAG_CTX_LUMA;
-
-    for (Int ctxIdx = 0; ctxIdx < NUM_ONE_FLAG_CTX_CHROMA; ctxIdx++)
-    {
-      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
-      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );    
-    }
-
-    for (Int ctxIdx = 0; ctxIdx < NUM_ABS_FLAG_CTX_CHROMA; ctxIdx++)
-    {
-      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 );
-      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 );    
-    }
+
+Void TEncSbac::estLastSignificantPositionBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
+{
+  //--------------------------------------------------------------------------------------------------.
+
+  //set up the number of channels
+
+  const UInt firstComponent = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
+  const UInt lastComponent  = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
+
+  //--------------------------------------------------------------------------------------------------
+
+  //fill the data for the last-significant-coefficient position
+
+  for (UInt componentIndex = firstComponent; componentIndex <= lastComponent; componentIndex++)
+  {
+    const ComponentID component = ComponentID(componentIndex);
+
+    Int iBitsX = 0, iBitsY = 0;
+
+    Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+    getLastSignificantContextParameters(ComponentID(component), width, height, blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY);
+
+    Int ctx;
+
+    const ChannelType channelType = toChannelType(ComponentID(component));
+
+    ContextModel *const pCtxX = m_cCuCtxLastX.get( 0, channelType );
+    ContextModel *const pCtxY = m_cCuCtxLastY.get( 0, channelType );
+    Int          *const lastXBitsArray = pcEstBitsSbac->lastXBits[channelType];
+    Int          *const lastYBitsArray = pcEstBitsSbac->lastYBits[channelType];
+
+    //------------------------------------------------
+
+    //X-coordinate
+
+    for (ctx = 0; ctx < g_uiGroupIdx[ width - 1 ]; ctx++)
+    {
+      Int ctxOffset = blkSizeOffsetX + (ctx >>shiftX);
+      lastXBitsArray[ ctx ] = iBitsX + pCtxX[ ctxOffset ].getEntropyBits( 0 );
+      iBitsX += pCtxX[ ctxOffset ].getEntropyBits( 1 );
+    }
+
+    lastXBitsArray[ctx] = iBitsX;
+
+    //------------------------------------------------
+
+    //Y-coordinate
+
+    for (ctx = 0; ctx < g_uiGroupIdx[ height - 1 ]; ctx++)
+    {
+      Int ctxOffset = blkSizeOffsetY + (ctx >>shiftY);
+      lastYBitsArray[ ctx ] = iBitsY + pCtxY[ ctxOffset ].getEntropyBits( 0 );
+      iBitsY += pCtxY[ ctxOffset ].getEntropyBits( 1 );
+    }
+
+    lastYBitsArray[ctx] = iBitsY;
+
+  } //end of component loop
+
+  //--------------------------------------------------------------------------------------------------
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost of significant coefficient
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType )
+{
+  ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0);
+  ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0);
+
+  const UInt oneStartIndex = ((isLuma(chType)) ? (0)                     : (NUM_ONE_FLAG_CTX_LUMA));
+  const UInt oneStopIndex  = ((isLuma(chType)) ? (NUM_ONE_FLAG_CTX_LUMA) : (NUM_ONE_FLAG_CTX));
+  const UInt absStartIndex = ((isLuma(chType)) ? (0)                     : (NUM_ABS_FLAG_CTX_LUMA));
+  const UInt absStopIndex  = ((isLuma(chType)) ? (NUM_ABS_FLAG_CTX_LUMA) : (NUM_ABS_FLAG_CTX));
+
+  for (Int ctxIdx = oneStartIndex; ctxIdx < oneStopIndex; ctxIdx++)
+  {
+    pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
+    pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );
+  }
+
+  for (Int ctxIdx = absStartIndex; ctxIdx < absStopIndex; ctxIdx++)
+  {
+    pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 );
+    pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 );
   }
 }
@@ -2141,124 +2545,51 @@
  \param pSrc From where to copy context information.
  */
-Void TEncSbac::xCopyContextsFrom( TEncSbac* pSrc )
-{  
+Void TEncSbac::xCopyContextsFrom( const TEncSbac* pSrc )
+{
   memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
-}
-
-Void  TEncSbac::loadContexts ( TEncSbac* pScr)
-{
-  this->xCopyContextsFrom(pScr);
-}
-
-Void TEncSbac::codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled)
-{
-  UInt uiSymbol;
-  if(!sliceEnabled)
-  {
-    assert(ctbParam.modeIdc == SAO_MODE_OFF);
-    return;
-  }
-
-  //type
-  if(compIdx == SAO_Y || compIdx == SAO_Cb)
-  {
-    //sao_type_idx_luma or sao_type_idx_chroma
-    if(ctbParam.modeIdc == SAO_MODE_OFF)
-    {
-      uiSymbol =0;
-    }
-    else if(ctbParam.typeIdc == SAO_TYPE_BO) //BO
-    {
-      uiSymbol = 1;
+  memcpy(m_golombRiceAdaptationStatistics, pSrc->m_golombRiceAdaptationStatistics, (sizeof(UInt) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS));
+}
+
+Void  TEncSbac::loadContexts ( const TEncSbac* pSrc)
+{
+  xCopyContextsFrom(pSrc);
+}
+
+/** Performs CABAC encoding of the explicit RDPCM mode
+ * \param rTu current TU data structure
+ * \param compID component identifier
+ */
+Void TEncSbac::codeExplicitRdpcmMode( TComTU &rTu, const ComponentID compID )
+{
+  TComDataCU *cu = rTu.getCU();
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt absPartIdx   = rTu.GetAbsPartIdxTU(compID);
+  const UInt tuHeight = g_aucConvertToBit[rect.height];
+  const UInt tuWidth  = g_aucConvertToBit[rect.width];
+
+  assert(tuHeight == tuWidth);
+  assert(tuHeight < 4);
+
+  UInt explicitRdpcmMode = cu->getExplicitRdpcmMode(compID, absPartIdx);
+
+  if( explicitRdpcmMode == RDPCM_OFF )
+  {
+    m_pcBinIf->encodeBin (0, m_explicitRdpcmFlagSCModel.get (0, toChannelType(compID), 0));
+  }
+  else if( explicitRdpcmMode == RDPCM_HOR || explicitRdpcmMode == RDPCM_VER )
+  {
+    m_pcBinIf->encodeBin (1, m_explicitRdpcmFlagSCModel.get (0, toChannelType(compID), 0));
+    if(explicitRdpcmMode == RDPCM_HOR)
+    {
+      m_pcBinIf->encodeBin ( 0, m_explicitRdpcmDirSCModel.get(0, toChannelType(compID), 0));
     }
     else
     {
-      assert(ctbParam.typeIdc < SAO_TYPE_START_BO); //EO
-      uiSymbol = 2;
-    }
-    codeSaoTypeIdx(uiSymbol); 
-  }
-
-  if(ctbParam.modeIdc == SAO_MODE_NEW)
-  {
-    Int numClasses = (ctbParam.typeIdc == SAO_TYPE_BO)?4:NUM_SAO_EO_CLASSES; 
-    Int offset[4];
-    Int k=0;
-    for(Int i=0; i< numClasses; i++)
-    {
-      if(ctbParam.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN)
-      {
-        continue;
-      }
-      Int classIdx = (ctbParam.typeIdc == SAO_TYPE_BO)?(  (ctbParam.typeAuxInfo+i)% NUM_SAO_BO_CLASSES   ):i;
-      offset[k] = ctbParam.offset[classIdx];
-      k++;
-    }
-
-    for(Int i=0; i< 4; i++)
-    {
-      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
-    }
-
-
-    if(ctbParam.typeIdc == SAO_TYPE_BO)
-    {
-      for(Int i=0; i< 4; i++)
-      {
-        if(offset[i] != 0)
-        {
-          codeSAOSign((offset[i]< 0)?1:0);
-        }
-      }
-
-      codeSaoUflc(NUM_SAO_BO_CLASSES_LOG2, ctbParam.typeAuxInfo ); //sao_band_position
-    }
-    else //EO
-    {
-      if(compIdx == SAO_Y || compIdx == SAO_Cb)
-      {
-        assert(ctbParam.typeIdc - SAO_TYPE_START_EO >=0);
-        codeSaoUflc(NUM_SAO_EO_TYPES_LOG2, ctbParam.typeIdc - SAO_TYPE_START_EO ); //sao_eo_class_luma or sao_eo_class_chroma
-      }
-    }
-
-  }
-}
-
-
-Void TEncSbac::codeSAOBlkParam(SAOBlkParam& saoBlkParam
-                              , Bool* sliceEnabled
-                              , Bool leftMergeAvail
-                              , Bool aboveMergeAvail
-                              , Bool onlyEstMergeInfo // = false
-                              )
-{
-
-  Bool isLeftMerge = false;
-  Bool isAboveMerge= false;
-
-  if(leftMergeAvail)
-  {
-    isLeftMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_LEFT));
-    codeSaoMerge( isLeftMerge?1:0  ); //sao_merge_left_flag
-  }
-
-  if( aboveMergeAvail && !isLeftMerge)
-  {
-    isAboveMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_ABOVE)); 
-    codeSaoMerge( isAboveMerge?1:0  ); //sao_merge_left_flag
-  }
-
-  if(onlyEstMergeInfo)
-  {
-    return; //only for RDO
-  }
-
-  if(!isLeftMerge && !isAboveMerge) //not merge mode
-  {
-    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
-    {
-      codeSAOOffsetParam(compIdx, saoBlkParam[compIdx], sliceEnabled[compIdx]);
-    }
+      m_pcBinIf->encodeBin ( 1, m_explicitRdpcmDirSCModel.get(0, toChannelType(compID), 0));
+    }
+  }
+  else
+  {
+    assert(0);
   }
 }
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSbac.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSbac.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -69,44 +69,39 @@
   TEncSbac();
   virtual ~TEncSbac();
-  
+
   Void  init                   ( TEncBinIf* p )  { m_pcBinIf = p; }
   Void  uninit                 ()                { m_pcBinIf = 0; }
 
   //  Virtual list
-  Void  resetEntropy           ();
-  Void  determineCabacInitIdx  ();
+  Void  resetEntropy           (const TComSlice *pSlice);
+  SliceType determineCabacInitIdx  (const TComSlice *pSlice);
   Void  setBitstream           ( TComBitIf* p )  { m_pcBitIf = p; m_pcBinIf->init( p ); }
-  Void  setSlice               ( TComSlice* p )  { m_pcSlice = p;                       }
-  // SBAC RD
-  Void  resetCoeffCost         ()                { m_uiCoeffCost = 0;  }
-  UInt  getCoeffCost           ()                { return  m_uiCoeffCost;  }
-  
-  Void  load                   ( TEncSbac* pScr  );
-  Void  loadIntraDirModeLuma   ( TEncSbac* pScr  );
+
+  Void  load                   ( const TEncSbac* pSrc  );
+  Void  loadIntraDirMode       ( const TEncSbac* pScr, const ChannelType chType  );
 #if H_3D_DIM
   Void  loadIntraDepthMode     ( TEncSbac* pScr  );
 #endif
-  Void  store                  ( TEncSbac* pDest );
-  Void  loadContexts           ( TEncSbac* pScr  );
+  Void  store                  ( TEncSbac* pDest ) const;
+  Void  loadContexts           ( const TEncSbac* pSrc  );
   Void  resetBits              ()                { m_pcBinIf->resetBits(); m_pcBitIf->resetBits(); }
   UInt  getNumberOfWrittenBits ()                { return m_pcBinIf->getNumWrittenBits(); }
   //--SBAC RD
 
-  Void  codeVPS                 ( TComVPS* pcVPS );
-  Void  codeSPS                 ( TComSPS* pcSPS     );
-  Void  codePPS                 ( TComPPS* pcPPS     );
-  Void  codeSliceHeader         ( TComSlice* pcSlice );
-  Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
-  Void  codeTerminatingBit      ( UInt uilsLast      );
-  Void  codeSliceFinish         ();
-  Void  codeSaoMaxUvlc    ( UInt code, UInt maxSymbol );
-  Void  codeSaoMerge  ( UInt  uiCode );
-  Void  codeSaoTypeIdx    ( UInt  uiCode);
-  Void  codeSaoUflc       ( UInt uiLength, UInt  uiCode );
-  Void  codeSAOSign       ( UInt  uiCode);  //<! code SAO offset sign
-  Void  codeScalingList      ( TComScalingList* /*scalingList*/     ){ assert (0);  return;};
-
-  Void codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled);
-  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
+  Void  codeVPS                ( const TComVPS* pcVPS );
+  Void  codeSPS                ( const TComSPS* pcSPS     );
+  Void  codePPS                ( const TComPPS* pcPPS     );
+  Void  codeSliceHeader        ( TComSlice* pcSlice );
+  Void  codeTilesWPPEntryPoint ( TComSlice* pSlice );
+  Void  codeTerminatingBit     ( UInt uilsLast      );
+  Void  codeSliceFinish        ();
+  Void  codeSaoMaxUvlc       ( UInt code, UInt maxSymbol );
+  Void  codeSaoMerge         ( UInt  uiCode );
+  Void  codeSaoTypeIdx       ( UInt  uiCode);
+  Void  codeSaoUflc          ( UInt uiLength, UInt  uiCode );
+  Void  codeSAOSign          ( UInt  uiCode);  //<! code SAO offset sign
+
+  Void codeSAOOffsetParam(ComponentID compIdx, SAOOffset& ctbParam, Bool sliceEnabled, const Int channelBitDepth);
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, const BitDepths &bitDepths
                     , Bool* sliceEnabled
                     , Bool leftMergeAvail
@@ -119,5 +114,5 @@
   Void  xWriteUnaryMaxSymbol ( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol );
   Void  xWriteEpExGolomb     ( UInt uiSymbol, UInt uiCount );
-  Void  xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam );
+  Void  xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange );
 #if H_3D_DIM
   Void  xWriteExGolombLevel  ( UInt uiSymbol, ContextModel& rcSCModel  );
@@ -127,20 +122,14 @@
 #endif
 #endif
-  
-  Void  xCopyFrom            ( TEncSbac* pSrc );
-  Void  xCopyContextsFrom    ( TEncSbac* pSrc );  
-  
-  Void codeDFFlag( UInt /*uiCode*/, const Char* /*pSymbolName*/ )       {printf("Not supported in codeDFFlag()\n"); assert(0); exit(1);};
-  Void codeDFSvlc( Int /*iCode*/, const Char* /*pSymbolName*/ )         {printf("Not supported in codeDFSvlc()\n"); assert(0); exit(1);};
+
+  Void  xCopyFrom            ( const TEncSbac* pSrc );
+  Void  xCopyContextsFrom    ( const TEncSbac* pSrc );
 
 protected:
   TComBitIf*    m_pcBitIf;
-  TComSlice*    m_pcSlice;
   TEncBinIf*    m_pcBinIf;
-  //SBAC RD
-  UInt          m_uiCoeffCost;
 
   //--Adaptive loop filter
-  
+
 public:
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
@@ -166,15 +155,15 @@
   Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void codeMVPIdx        ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
-  
+
   Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeTransformSubdivFlag ( UInt uiSymbol, UInt uiCtx );
-  Void codeQtCbf               ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtCbf               ( TComTU & rTu, const ComponentID compID, const Bool lowestLevel );
   Void codeQtRootCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-  Void codeQtCbfZero           ( TComDataCU* pcCU, TextType eType, UInt uiTrDepth );
-  Void codeQtRootCbfZero       ( TComDataCU* pcCU );
+  Void codeQtCbfZero           ( TComTU &rTu, const ChannelType chType );
+  Void codeQtRootCbfZero       ( );
   Void codeIntraDirLumaAng     ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple);
-  
+
   Void codeIntraDirChroma      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 
@@ -187,28 +176,30 @@
   Void codeRefFrmIdx           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
   Void codeMvd                 ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
-  
+
+  Void codeCrossComponentPrediction( TComTU &rTu, ComponentID compID );
+
   Void codeDeltaQP             ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-  
-  Void codeLastSignificantXY ( UInt uiPosX, UInt uiPosY, Int width, Int height, TextType eTType, UInt uiScanIdx );
-  Void codeCoeffNxN            ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
-  void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType );
+  Void codeChromaQpAdjustment  ( TComDataCU* cu, UInt absPartIdx );
+
+  Void codeLastSignificantXY ( UInt uiPosX, UInt uiPosY, Int width, Int height, ComponentID component, UInt uiScanIdx );
+  Void codeCoeffNxN            ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID );
+  Void codeTransformSkipFlags ( TComTU &rTu, ComponentID component );
 
   // -------------------------------------------------------------------------------------------------------------------
   // for RD-optimizatioon
   // -------------------------------------------------------------------------------------------------------------------
-  
-  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType);
   Void estCBFBit                     ( estBitsSbacStruct* pcEstBitsSbac );
-  Void estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, TextType eTType );
-  Void estSignificantMapBit          ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType );
-  Void estSignificantCoefficientsBit ( estBitsSbacStruct* pcEstBitsSbac, TextType eTType );
-  
-  Void updateContextTables           ( SliceType eSliceType, Int iQp, Bool bExecuteFinish=true  );
-  Void updateContextTables           ( SliceType eSliceType, Int iQp  ) { this->updateContextTables( eSliceType, iQp, true); };
-  
+  Void estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType );
+  Void estSignificantMapBit          ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+  Void estLastSignificantPositionBit ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+  Void estSignificantCoefficientsBit ( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType );
+
+  Void codeExplicitRdpcmMode            ( TComTU &rTu, const ComponentID compID );
+
+
   TEncBinIf* getEncBinIf()  { return m_pcBinIf; }
 private:
-  UInt                 m_uiLastQp;
-  
   ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
   Int                  m_numContextModels;
@@ -238,5 +229,5 @@
   ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
   ContextModel3DBuffer m_cCUQtRootCbfSCModel;
-  
+
   ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
   ContextModel3DBuffer m_cCUSigSCModel;
@@ -245,12 +236,17 @@
   ContextModel3DBuffer m_cCUOneSCModel;
   ContextModel3DBuffer m_cCUAbsSCModel;
-  
+
   ContextModel3DBuffer m_cMVPIdxSCModel;
-  
+
   ContextModel3DBuffer m_cSaoMergeSCModel;
   ContextModel3DBuffer m_cSaoTypeIdxSCModel;
   ContextModel3DBuffer m_cTransformSkipSCModel;
   ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
-
+  ContextModel3DBuffer m_explicitRdpcmFlagSCModel;
+  ContextModel3DBuffer m_explicitRdpcmDirSCModel;
+  ContextModel3DBuffer m_cCrossComponentPredictionSCModel;
+
+  ContextModel3DBuffer m_ChromaQpAdjFlagSCModel;
+  ContextModel3DBuffer m_ChromaQpAdjIdcSCModel;
 #if H_3D_DIM
   ContextModel3DBuffer m_cDepthIntraModeSCModel;
@@ -269,4 +265,6 @@
   ContextModel3DBuffer m_cDBBPFlagSCModel;
 #endif
+
+  UInt m_golombRiceAdaptationStatistics[RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS];
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,12 +36,16 @@
  */
 
-#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/CommonDef.h"
 #include "TLibCommon/TComRom.h"
 #include "TLibCommon/TComMotionInfo.h"
 #include "TEncSearch.h"
+#include "TLibCommon/TComTU.h"
+#include "TLibCommon/Debug.h"
 #include <math.h>
+#include <limits>
 #if H_3D_INTER_SDC
 #include <memory.h>
 #endif
+
 
 //! \ingroup TLibEncoder
@@ -81,40 +85,63 @@
 };
 
+static Void offsetSubTUCBFs(TComTU &rTu, const ComponentID compID)
+{
+        TComDataCU *pcCU              = rTu.getCU();
+  const UInt        uiTrDepth         = rTu.GetTransformDepthRel();
+  const UInt        uiAbsPartIdx      = rTu.GetAbsPartIdxTU(compID);
+  const UInt        partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
+
+  //move the CBFs down a level and set the parent CBF
+
+  UChar subTUCBF[2];
+  UChar combinedSubTUCBF = 0;
+
+  for (UInt subTU = 0; subTU < 2; subTU++)
+  {
+    const UInt subTUAbsPartIdx = uiAbsPartIdx + (subTU * partIdxesPerSubTU);
+
+    subTUCBF[subTU]   = pcCU->getCbf(subTUAbsPartIdx, compID, uiTrDepth);
+    combinedSubTUCBF |= subTUCBF[subTU];
+  }
+
+  for (UInt subTU = 0; subTU < 2; subTU++)
+  {
+    const UInt subTUAbsPartIdx = uiAbsPartIdx + (subTU * partIdxesPerSubTU);
+    const UChar compositeCBF = (subTUCBF[subTU] << 1) | combinedSubTUCBF;
+
+    pcCU->setCbfPartRange((compositeCBF << uiTrDepth), compID, subTUAbsPartIdx, partIdxesPerSubTU);
+  }
+}
+
+
 TEncSearch::TEncSearch()
 {
-  m_ppcQTTempCoeffY  = NULL;
-  m_ppcQTTempCoeffCb = NULL;
-  m_ppcQTTempCoeffCr = NULL;
-  m_pcQTTempCoeffY   = NULL;
-  m_pcQTTempCoeffCb  = NULL;
-  m_pcQTTempCoeffCr  = NULL;
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    m_ppcQTTempCoeff[ch]                           = NULL;
+    m_pcQTTempCoeff[ch]                            = NULL;
 #if ADAPTIVE_QP_SELECTION
-  m_ppcQTTempArlCoeffY  = NULL;
-  m_ppcQTTempArlCoeffCb = NULL;
-  m_ppcQTTempArlCoeffCr = NULL;
-  m_pcQTTempArlCoeffY   = NULL;
-  m_pcQTTempArlCoeffCb  = NULL;
-  m_pcQTTempArlCoeffCr  = NULL;
-#endif
-  m_puhQTTempTrIdx   = NULL;
-  m_puhQTTempCbf[0] = m_puhQTTempCbf[1] = m_puhQTTempCbf[2] = NULL;
-  m_pcQTTempTComYuv  = NULL;
-  m_pcEncCfg = NULL;
-  m_pcEntropyCoder = NULL;
-  m_pTempPel = NULL;
-  m_pSharedPredTransformSkip[0] = m_pSharedPredTransformSkip[1] = m_pSharedPredTransformSkip[2] = NULL;
-  m_pcQTTempTUCoeffY   = NULL;
-  m_pcQTTempTUCoeffCb  = NULL;
-  m_pcQTTempTUCoeffCr  = NULL;
+    m_ppcQTTempArlCoeff[ch]                        = NULL;
+    m_pcQTTempArlCoeff[ch]                         = NULL;
+#endif
+    m_puhQTTempCbf[ch]                             = NULL;
+    m_phQTTempCrossComponentPredictionAlpha[ch]    = NULL;
+    m_pSharedPredTransformSkip[ch]                 = NULL;
+    m_pcQTTempTUCoeff[ch]                          = NULL;
 #if ADAPTIVE_QP_SELECTION
-  m_ppcQTTempTUArlCoeffY  = NULL;
-  m_ppcQTTempTUArlCoeffCb = NULL;
-  m_ppcQTTempTUArlCoeffCr = NULL;
-#endif
-  m_puhQTTempTransformSkipFlag[0] = NULL;
-  m_puhQTTempTransformSkipFlag[1] = NULL;
-  m_puhQTTempTransformSkipFlag[2] = NULL;
+    m_ppcQTTempTUArlCoeff[ch]                      = NULL;
+#endif
+    m_puhQTTempTransformSkipFlag[ch]               = NULL;
+  }
+  m_puhQTTempTrIdx                                 = NULL;
+  m_pcQTTempTComYuv                                = NULL;
+  m_pcEncCfg                                       = NULL;
+  m_pcEntropyCoder                                 = NULL;
+  m_pTempPel                                       = NULL;
   setWpScalingDistParam( NULL, -1, REF_PIC_LIST_X );
 }
+
+
+
 
 TEncSearch::~TEncSearch()
@@ -125,64 +152,62 @@
     m_pTempPel = NULL;
   }
-  
+
   if ( m_pcEncCfg )
   {
     const UInt uiNumLayersAllocated = m_pcEncCfg->getQuadtreeTULog2MaxSize()-m_pcEncCfg->getQuadtreeTULog2MinSize()+1;
-    for( UInt ui = 0; ui < uiNumLayersAllocated; ++ui )
-    {
-      delete[] m_ppcQTTempCoeffY[ui];
-      delete[] m_ppcQTTempCoeffCb[ui];
-      delete[] m_ppcQTTempCoeffCr[ui];
+
+    for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+    {
+      for (UInt layer = 0; layer < uiNumLayersAllocated; layer++)
+      {
+        delete[] m_ppcQTTempCoeff[ch][layer];
 #if ADAPTIVE_QP_SELECTION
-      delete[] m_ppcQTTempArlCoeffY[ui];
-      delete[] m_ppcQTTempArlCoeffCb[ui];
-      delete[] m_ppcQTTempArlCoeffCr[ui];
-#endif
-      m_pcQTTempTComYuv[ui].destroy();
-    }
-  }
-  delete[] m_ppcQTTempCoeffY;
-  delete[] m_ppcQTTempCoeffCb;
-  delete[] m_ppcQTTempCoeffCr;
-  delete[] m_pcQTTempCoeffY;
-  delete[] m_pcQTTempCoeffCb;
-  delete[] m_pcQTTempCoeffCr;
+        delete[] m_ppcQTTempArlCoeff[ch][layer];
+#endif
+      }
+      delete[] m_ppcQTTempCoeff[ch];
+      delete[] m_pcQTTempCoeff[ch];
+      delete[] m_puhQTTempCbf[ch];
 #if ADAPTIVE_QP_SELECTION
-  delete[] m_ppcQTTempArlCoeffY;
-  delete[] m_ppcQTTempArlCoeffCb;
-  delete[] m_ppcQTTempArlCoeffCr;
-  delete[] m_pcQTTempArlCoeffY;
-  delete[] m_pcQTTempArlCoeffCb;
-  delete[] m_pcQTTempArlCoeffCr;
-#endif
+      delete[] m_ppcQTTempArlCoeff[ch];
+      delete[] m_pcQTTempArlCoeff[ch];
+#endif
+    }
+
+    for( UInt layer = 0; layer < uiNumLayersAllocated; layer++ )
+    {
+      m_pcQTTempTComYuv[layer].destroy();
+    }
+  }
+
   delete[] m_puhQTTempTrIdx;
-  delete[] m_puhQTTempCbf[0];
-  delete[] m_puhQTTempCbf[1];
-  delete[] m_puhQTTempCbf[2];
   delete[] m_pcQTTempTComYuv;
-  delete[] m_pSharedPredTransformSkip[0];
-  delete[] m_pSharedPredTransformSkip[1];
-  delete[] m_pSharedPredTransformSkip[2];
-  delete[] m_pcQTTempTUCoeffY;
-  delete[] m_pcQTTempTUCoeffCb;
-  delete[] m_pcQTTempTUCoeffCr;
+
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    delete[] m_pSharedPredTransformSkip[ch];
+    delete[] m_pcQTTempTUCoeff[ch];
 #if ADAPTIVE_QP_SELECTION
-  delete[] m_ppcQTTempTUArlCoeffY;
-  delete[] m_ppcQTTempTUArlCoeffCb;
-  delete[] m_ppcQTTempTUArlCoeffCr;
-#endif
-  delete[] m_puhQTTempTransformSkipFlag[0];
-  delete[] m_puhQTTempTransformSkipFlag[1];
-  delete[] m_puhQTTempTransformSkipFlag[2];
+    delete[] m_ppcQTTempTUArlCoeff[ch];
+#endif
+    delete[] m_phQTTempCrossComponentPredictionAlpha[ch];
+    delete[] m_puhQTTempTransformSkipFlag[ch];
+  }
   m_pcQTTempTransformSkipTComYuv.destroy();
+
   m_tmpYuvPred.destroy();
 }
 
-void TEncSearch::init(TEncCfg*      pcEncCfg,
+
+
+
+Void TEncSearch::init(TEncCfg*      pcEncCfg,
                       TComTrQuant*  pcTrQuant,
                       Int           iSearchRange,
                       Int           bipredSearchRange,
                       Int           iFastSearch,
-                      Int           iMaxDeltaQP,
+                      const UInt    maxCUWidth,
+                      const UInt    maxCUHeight,
+                      const UInt    maxTotalCUDepth,
                       TEncEntropy*  pcEntropyCoder,
                       TComRdCost*   pcRdCost,
@@ -196,26 +221,21 @@
   m_bipredSearchRange    = bipredSearchRange;
   m_iFastSearch          = iFastSearch;
-  m_iMaxDeltaQP          = iMaxDeltaQP;
   m_pcEntropyCoder       = pcEntropyCoder;
   m_pcRdCost             = pcRdCost;
-  
+
   m_pppcRDSbacCoder     = pppcRDSbacCoder;
   m_pcRDGoOnSbacCoder   = pcRDGoOnSbacCoder;
-  
-  for (Int iDir = 0; iDir < 2; iDir++)
-  {
-    for (Int iRefIdx = 0; iRefIdx < 33; iRefIdx++)
+
+  for (UInt iDir = 0; iDir < MAX_NUM_REF_LIST_ADAPT_SR; iDir++)
+  {
+    for (UInt iRefIdx = 0; iRefIdx < MAX_IDX_ADAPT_SR; iRefIdx++)
     {
       m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange;
     }
   }
-  
+
   m_puiDFilter = s_auiDFilter + 4;
-  
+
   // initialize motion cost
-#if !FIX203
-  m_pcRdCost->initRateDistortionModel( m_iSearchRange << 2 );
-#endif
-  
   for( Int iNum = 0; iNum < AMVP_MAX_NUM_CANDS+1; iNum++)
   {
@@ -223,72 +243,58 @@
     {
       if (iIdx < iNum)
+      {
         m_auiMVPIdxCost[iIdx][iNum] = xGetMvpIdxBits(iIdx, iNum);
+      }
       else
+      {
         m_auiMVPIdxCost[iIdx][iNum] = MAX_INT;
-    }
-  }
-  
-  initTempBuff();
-  
-  m_pTempPel = new Pel[g_uiMaxCUWidth*g_uiMaxCUHeight];
-  
+      }
+    }
+  }
+
+  const ChromaFormat cform=pcEncCfg->getChromaFormatIdc();
+  initTempBuff(cform);
+
+  m_pTempPel = new Pel[maxCUWidth*maxCUHeight];
+
   const UInt uiNumLayersToAllocate = pcEncCfg->getQuadtreeTULog2MaxSize()-pcEncCfg->getQuadtreeTULog2MinSize()+1;
-  m_ppcQTTempCoeffY  = new TCoeff*[uiNumLayersToAllocate];
-  m_ppcQTTempCoeffCb = new TCoeff*[uiNumLayersToAllocate];
-  m_ppcQTTempCoeffCr = new TCoeff*[uiNumLayersToAllocate];
-  m_pcQTTempCoeffY   = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight   ];
-  m_pcQTTempCoeffCb  = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
-  m_pcQTTempCoeffCr  = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+  const UInt uiNumPartitions = 1<<(maxTotalCUDepth<<1);
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    const UInt csx=::getComponentScaleX(ComponentID(ch), cform);
+    const UInt csy=::getComponentScaleY(ComponentID(ch), cform);
+    m_ppcQTTempCoeff[ch] = new TCoeff* [uiNumLayersToAllocate];
+    m_pcQTTempCoeff[ch]   = new TCoeff [(maxCUWidth*maxCUHeight)>>(csx+csy)   ];
 #if ADAPTIVE_QP_SELECTION
-  m_ppcQTTempArlCoeffY  = new Int*[uiNumLayersToAllocate];
-  m_ppcQTTempArlCoeffCb = new Int*[uiNumLayersToAllocate];
-  m_ppcQTTempArlCoeffCr = new Int*[uiNumLayersToAllocate];
-  m_pcQTTempArlCoeffY   = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight   ];
-  m_pcQTTempArlCoeffCb  = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
-  m_pcQTTempArlCoeffCr  = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
-#endif
-  
-  const UInt uiNumPartitions = 1<<(g_uiMaxCUDepth<<1);
+    m_ppcQTTempArlCoeff[ch]  = new TCoeff*[uiNumLayersToAllocate];
+    m_pcQTTempArlCoeff[ch]   = new TCoeff [(maxCUWidth*maxCUHeight)>>(csx+csy)   ];
+#endif
+    m_puhQTTempCbf[ch] = new UChar  [uiNumPartitions];
+
+    for (UInt layer = 0; layer < uiNumLayersToAllocate; layer++)
+    {
+      m_ppcQTTempCoeff[ch][layer] = new TCoeff[(maxCUWidth*maxCUHeight)>>(csx+csy)];
+#if ADAPTIVE_QP_SELECTION
+      m_ppcQTTempArlCoeff[ch][layer]  = new TCoeff[(maxCUWidth*maxCUHeight)>>(csx+csy) ];
+#endif
+    }
+
+    m_phQTTempCrossComponentPredictionAlpha[ch]    = new Char  [uiNumPartitions];
+    m_pSharedPredTransformSkip[ch]                 = new Pel   [MAX_CU_SIZE*MAX_CU_SIZE];
+    m_pcQTTempTUCoeff[ch]                          = new TCoeff[MAX_CU_SIZE*MAX_CU_SIZE];
+#if ADAPTIVE_QP_SELECTION
+    m_ppcQTTempTUArlCoeff[ch]                      = new TCoeff[MAX_CU_SIZE*MAX_CU_SIZE];
+#endif
+    m_puhQTTempTransformSkipFlag[ch]               = new UChar [uiNumPartitions];
+  }
   m_puhQTTempTrIdx   = new UChar  [uiNumPartitions];
-  m_puhQTTempCbf[0]  = new UChar  [uiNumPartitions];
-  m_puhQTTempCbf[1]  = new UChar  [uiNumPartitions];
-  m_puhQTTempCbf[2]  = new UChar  [uiNumPartitions];
   m_pcQTTempTComYuv  = new TComYuv[uiNumLayersToAllocate];
   for( UInt ui = 0; ui < uiNumLayersToAllocate; ++ui )
   {
-    m_ppcQTTempCoeffY[ui]  = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight   ];
-    m_ppcQTTempCoeffCb[ui] = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
-    m_ppcQTTempCoeffCr[ui] = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
-#if ADAPTIVE_QP_SELECTION
-    m_ppcQTTempArlCoeffY[ui]  = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight   ];
-    m_ppcQTTempArlCoeffCb[ui] = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
-    m_ppcQTTempArlCoeffCr[ui] = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
-#endif
-    m_pcQTTempTComYuv[ui].create( g_uiMaxCUWidth, g_uiMaxCUHeight );
-  }
-  m_pSharedPredTransformSkip[0] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-  m_pSharedPredTransformSkip[1] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-  m_pSharedPredTransformSkip[2] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-  m_pcQTTempTUCoeffY  = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-  m_pcQTTempTUCoeffCb = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-  m_pcQTTempTUCoeffCr = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-#if ADAPTIVE_QP_SELECTION
-  m_ppcQTTempTUArlCoeffY  = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-  m_ppcQTTempTUArlCoeffCb = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-  m_ppcQTTempTUArlCoeffCr = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
-#endif
-  m_pcQTTempTransformSkipTComYuv.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
-
-  m_puhQTTempTransformSkipFlag[0] = new UChar  [uiNumPartitions];
-  m_puhQTTempTransformSkipFlag[1] = new UChar  [uiNumPartitions];
-  m_puhQTTempTransformSkipFlag[2] = new UChar  [uiNumPartitions];
-  m_tmpYuvPred.create(MAX_CU_SIZE, MAX_CU_SIZE);
+    m_pcQTTempTComYuv[ui].create( maxCUWidth, maxCUHeight, pcEncCfg->getChromaFormatIdc() );
+  }
+  m_pcQTTempTransformSkipTComYuv.create( maxCUWidth, maxCUHeight, pcEncCfg->getChromaFormatIdc() );
+  m_tmpYuvPred.create(MAX_CU_SIZE, MAX_CU_SIZE, pcEncCfg->getChromaFormatIdc());
 }
-
-#if FASTME_SMOOTHER_MV
-#define FIRSTSEARCHSTOP     1
-#else
-#define FIRSTSEARCHSTOP     0
-#endif
 
 #define TZ_SEARCH_CONFIGURATION                                                                                 \
@@ -299,5 +305,5 @@
 const Bool bTestZeroVectorStop      = 0;                                                                      \
 const Bool bFirstSearchDiamond      = 1;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
-const Bool bFirstSearchStop         = FIRSTSEARCHSTOP;                                                        \
+const Bool bFirstSearchStop         = m_pcEncCfg->getFastMEAssumingSmootherMVEnabled();                       \
 const UInt uiFirstSearchRounds      = 3;  /* first search stop X rounds after best match (must be >=1) */     \
 const Bool bEnableRasterSearch      = 1;                                                                      \
@@ -311,10 +317,26 @@
 
 
+#define SEL_SEARCH_CONFIGURATION                                                                                 \
+  const Bool bTestOtherPredictedMV    = 1;                                                                       \
+  const Bool bTestZeroVector          = 1;                                                                       \
+  const Bool bEnableRasterSearch      = 1;                                                                       \
+  const Bool bAlwaysRasterSearch      = 0;  /* ===== 1: BETTER but factor 15x slower ===== */                    \
+  const Bool bStarRefinementEnable    = 1;  /* enable either star refinement or raster refinement */             \
+  const Bool bStarRefinementDiamond   = 1;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */         \
+  const Bool bStarRefinementStop      = 0;                                                                       \
+  const UInt uiStarRefinementRounds   = 2;  /* star refinement stop X rounds after best match (must be >=1) */   \
+  const UInt uiSearchRange            = m_iSearchRange;                                                          \
+  const Int  uiSearchRangeInitial     = m_iSearchRange >> 2;                                                     \
+  const Int  uiSearchStep             = 4;                                                                       \
+  const Int  iMVDistThresh            = 8;                                                                       \
+
+
+
 __inline Void TEncSearch::xTZSearchHelp( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance )
 {
-  UInt  uiSad;
-  
+  Distortion  uiSad = 0;
+
   Pel*  piRefSrch;
-  
+
   piRefSrch = rcStruct.piRefY + iSearchY * rcStruct.iYStride + iSearchX;
 #if H_3D_IC
@@ -326,33 +348,99 @@
   //-- jclee for using the SAD function pointer
   m_pcRdCost->setDistParam( pcPatternKey, piRefSrch, rcStruct.iYStride,  m_cDistParam );
-  
-  // fast encoder decision: use subsampled SAD when rows > 8 for integer ME
-  if ( m_pcEncCfg->getUseFastEnc() )
-  {
-    if ( m_cDistParam.iRows > 8 )
+
+  if(m_pcEncCfg->getFastSearch() != SELECTIVE)
+  {
+    // fast encoder decision: use subsampled SAD when rows > 8 for integer ME
+    if ( m_pcEncCfg->getUseFastEnc() )
+    {
+      if ( m_cDistParam.iRows > 8 )
+      {
+        m_cDistParam.iSubShift = 1;
+      }
+    }
+  }
+
+  setDistParamComp(COMPONENT_Y);
+
+  // distortion
+  m_cDistParam.bitDepth = pcPatternKey->getBitDepthY();
+  if(m_pcEncCfg->getFastSearch() == SELECTIVE)
+  {
+    Int isubShift = 0;
+    // motion cost
+    Distortion uiBitCost = m_pcRdCost->getCost( iSearchX, iSearchY );
+
+    if ( m_cDistParam.iRows > 32 )
+    {
+      m_cDistParam.iSubShift = 4;
+    }
+    else if ( m_cDistParam.iRows > 16 )
+    {
+      m_cDistParam.iSubShift = 3;
+    }
+    else if ( m_cDistParam.iRows > 8 )
+    {
+      m_cDistParam.iSubShift = 2;
+    }
+    else
     {
       m_cDistParam.iSubShift = 1;
     }
-  }
-
-  setDistParamComp(0);  // Y component
-
-  // distortion
-  m_cDistParam.bitDepth = g_bitDepthY;
-  uiSad = m_cDistParam.DistFunc( &m_cDistParam );
-  
-  // motion cost
-  uiSad += m_pcRdCost->getCost( iSearchX, iSearchY );
-  
-  if( uiSad < rcStruct.uiBestSad )
-  {
-    rcStruct.uiBestSad      = uiSad;
-    rcStruct.iBestX         = iSearchX;
-    rcStruct.iBestY         = iSearchY;
-    rcStruct.uiBestDistance = uiDistance;
-    rcStruct.uiBestRound    = 0;
-    rcStruct.ucPointNr      = ucPointNr;
+
+    Distortion uiTempSad = m_cDistParam.DistFunc( &m_cDistParam );
+    if((uiTempSad + uiBitCost) < rcStruct.uiBestSad)
+    {
+      uiSad += uiTempSad >>  m_cDistParam.iSubShift;
+      while(m_cDistParam.iSubShift > 0)
+      {
+        isubShift         = m_cDistParam.iSubShift -1;
+        m_cDistParam.pOrg = pcPatternKey->getROIY() + (pcPatternKey->getPatternLStride() << isubShift);
+        m_cDistParam.pCur = piRefSrch + (rcStruct.iYStride << isubShift);
+        uiTempSad = m_cDistParam.DistFunc( &m_cDistParam );
+        uiSad += uiTempSad >>  m_cDistParam.iSubShift;
+        if(((uiSad << isubShift) + uiBitCost) > rcStruct.uiBestSad)
+        {
+          break;
+        }
+
+        m_cDistParam.iSubShift--;
+      }
+
+      if(m_cDistParam.iSubShift == 0)
+      {
+        uiSad += uiBitCost;
+        if( uiSad < rcStruct.uiBestSad )
+        {
+          rcStruct.uiBestSad      = uiSad;
+          rcStruct.iBestX         = iSearchX;
+          rcStruct.iBestY         = iSearchY;
+          rcStruct.uiBestDistance = uiDistance;
+          rcStruct.uiBestRound    = 0;
+          rcStruct.ucPointNr      = ucPointNr;
+        }
+      }
+    }
+  }
+  else
+  {
+    uiSad = m_cDistParam.DistFunc( &m_cDistParam );
+
+    // motion cost
+    uiSad += m_pcRdCost->getCost( iSearchX, iSearchY );
+
+    if( uiSad < rcStruct.uiBestSad )
+    {
+      rcStruct.uiBestSad      = uiSad;
+      rcStruct.iBestX         = iSearchX;
+      rcStruct.iBestY         = iSearchY;
+      rcStruct.uiBestDistance = uiDistance;
+      rcStruct.uiBestRound    = 0;
+      rcStruct.ucPointNr      = ucPointNr;
+    }
   }
 }
+
+
+
 
 __inline Void TEncSearch::xTZ2PointSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB )
@@ -362,5 +450,5 @@
   Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
   Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
-  
+
   // 2 point search,                   //   1 2 3
   // check only the 2 untested points  //   4 0 5
@@ -486,4 +574,7 @@
 }
 
+
+
+
 __inline Void TEncSearch::xTZ8PointSquareSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
 {
@@ -492,5 +583,5 @@
   Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
   Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
-  
+
   // 8 point search,                   //   1 2 3
   // search around the start point     //   4 0 5
@@ -502,5 +593,5 @@
   const Int iRight      = iStartX + iDist;
   rcStruct.uiBestRound += 1;
-  
+
   if ( iTop >= iSrchRngVerTop ) // check top
   {
@@ -511,5 +602,5 @@
     // top middle
     xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
-    
+
     if ( iRight <= iSrchRngHorRight ) // check top right
     {
@@ -533,5 +624,5 @@
     // check bottom middle
     xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
-    
+
     if ( iRight <= iSrchRngHorRight ) // check bottom right
     {
@@ -540,4 +631,7 @@
   } // check bottom
 }
+
+
+
 
 __inline Void TEncSearch::xTZ8PointDiamondSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
@@ -547,5 +641,5 @@
   Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
   Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
-  
+
   // 8 point search,                   //   1 2 3
   // search around the start point     //   4 0 5
@@ -557,5 +651,5 @@
   const Int iRight      = iStartX + iDist;
   rcStruct.uiBestRound += 1;
-  
+
   if ( iDist == 1 ) // iDist == 1
   {
@@ -585,5 +679,5 @@
       const Int iLeft_2     = iStartX - (iDist>>1);
       const Int iRight_2    = iStartX + (iDist>>1);
-      
+
       if (  iTop >= iSrchRngVerTop && iLeft >= iSrchRngHorLeft &&
           iRight <= iSrchRngHorRight && iBottom <= iSrchRngVerBottom ) // check border
@@ -685,5 +779,5 @@
           Int iPosXL = iStartX - ((iDist>>2) * index);
           Int iPosXR = iStartX + ((iDist>>2) * index);
-          
+
           if ( iPosYT >= iSrchRngVerTop ) // check top
           {
@@ -714,28 +808,35 @@
 }
 
+
+
+
+
 //<--
 
-UInt TEncSearch::xPatternRefinement( TComPattern* pcPatternKey,
-                                    TComMv baseRefMv,
-                                    Int iFrac, TComMv& rcMvFrac )
+Distortion TEncSearch::xPatternRefinement( TComPattern* pcPatternKey,
+                                           TComMv baseRefMv,
+                                           Int iFrac, TComMv& rcMvFrac,
+                                           Bool bAllowUseOfHadamard
+                                         )
 {
-  UInt  uiDist;
-  UInt  uiDistBest  = MAX_UINT;
-  UInt  uiDirecBest = 0;
-  
+  Distortion  uiDist;
+  Distortion  uiDistBest  = std::numeric_limits<Distortion>::max();
+  UInt        uiDirecBest = 0;
+
   Pel*  piRefPos;
-  Int iRefStride = m_filteredBlock[0][0].getStride();
-  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
-  
+  Int iRefStride = m_filteredBlock[0][0].getStride(COMPONENT_Y);
+
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getAddr(COMPONENT_Y), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() && bAllowUseOfHadamard );
+
   const TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
-  
+
   for (UInt i = 0; i < 9; i++)
   {
     TComMv cMvTest = pcMvRefine[i];
     cMvTest += baseRefMv;
-    
+
     Int horVal = cMvTest.getHor() * iFrac;
     Int verVal = cMvTest.getVer() * iFrac;
-    piRefPos = m_filteredBlock[ verVal & 3 ][ horVal & 3 ].getLumaAddr();
+    piRefPos = m_filteredBlock[ verVal & 3 ][ horVal & 3 ].getAddr(COMPONENT_Y);
     if ( horVal == 2 && ( verVal & 1 ) == 0 )
     {
@@ -749,5 +850,5 @@
     cMvTest += rcMvFrac;
 
-    setDistParamComp(0);  // Y component
+    setDistParamComp(COMPONENT_Y);
 #if H_3D_IC
     m_cDistParam.bUseIC = pcPatternKey->getICFlag();
@@ -756,9 +857,10 @@
     m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
 #endif
+
     m_cDistParam.pCur = piRefPos;
-    m_cDistParam.bitDepth = g_bitDepthY;
+    m_cDistParam.bitDepth = pcPatternKey->getBitDepthY();
     uiDist = m_cDistParam.DistFunc( &m_cDistParam );
     uiDist += m_pcRdCost->getCost( cMvTest.getHor(), cMvTest.getVer() );
-    
+
     if ( uiDist < uiDistBest )
     {
@@ -767,131 +869,121 @@
     }
   }
-  
+
   rcMvFrac = pcMvRefine[uiDirecBest];
-  
+
   return uiDistBest;
 }
 
+
+
 Void
-TEncSearch::xEncSubdivCbfQT( TComDataCU*  pcCU,
-                            UInt         uiTrDepth,
-                            UInt         uiAbsPartIdx,
+TEncSearch::xEncSubdivCbfQT(TComTU      &rTu,
                             Bool         bLuma,
                             Bool         bChroma )
 {
-  UInt  uiFullDepth     = pcCU->getDepth(0) + uiTrDepth;
-  UInt  uiTrMode        = pcCU->getTransformIdx( uiAbsPartIdx );
-  UInt  uiSubdiv        = ( uiTrMode > uiTrDepth ? 1 : 0 );
-  UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
-
-    if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
-    {
-      assert( uiSubdiv );
-    }
-    else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
-    {
-      assert( uiSubdiv );
-    }
-    else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
-    {
-      assert( !uiSubdiv );
-    }
-    else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-    {
-      assert( !uiSubdiv );
-    }
-    else
-    {
-      assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
-      if( bLuma )
-      {
-        m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
-      }
-    }
-  
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx         = rTu.GetAbsPartIdxTU();
+  const UInt uiTrDepth            = rTu.GetTransformDepthRel();
+  const UInt uiTrMode             = pcCU->getTransformIdx( uiAbsPartIdx );
+  const UInt uiSubdiv             = ( uiTrMode > uiTrDepth ? 1 : 0 );
+  const UInt uiLog2LumaTrafoSize  = rTu.GetLog2LumaTrSize();
+
+  if( pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2LumaTrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2LumaTrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    assert( !uiSubdiv );
+  }
+  else if( uiLog2LumaTrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    assert( !uiSubdiv );
+  }
+  else
+  {
+    assert( uiLog2LumaTrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2LumaTrafoSize );
+    }
+  }
+
   if ( bChroma )
   {
-    if( uiLog2TrafoSize > 2 )
-    {
-      if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth-1 ) )
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
-      }
-      if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth-1 ) )
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
-    }
-  }
+    const UInt numberValidComponents = getNumberValidComponents(rTu.GetChromaFormat());
+    for (UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+      if( rTu.ProcessingAllQuadrants(compID) && (uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepth-1 ) ))
+      {
+        m_pcEntropyCoder->encodeQtCbf(rTu, compID, (uiSubdiv == 0));
+      }
+    }
   }
 
   if( uiSubdiv )
   {
-    UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
-    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
-    {
-      xEncSubdivCbfQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiQPartNum, bLuma, bChroma );
-    }
-    return;
-  }
-  
+    TComTURecurse tuRecurse(rTu, false);
+    do
+    {
+      xEncSubdivCbfQT( tuRecurse, bLuma, bChroma );
+    } while (tuRecurse.nextSection(rTu));
+  }
+  else
+  {
     //===== Cbfs =====
     if( bLuma )
     {
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    }
-  }
+      m_pcEntropyCoder->encodeQtCbf( rTu, COMPONENT_Y, true );
+    }
+  }
+}
+
+
+
 
 Void
-TEncSearch::xEncCoeffQT( TComDataCU*  pcCU,
-                        UInt         uiTrDepth,
-                        UInt         uiAbsPartIdx,
-                        TextType     eTextType,
+TEncSearch::xEncCoeffQT(TComTU &rTu,
+                        const ComponentID  component,
                         Bool         bRealCoeff )
 {
-  UInt  uiFullDepth     = pcCU->getDepth(0) + uiTrDepth;
-  UInt  uiTrMode        = pcCU->getTransformIdx( uiAbsPartIdx );
-  UInt  uiSubdiv        = ( uiTrMode > uiTrDepth ? 1 : 0 );
-  UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
-  UInt  uiChroma        = ( eTextType != TEXT_LUMA ? 1 : 0 );
-  
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrDepth=rTu.GetTransformDepthRel();
+
+  const UInt  uiTrMode        = pcCU->getTransformIdx( uiAbsPartIdx );
+  const UInt  uiSubdiv        = ( uiTrMode > uiTrDepth ? 1 : 0 );
+
   if( uiSubdiv )
   {
-    UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
-      for( UInt uiPart = 0; uiPart < 4; uiPart++ )
-      {
-        xEncCoeffQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiQPartNum, eTextType, bRealCoeff );
-      }
-    return;
-  }
-  
-  if( eTextType != TEXT_LUMA && uiLog2TrafoSize == 2 )
-  {
-    assert( uiTrDepth > 0 );
-    uiTrDepth--;
-    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
-    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
-    if( !bFirstQ )
-    {
-      return;
-    }
-  }
-  
-  //===== coefficients =====
-  UInt    uiWidth         = pcCU->getWidth  ( 0 ) >> ( uiTrDepth + uiChroma );
-  UInt    uiHeight        = pcCU->getHeight ( 0 ) >> ( uiTrDepth + uiChroma );
-  UInt    uiCoeffOffset   = ( pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight() * uiAbsPartIdx ) >> ( uiChroma << 1 );
-  UInt    uiQTLayer       = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrafoSize;
-  TCoeff* pcCoeff         = 0;
-  switch( eTextType )
-  {
-    case TEXT_LUMA:     pcCoeff = ( bRealCoeff ? pcCU->getCoeffY () : m_ppcQTTempCoeffY [uiQTLayer] );  break;
-    case TEXT_CHROMA_U: pcCoeff = ( bRealCoeff ? pcCU->getCoeffCb() : m_ppcQTTempCoeffCb[uiQTLayer] );  break;
-    case TEXT_CHROMA_V: pcCoeff = ( bRealCoeff ? pcCU->getCoeffCr() : m_ppcQTTempCoeffCr[uiQTLayer] );  break;
-    default:            assert(0);
-  }
-  pcCoeff += uiCoeffOffset;
-  
-  m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeff, uiAbsPartIdx, uiWidth, uiHeight, uiFullDepth, eTextType );
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xEncCoeffQT( tuRecurseChild, component, bRealCoeff );
+    } while (tuRecurseChild.nextSection(rTu) );
+  }
+  else if (rTu.ProcessComponentSection(component))
+  {
+    //===== coefficients =====
+    const UInt  uiLog2TrafoSize = rTu.GetLog2LumaTrSize();
+    UInt    uiCoeffOffset   = rTu.getCoefficientOffset(component);
+    UInt    uiQTLayer       = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrafoSize;
+    TCoeff* pcCoeff         = bRealCoeff ? pcCU->getCoeff(component) : m_ppcQTTempCoeff[component][uiQTLayer];
+
+    if (isChroma(component) && (pcCU->getCbf( rTu.GetAbsPartIdxTU(), COMPONENT_Y, uiTrMode ) != 0) && pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag() )
+    {
+      m_pcEntropyCoder->encodeCrossComponentPrediction( rTu, component );
+    }
+
+    m_pcEntropyCoder->encodeCoeffNxN( rTu, pcCoeff+uiCoeffOffset, component );
+  }
 }
+
+
 
 
@@ -919,5 +1011,5 @@
         if(!pcCU->getDISFlag(uiAbsPartIdx))
 #endif
-          m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+        m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
       }
 #if H_3D
@@ -931,31 +1023,32 @@
       {
 #endif
-        m_pcEntropyCoder  ->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
-
-        if (pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_2Nx2N )
-        {
-          m_pcEntropyCoder->encodeIPCMInfo( pcCU, 0, true );
-          if ( pcCU->getIPCMFlag (0))
-          {
+      m_pcEntropyCoder  ->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+
+      if (pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+      {
+        m_pcEntropyCoder->encodeIPCMInfo( pcCU, 0, true );
+
+        if ( pcCU->getIPCMFlag (0))
+        {
 #if H_3D_DIM_SDC
             m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
 #endif
-            return;
-          }
-        }
+          return;
+        }
+      }
 #if H_3D
-      }
-#endif
-    }
+    }
+#endif
+  }
 #if H_3D
     if(!pcCU->getDISFlag(uiAbsPartIdx))
     {
 #endif
-      // luma prediction mode
-      if( pcCU->getPartitionSize(0) == SIZE_2Nx2N )
-      {
-        if( uiAbsPartIdx == 0 )
-        {
-          m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, 0 );
+    // luma prediction mode
+    if( pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+    {
+      if (uiAbsPartIdx==0)
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, 0 );
 #if H_3D_DIM_SDC
           m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
@@ -965,15 +1058,12 @@
           }
 #endif
-        }
-      }
-      else
-      {
-        UInt uiQNumParts = pcCU->getTotalNumPart() >> 2;
-        if( uiTrDepth == 0 )
-        {
-          assert( uiAbsPartIdx == 0 );
-          for( UInt uiPart = 0; uiPart < 4; uiPart++ )
-          {
-            m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPart * uiQNumParts );
+      }
+    }
+    else
+    {
+      UInt uiQNumParts = pcCU->getTotalNumPart() >> 2;
+      if (uiTrDepth>0 && (uiAbsPartIdx%uiQNumParts)==0)
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
 #if H_3D_DIM_SDC
           }
@@ -986,9 +1076,4 @@
             }
 #endif
-          }
-        }
-        else if( ( uiAbsPartIdx % uiQNumParts ) == 0 )
-        {
-          m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
 #if H_3D_DIM_SDC
           if( uiAbsPartIdx == 0 )  
@@ -1001,16 +1086,28 @@
           }
 #endif
-        }
 #if H_3D
       }
 #endif
-    }
-  }
+      }
+    }
+  }
+
   if( bChroma )
   {
-    // chroma prediction mode
-    if( uiAbsPartIdx == 0 )
-    {
-      m_pcEntropyCoder->encodeIntraDirModeChroma( pcCU, 0, true );
+    if( pcCU->getPartitionSize(0) == SIZE_2Nx2N || !enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()))
+    {
+      if(uiAbsPartIdx==0)
+      {
+         m_pcEntropyCoder->encodeIntraDirModeChroma ( pcCU, uiAbsPartIdx );
+      }
+    }
+    else
+    {
+      UInt uiQNumParts = pcCU->getTotalNumPart() >> 2;
+      assert(uiTrDepth>0);
+      if ((uiAbsPartIdx%uiQNumParts)==0)
+      {
+        m_pcEntropyCoder->encodeIntraDirModeChroma ( pcCU, uiAbsPartIdx );
+      }
     }
   }
@@ -1018,99 +1115,132 @@
 
 
+
+
 UInt
-TEncSearch::xGetIntraBitsQT( TComDataCU*  pcCU,
-                            UInt         uiTrDepth,
-                            UInt         uiAbsPartIdx,
+TEncSearch::xGetIntraBitsQT(TComTU &rTu,
                             Bool         bLuma,
                             Bool         bChroma,
                             Bool         bRealCoeff /* just for test */ )
 {
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrDepth=rTu.GetTransformDepthRel();
   m_pcEntropyCoder->resetBits();
   xEncIntraHeader ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
-  xEncSubdivCbfQT ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
-  
+  xEncSubdivCbfQT ( rTu, bLuma, bChroma );
+
   if( bLuma )
   {
-    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_LUMA,      bRealCoeff );
+    xEncCoeffQT   ( rTu, COMPONENT_Y,      bRealCoeff );
   }
   if( bChroma )
   {
-    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_U,  bRealCoeff );
-    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_V,  bRealCoeff );
-  }
+    xEncCoeffQT   ( rTu, COMPONENT_Cb,  bRealCoeff );
+    xEncCoeffQT   ( rTu, COMPONENT_Cr,  bRealCoeff );
+  }
+  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+  return uiBits;
+}
+
+UInt TEncSearch::xGetIntraBitsQTChroma(TComTU &rTu,
+                                       ComponentID compID,
+                                       Bool         bRealCoeff /* just for test */ )
+{
+  m_pcEntropyCoder->resetBits();
+  xEncCoeffQT   ( rTu, compID,  bRealCoeff );
   UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
   return uiBits;
 }
 
-UInt
-TEncSearch::xGetIntraBitsQTChroma( TComDataCU*  pcCU,
-                                  UInt         uiTrDepth,
-                                  UInt         uiAbsPartIdx,
-                                  UInt         uiChromaId,
-                                  Bool         bRealCoeff /* just for test */ )
-{
-  m_pcEntropyCoder->resetBits();
-  if( uiChromaId == TEXT_CHROMA_U)
-  {
-    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_U,  bRealCoeff );
-  }
-  else if(uiChromaId == TEXT_CHROMA_V)
-  {
-    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_V,  bRealCoeff );
-  }
-
-  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
-  return uiBits;
-}
-
-Void
-TEncSearch::xIntraCodingLumaBlk( TComDataCU* pcCU,
-                                UInt        uiTrDepth,
-                                UInt        uiAbsPartIdx,
-                                TComYuv*    pcOrgYuv, 
-                                TComYuv*    pcPredYuv, 
-                                TComYuv*    pcResiYuv, 
-#if H_3D_VSO
-                                Dist&       ruiDist,
+Void TEncSearch::xIntraCodingTUBlock(       TComYuv*    pcOrgYuv,
+                                            TComYuv*    pcPredYuv,
+                                            TComYuv*    pcResiYuv,
+                                            Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                      const Bool        checkCrossCPrediction,
+#if NH_3D_VSO
+                                            Dist&       ruiDist,
 #else
-                                UInt&       ruiDist,
-#endif
-                                Int        default0Save1Load2 
+                                            Distortion& ruiDist,
+#endif
+                                      const ComponentID compID,
+                                            TComTU&     rTu
+                                      DEBUG_STRING_FN_DECLARE(sDebug)
+                                           ,Int         default0Save1Load2
 #if H_3D_DIM_ENC
                                 , Bool       zeroResi
 #endif
-                                )
+
+                                     )
 {
-  UInt    uiLumaPredMode    = pcCU     ->getLumaIntraDir     ( uiAbsPartIdx );
-  UInt    uiFullDepth       = pcCU     ->getDepth   ( 0 )  + uiTrDepth;
-  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
-  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
-  UInt    uiStride          = pcOrgYuv ->getStride  ();
-  Pel*    piOrg             = pcOrgYuv ->getLumaAddr( uiAbsPartIdx );
-  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
-  Pel*    piResi            = pcResiYuv->getLumaAddr( uiAbsPartIdx );
-  Pel*    piReco            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
-  
-  UInt    uiLog2TrSize      = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-  UInt    uiQTLayer         = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-  UInt    uiNumCoeffPerInc  = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
-  TCoeff* pcCoeff           = m_ppcQTTempCoeffY[ uiQTLayer ] + uiNumCoeffPerInc * uiAbsPartIdx;
+  if (!rTu.ProcessComponentSection(compID))
+  {
+    return;
+  }
+  const Bool           bIsLuma          = isLuma(compID);
+  const TComRectangle &rect             = rTu.getRect(compID);
+        TComDataCU    *pcCU             = rTu.getCU();
+  const UInt           uiAbsPartIdx     = rTu.GetAbsPartIdxTU();
+  const TComSPS       &sps              = *(pcCU->getSlice()->getSPS());
+
+  const UInt           uiTrDepth        = rTu.GetTransformDepthRelAdj(compID);
+  const UInt           uiFullDepth      = rTu.GetTransformDepthTotal();
+  const UInt           uiLog2TrSize     = rTu.GetLog2LumaTrSize();
+  const ChromaFormat   chFmt            = pcOrgYuv->getChromaFormat();
+  const ChannelType    chType           = toChannelType(compID);
+  const Int            bitDepth         = sps.getBitDepth(chType);
+
+  const UInt           uiWidth          = rect.width;
+  const UInt           uiHeight         = rect.height;
+  const UInt           uiStride         = pcOrgYuv ->getStride (compID);
+        Pel           *piOrg            = pcOrgYuv ->getAddr( compID, uiAbsPartIdx );
+        Pel           *piPred           = pcPredYuv->getAddr( compID, uiAbsPartIdx );
+        Pel           *piResi           = pcResiYuv->getAddr( compID, uiAbsPartIdx );
+        Pel           *piReco           = pcPredYuv->getAddr( compID, uiAbsPartIdx );
+  const UInt           uiQTLayer        = sps.getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+        Pel           *piRecQt          = m_pcQTTempTComYuv[ uiQTLayer ].getAddr( compID, uiAbsPartIdx );
+  const UInt           uiRecQtStride    = m_pcQTTempTComYuv[ uiQTLayer ].getStride(compID);
+  const UInt           uiZOrder         = pcCU->getZorderIdxInCtu() + uiAbsPartIdx;
+        Pel           *piRecIPred       = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), uiZOrder );
+        UInt           uiRecIPredStride = pcCU->getPic()->getPicYuvRec()->getStride  ( compID );
+        TCoeff        *pcCoeff          = m_ppcQTTempCoeff[compID][uiQTLayer] + rTu.getCoefficientOffset(compID);
+        Bool           useTransformSkip = pcCU->getTransformSkip(uiAbsPartIdx, compID);
+
 #if ADAPTIVE_QP_SELECTION
-  Int*    pcArlCoeff        = m_ppcQTTempArlCoeffY[ uiQTLayer ] + uiNumCoeffPerInc * uiAbsPartIdx;
-#endif
-  Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
-  UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
-  
-  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
-  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
-  Bool    useTransformSkip  = pcCU->getTransformSkip(uiAbsPartIdx, TEXT_LUMA);
+        TCoeff        *pcArlCoeff       = m_ppcQTTempArlCoeff[compID][ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+#endif
+
+  const UInt           uiChPredMode     = pcCU->getIntraDir( chType, uiAbsPartIdx );
+  const UInt           partsPerMinCU    = 1<<(2*(sps.getMaxTotalCUDepth() - sps.getLog2DiffMaxMinCodingBlockSize()));
+  const UInt           uiChCodedMode    = (uiChPredMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt, partsPerMinCU)) : uiChPredMode;
+  const UInt           uiChFinalMode    = ((chFmt == CHROMA_422)       && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;
+
+  const Int            blkX                                 = g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  const Int            blkY                                 = g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  const Int            bufferOffset                         = blkX + (blkY * MAX_CU_SIZE);
+        Pel  *const    encoderLumaResidual                  = resiLuma[RESIDUAL_ENCODER_SIDE ] + bufferOffset;
+        Pel  *const    reconstructedLumaResidual            = resiLuma[RESIDUAL_RECONSTRUCTED] + bufferOffset;
+  const Bool           bUseCrossCPrediction                 = isChroma(compID) && (uiChPredMode == DM_CHROMA_IDX) && checkCrossCPrediction;
+  const Bool           bUseReconstructedResidualForEstimate = m_pcEncCfg->getUseReconBasedCrossCPredictionEstimate();
+        Pel *const     lumaResidualForEstimate              = bUseReconstructedResidualForEstimate ? reconstructedLumaResidual : encoderLumaResidual;
+
+#if DEBUG_STRING
+  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTRA);
+#endif
+
   //===== init availability pattern =====
   Bool  bAboveAvail = false;
   Bool  bLeftAvail  = false;
-  if(default0Save1Load2 != 2)
-  {
-    pcCU->getPattern()->initPattern   ( pcCU, uiTrDepth, uiAbsPartIdx );
-    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+
+  DEBUG_STRING_NEW(sTemp)
+
+#if !DEBUG_STRING
+  if( default0Save1Load2 != 2 )
+#endif
+  {
+    const Bool bUseFilteredPredictions=TComPrediction::filteringIntraReferenceSamples(compID, uiChFinalMode, uiWidth, uiHeight, chFmt, sps.getSpsRangeExtension().getIntraSmoothingDisabledFlag());
+
+    initIntraPatternChType( rTu, bAboveAvail, bLeftAvail, compID, bUseFilteredPredictions DEBUG_STRING_PASS_INTO(sDebug) );
+
     //===== get prediction signal =====
 #if H_3D_DIM
@@ -1122,13 +1252,15 @@
     {
 #endif
-    predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+
+    predIntraAng( compID, uiChFinalMode, piOrg, uiStride, piPred, uiStride, rTu, bAboveAvail, bLeftAvail, bUseFilteredPredictions );
 #if H_3D_DIM
     }
 #endif
-    // save prediction 
-    if(default0Save1Load2 == 1)
+
+    // save prediction
+    if( default0Save1Load2 == 1 )
     {
       Pel*  pPred   = piPred;
-      Pel*  pPredBuf = m_pSharedPredTransformSkip[0];
+      Pel*  pPredBuf = m_pSharedPredTransformSkip[compID];
       Int k = 0;
       for( UInt uiY = 0; uiY < uiHeight; uiY++ )
@@ -1142,9 +1274,10 @@
     }
   }
-  else 
+#if !DEBUG_STRING
+  else
   {
     // load prediction
     Pel*  pPred   = piPred;
-    Pel*  pPredBuf = m_pSharedPredTransformSkip[0];
+    Pel*  pPredBuf = m_pSharedPredTransformSkip[compID];
     Int k = 0;
     for( UInt uiY = 0; uiY < uiHeight; uiY++ )
@@ -1157,4 +1290,6 @@
     }
   }
+#endif
+
   //===== get residual signal =====
   {
@@ -1163,4 +1298,5 @@
     Pel*  pPred   = piPred;
     Pel*  pResi   = piResi;
+
     for( UInt uiY = 0; uiY < uiHeight; uiY++ )
     {
@@ -1174,47 +1310,71 @@
       {
 #endif
-        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-        {
-          pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
-        }
-        pOrg  += uiStride;
-        pResi += uiStride;
-        pPred += uiStride;
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
+      }
+
+      pOrg  += uiStride;
+      pResi += uiStride;
+      pPred += uiStride;
 #if H_3D_DIM_ENC
       }
 #endif
-    }
-  }
-  
+
+    }
+  }
+
+  if (pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
+  {
+    if (bUseCrossCPrediction)
+    {
+      if (xCalcCrossComponentPredictionAlpha( rTu, compID, lumaResidualForEstimate, piResi, uiWidth, uiHeight, MAX_CU_SIZE, uiStride ) == 0)
+      {
+        return;
+      }
+      TComTrQuant::crossComponentPrediction ( rTu, compID, reconstructedLumaResidual, piResi, piResi, uiWidth, uiHeight, MAX_CU_SIZE, uiStride, uiStride, false );
+    }
+    else if (isLuma(compID) && !bUseReconstructedResidualForEstimate)
+    {
+      xStoreCrossComponentPredictionResult( encoderLumaResidual, piResi, rTu, 0, 0, MAX_CU_SIZE, uiStride );
+    }
+  }
+
   //===== transform and quantization =====
   //--- init rate estimation arrays for RDOQ ---
-  if( useTransformSkip? m_pcEncCfg->getUseRDOQTS():m_pcEncCfg->getUseRDOQ())
-  {
-    m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiWidth, TEXT_LUMA );
-  }
+  if( useTransformSkip ? m_pcEncCfg->getUseRDOQTS() : m_pcEncCfg->getUseRDOQ() )
+  {
+    m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiHeight, chType );
+  }
+
   //--- transform and quantization ---
-  UInt uiAbsSum = 0;
-  pcCU       ->setTrIdxSubParts ( uiTrDepth, uiAbsPartIdx, uiFullDepth );
-
-  m_pcTrQuant->setQPforQuant    ( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
-
-#if RDOQ_CHROMA_LAMBDA 
-  m_pcTrQuant->selectLambda     (TEXT_LUMA);  
-#endif
-
-  m_pcTrQuant->transformNxN     ( pcCU, piResi, uiStride, pcCoeff, 
+  TCoeff uiAbsSum = 0;
+  if (bIsLuma)
+  {
+    pcCU       ->setTrIdxSubParts ( uiTrDepth, uiAbsPartIdx, uiFullDepth );
+  }
+
+  const QpParam cQP(*pcCU, compID);
+
+#if RDOQ_CHROMA_LAMBDA
+  m_pcTrQuant->selectLambda     (compID);
+#endif
+
+  m_pcTrQuant->transformNxN     ( rTu, compID, piResi, uiStride, pcCoeff,
 #if ADAPTIVE_QP_SELECTION
-    pcArlCoeff, 
-#endif
-    uiWidth, uiHeight, uiAbsSum, TEXT_LUMA, uiAbsPartIdx,useTransformSkip );
-  
-  //--- set coded block flag ---
-  pcCU->setCbfSubParts          ( ( uiAbsSum ? 1 : 0 ) << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+    pcArlCoeff,
+#endif
+    uiAbsSum, cQP
+    );
+
   //--- inverse transform ---
-  if( uiAbsSum )
-  {
-    Int scalingListType = 0 + g_eTTable[(Int)TEXT_LUMA];
-    assert(scalingListType < SCALING_LIST_NUM);
-    m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
+
+#if DEBUG_STRING
+  if ( (uiAbsSum > 0) || (DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask) )
+#else
+  if ( uiAbsSum > 0 )
+#endif
+  {
+    m_pcTrQuant->invTransformNxN ( rTu, compID, piResi, uiStride, pcCoeff, cQP DEBUG_STRING_PASS_INTO_OPTIONAL(&sDebug, (DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask)) );
   }
   else
@@ -1228,5 +1388,6 @@
     }
   }
-  
+
+
   //===== reconstruction =====
   {
@@ -1236,257 +1397,145 @@
     Pel* pRecQt     = piRecQt;
     Pel* pRecIPred  = piRecIPred;
-    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-    {
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        pReco    [ uiX ] = ClipY( pPred[ uiX ] + pResi[ uiX ] );
-        pRecQt   [ uiX ] = pReco[ uiX ];
-        pRecIPred[ uiX ] = pReco[ uiX ];
-      }
-      pPred     += uiStride;
-      pResi     += uiStride;
-      pReco     += uiStride;
-      pRecQt    += uiRecQtStride;
-      pRecIPred += uiRecIPredStride;
-    }
-  }
-  
+
+    if (pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
+    {
+      if (bUseCrossCPrediction)
+      {
+        TComTrQuant::crossComponentPrediction( rTu, compID, reconstructedLumaResidual, piResi, piResi, uiWidth, uiHeight, MAX_CU_SIZE, uiStride, uiStride, true );
+      }
+      else if (isLuma(compID))
+      {
+        xStoreCrossComponentPredictionResult( reconstructedLumaResidual, piResi, rTu, 0, 0, MAX_CU_SIZE, uiStride );
+      }
+    }
+
+ #if DEBUG_STRING
+    std::stringstream ss(stringstream::out);
+    const Bool bDebugPred=((DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+    const Bool bDebugResi=((DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+    const Bool bDebugReco=((DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+
+    if (bDebugPred || bDebugResi || bDebugReco)
+    {
+      ss << "###: " << "CompID: " << compID << " pred mode (ch/fin): " << uiChPredMode << "/" << uiChFinalMode << " absPartIdx: " << rTu.GetAbsPartIdxTU() << "\n";
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        ss << "###: ";
+        if (bDebugPred)
+        {
+          ss << " - pred: ";
+          for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+          {
+            ss << pPred[ uiX ] << ", ";
+          }
+        }
+        if (bDebugResi)
+        {
+          ss << " - resi: ";
+        }
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          if (bDebugResi)
+          {
+            ss << pResi[ uiX ] << ", ";
+          }
+          pReco    [ uiX ] = Pel(ClipBD<Int>( Int(pPred[uiX]) + Int(pResi[uiX]), bitDepth ));
+          pRecQt   [ uiX ] = pReco[ uiX ];
+          pRecIPred[ uiX ] = pReco[ uiX ];
+        }
+        if (bDebugReco)
+        {
+          ss << " - reco: ";
+          for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+          {
+            ss << pReco[ uiX ] << ", ";
+          }
+        }
+        pPred     += uiStride;
+        pResi     += uiStride;
+        pReco     += uiStride;
+        pRecQt    += uiRecQtStride;
+        pRecIPred += uiRecIPredStride;
+        ss << "\n";
+      }
+      DEBUG_STRING_APPEND(sDebug, ss.str())
+    }
+    else
+#endif
+    {
+
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pReco    [ uiX ] = Pel(ClipBD<Int>( Int(pPred[uiX]) + Int(pResi[uiX]), bitDepth ));
+          pRecQt   [ uiX ] = pReco[ uiX ];
+          pRecIPred[ uiX ] = pReco[ uiX ];
+        }
+        pPred     += uiStride;
+        pResi     += uiStride;
+        pReco     += uiStride;
+        pRecQt    += uiRecQtStride;
+        pRecIPred += uiRecIPredStride;
+      }
+    }
+  }
+
   //===== update distortion =====
-#if H_3D_VSO // M39
+#if NH_3D_VSO // M39
   if ( m_pcRdCost->getUseVSO() )  
-      ruiDist += m_pcRdCost->getDistPartVSO  ( pcCU, uiAbsPartIdx, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, false );  
+  {
+      ruiDist += m_pcRdCost->getDistPartVSO  ( pcCU, uiAbsPartIdx, bitDepth, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, false );  
+  }
   else
 #endif
-  ruiDist += m_pcRdCost->getDistPart(g_bitDepthY, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+    ruiDist += m_pcRdCost->getDistPart( bitDepth, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, compID );
 }
-
-Void
-TEncSearch::xIntraCodingChromaBlk( TComDataCU* pcCU,
-                                  UInt        uiTrDepth,
-                                  UInt        uiAbsPartIdx,
-                                  TComYuv*    pcOrgYuv, 
-                                  TComYuv*    pcPredYuv, 
-                                  TComYuv*    pcResiYuv, 
-                                  UInt&       ruiDist,
-                                  UInt        uiChromaId,
-                                  Int        default0Save1Load2 )
-{
-  UInt uiOrgTrDepth = uiTrDepth;
-  UInt uiFullDepth  = pcCU->getDepth( 0 ) + uiTrDepth;
-  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-  if( uiLog2TrSize == 2 )
-  {
-    assert( uiTrDepth > 0 );
-    uiTrDepth--;
-    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
-    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
-    if( !bFirstQ )
-    {
-      return;
-    }
-  }
-  
-  TextType  eText             = ( uiChromaId > 0 ? TEXT_CHROMA_V : TEXT_CHROMA_U );
-  UInt      uiChromaPredMode  = pcCU     ->getChromaIntraDir( uiAbsPartIdx );
-  UInt      uiWidth           = pcCU     ->getWidth   ( 0 ) >> ( uiTrDepth + 1 );
-  UInt      uiHeight          = pcCU     ->getHeight  ( 0 ) >> ( uiTrDepth + 1 );
-  UInt      uiStride          = pcOrgYuv ->getCStride ();
-  Pel*      piOrg             = ( uiChromaId > 0 ? pcOrgYuv ->getCrAddr( uiAbsPartIdx ) : pcOrgYuv ->getCbAddr( uiAbsPartIdx ) );
-  Pel*      piPred            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
-  Pel*      piResi            = ( uiChromaId > 0 ? pcResiYuv->getCrAddr( uiAbsPartIdx ) : pcResiYuv->getCbAddr( uiAbsPartIdx ) );
-  Pel*      piReco            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
-  
-  UInt      uiQTLayer         = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-  UInt      uiNumCoeffPerInc  = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) ) >> 2;
-  TCoeff*   pcCoeff           = ( uiChromaId > 0 ? m_ppcQTTempCoeffCr[ uiQTLayer ] : m_ppcQTTempCoeffCb[ uiQTLayer ] ) + uiNumCoeffPerInc * uiAbsPartIdx;
-#if ADAPTIVE_QP_SELECTION
-  Int*      pcArlCoeff        = ( uiChromaId > 0 ? m_ppcQTTempArlCoeffCr[ uiQTLayer ] : m_ppcQTTempArlCoeffCb[ uiQTLayer ] ) + uiNumCoeffPerInc * uiAbsPartIdx;
-#endif
-  Pel*      piRecQt           = ( uiChromaId > 0 ? m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx ) : m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx ) );
-  UInt      uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getCStride();
-  
-  UInt      uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-  Pel*      piRecIPred        = ( uiChromaId > 0 ? pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder ) : pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder ) );
-  UInt      uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride();
-  Bool      useTransformSkipChroma       = pcCU->getTransformSkip(uiAbsPartIdx, eText);
-  //===== update chroma mode =====
-  if( uiChromaPredMode == DM_CHROMA_IDX )
-  {
-    uiChromaPredMode          = pcCU->getLumaIntraDir( 0 );
 #if H_3D_DIM
     mapDepthModeToIntraDir( uiChromaPredMode );
 #endif
-  }
-  
-  //===== init availability pattern =====
-  Bool  bAboveAvail = false;
-  Bool  bLeftAvail  = false;
-  if( default0Save1Load2 != 2 )
-  {
-    pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
-
-    pcCU->getPattern()->initAdiPatternChroma( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
-    Int*  pPatChroma  = ( uiChromaId > 0 ? pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_piYuvExt ) : pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_piYuvExt ) );
-
-    //===== get prediction signal =====
-    {
-      predIntraChromaAng( pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
-    }
-    // save prediction 
-    if( default0Save1Load2 == 1 )
-    {
-      Pel*  pPred   = piPred;
-      Pel*  pPredBuf = m_pSharedPredTransformSkip[1 + uiChromaId];
-      Int k = 0;
-      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-      {
-        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-        {
-          pPredBuf[ k ++ ] = pPred[ uiX ];
-        }
-        pPred += uiStride;
-      }
-    }
-  }
-  else
-  {
-    // load prediction 
-    Pel*  pPred   = piPred;
-    Pel*  pPredBuf = m_pSharedPredTransformSkip[1 + uiChromaId];
-    Int k = 0;
-    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-    {
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        pPred[ uiX ] = pPredBuf[ k ++ ];
-      }
-      pPred += uiStride;
-    }
-  }
-  //===== get residual signal =====
-  {
-    // get residual
-    Pel*  pOrg    = piOrg;
-    Pel*  pPred   = piPred;
-    Pel*  pResi   = piResi;
-    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-    {
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
-      }
-      pOrg  += uiStride;
-      pResi += uiStride;
-      pPred += uiStride;
-    }
-  }
-  
-  //===== transform and quantization =====
-  {
-    //--- init rate estimation arrays for RDOQ ---
-    if( useTransformSkipChroma? m_pcEncCfg->getUseRDOQTS():m_pcEncCfg->getUseRDOQ())
-    {
-      m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiWidth, eText );
-    }
-    //--- transform and quantization ---
-    UInt uiAbsSum = 0;
-
-    Int curChromaQpOffset;
-    if(eText == TEXT_CHROMA_U)
-    {
-      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
-    }
-    else
-    {
-      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
-    }
-    m_pcTrQuant->setQPforQuant     ( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-#if RDOQ_CHROMA_LAMBDA 
-    m_pcTrQuant->selectLambda(eText);
-#endif
-    m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 
-#if ADAPTIVE_QP_SELECTION
-                                     pcArlCoeff, 
-#endif
-                                     uiWidth, uiHeight, uiAbsSum, eText, uiAbsPartIdx, useTransformSkipChroma );
-    //--- set coded block flag ---
-    pcCU->setCbfSubParts           ( ( uiAbsSum ? 1 : 0 ) << uiOrgTrDepth, eText, uiAbsPartIdx, pcCU->getDepth(0) + uiTrDepth );
-    //--- inverse transform ---
-    if( uiAbsSum )
-    {
-      Int scalingListType = 0 + g_eTTable[(Int)eText];
-      assert(scalingListType < SCALING_LIST_NUM);
-      m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
-    }
-    else
-    {
-      Pel* pResi = piResi;
-      memset( pcCoeff, 0, sizeof( TCoeff ) * uiWidth * uiHeight );
-      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-      {
-        memset( pResi, 0, sizeof( Pel ) * uiWidth );
-        pResi += uiStride;
-      }
-    }
-  }
-  
-  //===== reconstruction =====
-  {
-    Pel* pPred      = piPred;
-    Pel* pResi      = piResi;
-    Pel* pReco      = piReco;
-    Pel* pRecQt     = piRecQt;
-    Pel* pRecIPred  = piRecIPred;
-    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-    {
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        pReco    [ uiX ] = ClipC( pPred[ uiX ] + pResi[ uiX ] );
-        pRecQt   [ uiX ] = pReco[ uiX ];
-        pRecIPred[ uiX ] = pReco[ uiX ];
-      }
-      pPred     += uiStride;
-      pResi     += uiStride;
-      pReco     += uiStride;
-      pRecQt    += uiRecQtStride;
-      pRecIPred += uiRecIPredStride;
-    }
-  }
-  
-  //===== update distortion =====
-  ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, eText );
-}
-
-
-
-Void 
-TEncSearch::xRecurIntraCodingQT( TComDataCU*  pcCU, 
-                                UInt         uiTrDepth,
-                                UInt         uiAbsPartIdx, 
-                                Bool         bLumaOnly,
-                                TComYuv*     pcOrgYuv, 
-                                TComYuv*     pcPredYuv, 
-                                TComYuv*     pcResiYuv, 
-#if H_3D_VSO
-                                Dist&        ruiDistY,
+
+
+
+
+Void
+TEncSearch::xRecurIntraCodingLumaQT(TComYuv*    pcOrgYuv,
+                                    TComYuv*    pcPredYuv,
+                                    TComYuv*    pcResiYuv,
+                                    Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+#if NH_3D_VSO
+                                    Dist&        ruiDistY,
 #else
-                                UInt&        ruiDistY,
-#endif
-                                UInt&        ruiDistC,
+                                    Distortion& ruiDistY,
+#endif
 #if HHI_RQT_INTRA_SPEEDUP
-                                Bool         bCheckFirst,
-#endif
-                                Double&      dRDCost 
+                                    Bool        bCheckFirst,
+#endif
+                                    Double&     dRDCost,
+                                    TComTU&     rTu
 #if H_3D_DIM_ENC
                                 , Bool        zeroResi
 #endif                                
-)
+                                    DEBUG_STRING_FN_DECLARE(sDebug))
 {
-  UInt    uiFullDepth   = pcCU->getDepth( 0 ) +  uiTrDepth;
-  UInt    uiLog2TrSize  = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-  Bool    bCheckFull    = ( uiLog2TrSize  <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
-  Bool    bCheckSplit   = ( uiLog2TrSize  >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
-  
+  TComDataCU   *pcCU          = rTu.getCU();
+  const UInt    uiAbsPartIdx  = rTu.GetAbsPartIdxTU();
+  const UInt    uiFullDepth   = rTu.GetTransformDepthTotal();
+  const UInt    uiTrDepth     = rTu.GetTransformDepthRel();
+  const UInt    uiLog2TrSize  = rTu.GetLog2LumaTrSize();
+        Bool    bCheckFull    = ( uiLog2TrSize  <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+        Bool    bCheckSplit   = ( uiLog2TrSize  >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+
+        Pel     resiLumaSplit [NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
+        Pel     resiLumaSingle[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
+
+        Bool    bMaintainResidual[NUMBER_OF_STORED_RESIDUAL_TYPES];
+        for (UInt residualTypeIndex = 0; residualTypeIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; residualTypeIndex++)
+        {
+          bMaintainResidual[residualTypeIndex] = true; //assume true unless specified otherwise
+        }
+
+        bMaintainResidual[RESIDUAL_ENCODER_SIDE] = !(m_pcEncCfg->getUseReconBasedCrossCPredictionEstimate());
+
 #if HHI_RQT_INTRA_SPEEDUP
   Int maxTuSize = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize();
@@ -1499,5 +1548,5 @@
     noSplitIntraMaxTuSize = ( uiLog2TrSize  <= min(maxTuSize,4) );
 
-    // if maximum RD-penalty don't check TU size 32x32 
+    // if maximum RD-penalty don't check TU size 32x32
     if(m_pcEncCfg->getRDpenalty()==2)
     {
@@ -1506,4 +1555,5 @@
   }
   if( bCheckFirst && noSplitIntraMaxTuSize )
+
   {
     bCheckSplit = false;
@@ -1512,5 +1562,5 @@
   Int maxTuSize = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize();
   Int isIntraSlice = (pcCU->getSlice()->getSliceType() == I_SLICE);
-  // if maximum RD-penalty don't check TU size 32x32 
+  // if maximum RD-penalty don't check TU size 32x32
   if((m_pcEncCfg->getRDpenalty()==2)  && !isIntraSlice)
   {
@@ -1524,25 +1574,21 @@
   }
 #endif
-  Double  dSingleCost   = MAX_DOUBLE;
-#if H_3D_VSO
-  Dist    uiSingleDistY = 0;
+  Double     dSingleCost                        = MAX_DOUBLE;
+#if NH_3D_VSO
+  Dist       uiSingleDistLuma                   = 0;
 #else
-  UInt    uiSingleDistY = 0;
-#endif
-  UInt    uiSingleDistC = 0;
-  UInt    uiSingleCbfY  = 0;
-  UInt    uiSingleCbfU  = 0;
-  UInt    uiSingleCbfV  = 0;
-  Bool    checkTransformSkip  = pcCU->getSlice()->getPPS()->getUseTransformSkip();
-  UInt    widthTransformSkip  = pcCU->getWidth ( 0 ) >> uiTrDepth;
-  UInt    heightTransformSkip = pcCU->getHeight( 0 ) >> uiTrDepth;
-  Int     bestModeId    = 0;
-  Int     bestModeIdUV[2] = {0, 0};
-  checkTransformSkip         &= (widthTransformSkip == 4 && heightTransformSkip == 4);
-  checkTransformSkip         &= (!pcCU->getCUTransquantBypass(0));
+  Distortion uiSingleDistLuma                   = 0;
+#endif
+  UInt       uiSingleCbfLuma                    = 0;
+  Bool       checkTransformSkip  = pcCU->getSlice()->getPPS()->getUseTransformSkip();
+  Int        bestModeId[MAX_NUM_COMPONENT] = { 0, 0, 0};
+  checkTransformSkip           &= TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(COMPONENT_Y), pcCU->getSlice()->getPPS()->getPpsRangeExtension().getLog2MaxTransformSkipBlockSize());
+  checkTransformSkip           &= (!pcCU->getCUTransquantBypass(0));
+
   if ( m_pcEncCfg->getUseTransformSkipFast() )
   {
     checkTransformSkip       &= (pcCU->getPartitionSize(uiAbsPartIdx)==SIZE_NxN);
   }
+
   if( bCheckFull )
   {
@@ -1550,26 +1596,19 @@
     {
       //----- store original entropy coding status -----
-        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-#if H_3D_VSO
-      Dist   singleDistYTmp     = 0;
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+#if NH_3D_VSO
+      Dist       singleDistTmpLuma                    = 0;
 #else
-      UInt   singleDistYTmp     = 0;
-#endif
-      UInt   singleDistCTmp     = 0;
-      UInt   singleCbfYTmp      = 0;
-      UInt   singleCbfUTmp      = 0;
-      UInt   singleCbfVTmp      = 0;
-      Double singleCostTmp      = 0;
-      Int    default0Save1Load2 = 0;
-      Int    firstCheckId       = 0;
-
-      UInt   uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + (uiTrDepth - 1) ) << 1 );
-      Bool   bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+      Distortion singleDistTmpLuma                    = 0;
+#endif
+      UInt       singleCbfTmpLuma                     = 0;
+      Double     singleCostTmp                        = 0;
+      Int        firstCheckId                         = 0;
 
       for(Int modeId = firstCheckId; modeId < 2; modeId ++)
       {
-        singleDistYTmp = 0;
-        singleDistCTmp = 0;
-        pcCU ->setTransformSkipSubParts ( modeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+        DEBUG_STRING_NEW(sModeString)
+        Int  default0Save1Load2 = 0;
+        singleDistTmpLuma=0;
         if(modeId == firstCheckId)
         {
@@ -1580,53 +1619,60 @@
           default0Save1Load2 = 2;
         }
-        //----- code luma block with given intra prediction mode and store Cbf-----
-        xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistYTmp,default0Save1Load2); 
-        singleCbfYTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth );
-        //----- code chroma blocks with given intra prediction mode and store Cbf-----
-        if( !bLumaOnly )
-        {
-          if(bFirstQ)
+
+        if (rTu.ProcessComponentSection(COMPONENT_Y))
+        {
+          const UInt totalAdjustedDepthChan = rTu.GetTransformDepthTotalAdj(COMPONENT_Y);
+          pcCU->setTransformSkipSubParts ( modeId, COMPONENT_Y, uiAbsPartIdx, totalAdjustedDepthChan );
+
+          xIntraCodingTUBlock( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSingle, false, singleDistTmpLuma, COMPONENT_Y, rTu DEBUG_STRING_PASS_INTO(sModeString), default0Save1Load2 );
+        }
+        singleCbfTmpLuma = pcCU->getCbf( uiAbsPartIdx, COMPONENT_Y, uiTrDepth );
+
+        //----- determine rate and r-d cost -----
+        if(modeId == 1 && singleCbfTmpLuma == 0)
+        {
+          //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
+          singleCostTmp = MAX_DOUBLE;
+        }
+        else
+        {
+          UInt uiSingleBits = xGetIntraBitsQT( rTu, true, false, false );
+#if NH_3D_VSO // M NEW 
+          if ( m_pcRdCost->getUseRenModel() )
           {
-            pcCU ->setTransformSkipSubParts ( modeId, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
-            pcCU ->setTransformSkipSubParts ( modeId, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
+            singleCostTmp     = m_pcRdCost->calcRdCostVSO( uiSingleBits, singleDistTmpLuma );
           }
-          xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, 0, default0Save1Load2); 
-          xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, 1, default0Save1Load2); 
-          singleCbfUTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
-          singleCbfVTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
-        }
-        //----- determine rate and r-d cost -----
-        if(modeId == 1 && singleCbfYTmp == 0)
-        {
-          //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
-          singleCostTmp = MAX_DOUBLE; 
-        }
-        else
-        {
-          UInt uiSingleBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
-#if H_3D_VSO // M NEW 
-          if ( m_pcRdCost->getUseRenModel() )
-            singleCostTmp     = m_pcRdCost->calcRdCostVSO( uiSingleBits, singleDistYTmp + singleDistCTmp );
           else
 #endif
-          singleCostTmp     = m_pcRdCost->calcRdCost( uiSingleBits, singleDistYTmp + singleDistCTmp );
-        }
-
+            singleCostTmp     = m_pcRdCost->calcRdCost( uiSingleBits, singleDistTmpLuma );
+        }
         if(singleCostTmp < dSingleCost)
         {
+          DEBUG_STRING_SWAP(sDebug, sModeString)
           dSingleCost   = singleCostTmp;
-          uiSingleDistY = singleDistYTmp;
-          uiSingleDistC = singleDistCTmp;
-          uiSingleCbfY  = singleCbfYTmp;
-          uiSingleCbfU  = singleCbfUTmp;
-          uiSingleCbfV  = singleCbfVTmp;
-          bestModeId    = modeId;
-          if(bestModeId == firstCheckId)
+          uiSingleDistLuma = singleDistTmpLuma;
+          uiSingleCbfLuma = singleCbfTmpLuma;
+
+          bestModeId[COMPONENT_Y] = modeId;
+          if(bestModeId[COMPONENT_Y] == firstCheckId)
           {
-            xStoreIntraResultQT(pcCU, uiTrDepth, uiAbsPartIdx,bLumaOnly );
-              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+            xStoreIntraResultQT(COMPONENT_Y, rTu );
+            m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+          }
+
+          if (pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
+          {
+            const Int xOffset = rTu.getRect( COMPONENT_Y ).x0;
+            const Int yOffset = rTu.getRect( COMPONENT_Y ).y0;
+            for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+            {
+              if (bMaintainResidual[storedResidualIndex])
+              {
+                xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaSingle[storedResidualIndex], rTu, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE);
+              }
             }
           }
-        if(modeId == firstCheckId)
+        }
+        if (modeId == firstCheckId)
         {
           m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
@@ -1634,43 +1680,23 @@
       }
 
-      pcCU ->setTransformSkipSubParts ( bestModeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
-
-      if(bestModeId == firstCheckId)
-      {
-        xLoadIntraResultQT(pcCU, uiTrDepth, uiAbsPartIdx,bLumaOnly );
-        pcCU->setCbfSubParts  ( uiSingleCbfY << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
-        if( !bLumaOnly )
-        {
-          if(bFirstQ)
-          {
-            pcCU->setCbfSubParts( uiSingleCbfU << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth( 0 ) + uiTrDepth - 1 );
-            pcCU->setCbfSubParts( uiSingleCbfV << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth( 0 ) + uiTrDepth - 1 );
-          }
-        }
-          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
-        } 
-
-      if( !bLumaOnly )
-      {
-        bestModeIdUV[0] = bestModeIdUV[1] = bestModeId;
-        if(bFirstQ && bestModeId == 1)
-        {
-          //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
-          if(uiSingleCbfU == 0)
-          {
-            pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
-            bestModeIdUV[0] = 0;
-          }
-          if(uiSingleCbfV == 0)
-          {
-            pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
-            bestModeIdUV[1] = 0;
-          }
-        }
+      if (rTu.ProcessComponentSection(COMPONENT_Y))
+      {
+        const UInt totalAdjustedDepthChan   = rTu.GetTransformDepthTotalAdj(COMPONENT_Y);
+        pcCU ->setTransformSkipSubParts ( bestModeId[COMPONENT_Y], COMPONENT_Y, uiAbsPartIdx, totalAdjustedDepthChan );
+      }
+
+      if(bestModeId[COMPONENT_Y] == firstCheckId)
+      {
+        xLoadIntraResultQT(COMPONENT_Y, rTu );
+        if (rTu.ProcessComponentSection(COMPONENT_Y))
+        {
+          pcCU->setCbfSubParts  ( uiSingleCbfLuma << uiTrDepth, COMPONENT_Y, uiAbsPartIdx, rTu.GetTransformDepthTotalAdj(COMPONENT_Y) );
+        }
+
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
       }
     }
     else
     {
-      pcCU ->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
       //----- store original entropy coding status -----
       if( bCheckSplit )
@@ -1678,191 +1704,183 @@
         m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
       }
-      //----- code luma block with given intra prediction mode and store Cbf-----
+      //----- code luma/chroma block with given intra prediction mode and store Cbf-----
       dSingleCost   = 0.0;
+
+      if (rTu.ProcessComponentSection(COMPONENT_Y))
+      {
+        const UInt totalAdjustedDepthChan   = rTu.GetTransformDepthTotalAdj(COMPONENT_Y);
+        pcCU ->setTransformSkipSubParts ( 0, COMPONENT_Y, uiAbsPartIdx, totalAdjustedDepthChan );
+      }
 #if H_3D_DIM_ENC
       xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistY, 0, zeroResi );
 #else
-      xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistY ); 
-#endif
+      xIntraCodingTUBlock( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSingle, false, uiSingleDistLuma, COMPONENT_Y, rTu DEBUG_STRING_PASS_INTO(sDebug));
+#endif
+
       if( bCheckSplit )
       {
-        uiSingleCbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth );
-      }
-      //----- code chroma blocks with given intra prediction mode and store Cbf-----
-      if( !bLumaOnly )
-      {
-        pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth ); 
-        pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth ); 
-        xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistC, 0 ); 
-        xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistC, 1 ); 
-        if( bCheckSplit )
-        {
-          uiSingleCbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
-          uiSingleCbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
-        }
+        uiSingleCbfLuma = pcCU->getCbf( uiAbsPartIdx, COMPONENT_Y, uiTrDepth );
       }
       //----- determine rate and r-d cost -----
-      UInt uiSingleBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
+      UInt uiSingleBits = xGetIntraBitsQT( rTu, true, false, false );
+
       if(m_pcEncCfg->getRDpenalty() && (uiLog2TrSize==5) && !isIntraSlice)
       {
-        uiSingleBits=uiSingleBits*4; 
-      }
-#if H_3D_VSO // M40
+        uiSingleBits=uiSingleBits*4;
+      }
+#if NH_3D_VSO // M40
       if ( m_pcRdCost->getUseLambdaScaleVSO())      
-        dSingleCost = m_pcRdCost->calcRdCostVSO( uiSingleBits, uiSingleDistY + uiSingleDistC );      
+      {
+        dSingleCost = m_pcRdCost->calcRdCostVSO( uiSingleBits, uiSingleDistLuma );      
+      }
       else
 #endif
-      dSingleCost       = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDistY + uiSingleDistC );
-    }
-  }
-  
+      dSingleCost       = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDistLuma );
+
+      if (pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
+      {
+        const Int xOffset = rTu.getRect( COMPONENT_Y ).x0;
+        const Int yOffset = rTu.getRect( COMPONENT_Y ).y0;
+        for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+        {
+          if (bMaintainResidual[storedResidualIndex])
+          {
+            xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaSingle[storedResidualIndex], rTu, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE);
+          }
+        }
+      }
+    }
+  }
+
   if( bCheckSplit )
   {
     //----- store full entropy coding status, load original entropy coding status -----
-      if( bCheckFull )
-      {
-        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
-        m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
-      else
-      {
-        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
-
+    if( bCheckFull )
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    else
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
     //----- code splitted block -----
-    Double  dSplitCost      = 0.0;
-#if H_3D_VSO
-    Dist    uiSplitDistY    = 0;
+    Double     dSplitCost      = 0.0;
+#if NH_3D_VSO
+    Dist       uiSplitDistLuma = 0;
 #else
-    UInt    uiSplitDistY    = 0;
-#endif
-    UInt    uiSplitDistC    = 0;
-    UInt    uiQPartsDiv     = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
-    UInt    uiAbsPartIdxSub = uiAbsPartIdx;
-
-    UInt    uiSplitCbfY = 0;
-    UInt    uiSplitCbfU = 0;
-    UInt    uiSplitCbfV = 0;
-
-    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiAbsPartIdxSub += uiQPartsDiv )
-    {
+    Distortion uiSplitDistLuma = 0;
+#endif
+
+    UInt       uiSplitCbfLuma  = 0;
+
+    TComTURecurse tuRecurseChild(rTu, false);
+    DEBUG_STRING_NEW(sSplit)
+    do
+    {
+      DEBUG_STRING_NEW(sChild)
 #if HHI_RQT_INTRA_SPEEDUP
-      xRecurIntraCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiSplitDistY, uiSplitDistC, bCheckFirst, dSplitCost );
+      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSplit, uiSplitDistLuma, bCheckFirst, dSplitCost, tuRecurseChild DEBUG_STRING_PASS_INTO(sChild) );
 #else
-      xRecurIntraCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiSplitDistY, uiSplitDistC, dSplitCost );
-#endif
-
-      uiSplitCbfY |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_LUMA, uiTrDepth + 1 );
-      if(!bLumaOnly)
-      {
-        uiSplitCbfU |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_U, uiTrDepth + 1 );
-        uiSplitCbfV |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_V, uiTrDepth + 1 );
-      }
-    }
-
-    for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
-    {
-      pcCU->getCbf( TEXT_LUMA )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfY << uiTrDepth );
-    }
-    if( !bLumaOnly )
-    {
-      for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
-      {
-        pcCU->getCbf( TEXT_CHROMA_U )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfU << uiTrDepth );
-        pcCU->getCbf( TEXT_CHROMA_V )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfV << uiTrDepth );
+      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSplit, uiSplitDistLuma, dSplitCost, tuRecurseChild DEBUG_STRING_PASS_INTO(sChild) );
+#endif
+      DEBUG_STRING_APPEND(sSplit, sChild)
+      uiSplitCbfLuma |= pcCU->getCbf( tuRecurseChild.GetAbsPartIdxTU(), COMPONENT_Y, tuRecurseChild.GetTransformDepthRel() );
+    } while (tuRecurseChild.nextSection(rTu) );
+
+    UInt    uiPartsDiv     = rTu.GetAbsPartIdxNumParts();
+    {
+      if (uiSplitCbfLuma)
+      {
+        const UInt flag=1<<uiTrDepth;
+        UChar *pBase=pcCU->getCbf( COMPONENT_Y );
+        for( UInt uiOffs = 0; uiOffs < uiPartsDiv; uiOffs++ )
+        {
+          pBase[ uiAbsPartIdx + uiOffs ] |= flag;
+        }
       }
     }
     //----- restore context states -----
-      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-
+    m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    
     //----- determine rate and r-d cost -----
-    UInt uiSplitBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
-#if H_3D_VSO // M41
+
+    UInt uiSplitBits = xGetIntraBitsQT( rTu, true, false, false );
+#if NH_3D_VSO // M41
     if( m_pcRdCost->getUseLambdaScaleVSO() )    
-      dSplitCost = m_pcRdCost->calcRdCostVSO( uiSplitBits, uiSplitDistY + uiSplitDistC );    
+    {
+      dSplitCost = m_pcRdCost->calcRdCostVSO( uiSplitBits, uiSplitDistLuma );    
+    }
     else
 #endif
-    dSplitCost       = m_pcRdCost->calcRdCost( uiSplitBits, uiSplitDistY + uiSplitDistC );
-    
+    dSplitCost       = m_pcRdCost->calcRdCost( uiSplitBits, uiSplitDistLuma );
+
     //===== compare and set best =====
     if( dSplitCost < dSingleCost )
     {
       //--- update cost ---
-      ruiDistY += uiSplitDistY;
-      ruiDistC += uiSplitDistC;
+      DEBUG_STRING_SWAP(sSplit, sDebug)
+      ruiDistY += uiSplitDistLuma;
       dRDCost  += dSplitCost;
+
+      if (pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
+      {
+        const Int xOffset = rTu.getRect( COMPONENT_Y ).x0;
+        const Int yOffset = rTu.getRect( COMPONENT_Y ).y0;
+        for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+        {
+          if (bMaintainResidual[storedResidualIndex])
+          {
+            xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaSplit[storedResidualIndex], rTu, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE);
+          }
+        }
+      }
+
       return;
     }
+
     //----- set entropy coding status -----
-      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
-    
+    m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+
     //--- set transform index and Cbf values ---
     pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiFullDepth );
-    pcCU->setCbfSubParts  ( uiSingleCbfY << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
-    pcCU ->setTransformSkipSubParts  ( bestModeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
-    if( !bLumaOnly )
-    {
-      pcCU->setCbfSubParts( uiSingleCbfU << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth );
-      pcCU->setCbfSubParts( uiSingleCbfV << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth );
-      pcCU->setTransformSkipSubParts ( bestModeIdUV[0], TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
-      pcCU->setTransformSkipSubParts ( bestModeIdUV[1], TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
-    }
-    
+    const TComRectangle &tuRect=rTu.getRect(COMPONENT_Y);
+    const UInt totalAdjustedDepthChan   = rTu.GetTransformDepthTotalAdj(COMPONENT_Y);
+    pcCU->setCbfSubParts  ( uiSingleCbfLuma << uiTrDepth, COMPONENT_Y, uiAbsPartIdx, totalAdjustedDepthChan );
+    pcCU ->setTransformSkipSubParts  ( bestModeId[COMPONENT_Y], COMPONENT_Y, uiAbsPartIdx, totalAdjustedDepthChan );
+
     //--- set reconstruction for next intra prediction blocks ---
+    const UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    const UInt  uiZOrder    = pcCU->getZorderIdxInCtu() + uiAbsPartIdx;
+    const UInt  uiWidth     = tuRect.width;
+    const UInt  uiHeight    = tuRect.height;
+    Pel*  piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getAddr( COMPONENT_Y, uiAbsPartIdx );
+    UInt  uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ( COMPONENT_Y );
+    Pel*  piDes       = pcCU->getPic()->getPicYuvRec()->getAddr( COMPONENT_Y, pcCU->getCtuRsAddr(), uiZOrder );
+    UInt  uiDesStride = pcCU->getPic()->getPicYuvRec()->getStride  ( COMPONENT_Y );
+
+    for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        piDes[ uiX ] = piSrc[ uiX ];
+      }
+    }
+  }
+
+#if NH_3D_VSO // M42
+  if ( m_pcRdCost->getUseRenModel() && bCheckFull )
+  {
     UInt  uiWidth     = pcCU->getWidth ( 0 ) >> uiTrDepth;
     UInt  uiHeight    = pcCU->getHeight( 0 ) >> uiTrDepth;
     UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-    UInt  uiZOrder    = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-    Pel*  piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
-    UInt  uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
-    Pel*  piDes       = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
-    UInt  uiDesStride = pcCU->getPic()->getPicYuvRec()->getStride  ();
-    for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
-    {
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        piDes[ uiX ] = piSrc[ uiX ];
-      }
-    }
-    if( !bLumaOnly )
-    {
-      uiWidth   >>= 1;
-      uiHeight  >>= 1;
-      piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr  ( uiAbsPartIdx );
-      uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getCStride ();
-      piDes       = pcCU->getPic()->getPicYuvRec()->getCbAddr ( pcCU->getAddr(), uiZOrder );
-      uiDesStride = pcCU->getPic()->getPicYuvRec()->getCStride();
-      for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
-      {
-        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-        {
-          piDes[ uiX ] = piSrc[ uiX ];
-        }
-      }
-      piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr  ( uiAbsPartIdx );
-      piDes       = pcCU->getPic()->getPicYuvRec()->getCrAddr ( pcCU->getAddr(), uiZOrder );
-      for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
-      {
-        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-        {
-          piDes[ uiX ] = piSrc[ uiX ];
-        }
-      }
-    }
-  }
-#if H_3D_VSO // M42
-  if ( m_pcRdCost->getUseRenModel() && bCheckFull )
-  {
-    UInt  uiWidth     = pcCU->getWidth ( 0 ) >> uiTrDepth;
-    UInt  uiHeight    = pcCU->getHeight( 0 ) >> uiTrDepth;
-    UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-    Pel*  piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
-    UInt  uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
+    Pel*  piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getAddr( COMPONENT_Y, uiAbsPartIdx );
+    UInt  uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getStride( COMPONENT_Y );
 
     m_pcRdCost->setRenModelData( pcCU, uiAbsPartIdx, piSrc, (Int) uiSrcStride, (Int) uiWidth, (Int) uiHeight );
   }
 #endif
-  ruiDistY += uiSingleDistY;
-  ruiDistC += uiSingleDistC;
+
+  ruiDistY += uiSingleDistLuma;
   dRDCost  += dSingleCost;
 }
@@ -2216,9 +2234,5 @@
 
   Bool bDummy = false;
-#if H_3D_DISABLE_CHROMA
-  m_pcEntropyCoder->encodeCoeff( pcCU, 0, pcCU->getDepth( 0 ), uiWidth, uiHeight, bDummy, true );
-#else
   m_pcEntropyCoder->encodeCoeff( pcCU, 0, pcCU->getDepth( 0 ), uiWidth, uiHeight, bDummy );
-#endif
   UInt uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
 
@@ -2233,397 +2247,128 @@
 #endif
 
+
 Void
-TEncSearch::xSetIntraResultQT( TComDataCU* pcCU,
-                              UInt        uiTrDepth,
-                              UInt        uiAbsPartIdx,
-                              Bool        bLumaOnly,
-                              TComYuv*    pcRecoYuv )
+TEncSearch::xSetIntraResultLumaQT(TComYuv* pcRecoYuv, TComTU &rTu)
 {
-  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  TComDataCU *pcCU        = rTu.getCU();
+  const UInt uiTrDepth    = rTu.GetTransformDepthRel();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
   UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
   if(  uiTrMode == uiTrDepth )
   {
-    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
     UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-    
-    Bool bSkipChroma  = false;
-    Bool bChromaSame  = false;
-    if( !bLumaOnly && uiLog2TrSize == 2 )
-    {
-      assert( uiTrDepth > 0 );
-      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
-      bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
-      bChromaSame  = true;
-    }
-    
+
     //===== copy transform coefficients =====
-    UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
-    UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
-    TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
-    TCoeff* pcCoeffDstY = pcCU->getCoeffY ()              + ( uiNumCoeffIncY * uiAbsPartIdx );
-    ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+
+    const TComRectangle &tuRect=rTu.getRect(COMPONENT_Y);
+    const UInt coeffOffset = rTu.getCoefficientOffset(COMPONENT_Y);
+    const UInt numCoeffInBlock = tuRect.width * tuRect.height;
+
+    if (numCoeffInBlock!=0)
+    {
+      const TCoeff* srcCoeff = m_ppcQTTempCoeff[COMPONENT_Y][uiQTLayer] + coeffOffset;
+      TCoeff* destCoeff      = pcCU->getCoeff(COMPONENT_Y) + coeffOffset;
+      ::memcpy( destCoeff, srcCoeff, sizeof(TCoeff)*numCoeffInBlock );
 #if ADAPTIVE_QP_SELECTION
-    Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
-    Int* pcArlCoeffDstY = pcCU->getArlCoeffY ()              + ( uiNumCoeffIncY * uiAbsPartIdx );
-    ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
-#endif
-    if( !bLumaOnly && !bSkipChroma )
-    {
-      UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
-      UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
-      TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      TCoeff* pcCoeffDstU = pcCU->getCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
-      TCoeff* pcCoeffDstV = pcCU->getCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
-      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
-      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+      const TCoeff* srcArlCoeff = m_ppcQTTempArlCoeff[COMPONENT_Y][ uiQTLayer ] + coeffOffset;
+      TCoeff* destArlCoeff      = pcCU->getArlCoeff (COMPONENT_Y)               + coeffOffset;
+      ::memcpy( destArlCoeff, srcArlCoeff, sizeof( TCoeff ) * numCoeffInBlock );
+#endif
+      m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartComponent( COMPONENT_Y, pcRecoYuv, uiAbsPartIdx, tuRect.width, tuRect.height );
+    }
+
+  }
+  else
+  {
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xSetIntraResultLumaQT( pcRecoYuv, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
+  }
+}
+
+
+Void
+TEncSearch::xStoreIntraResultQT(const ComponentID compID, TComTU &rTu )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiTrDepth = rTu.GetTransformDepthRel();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if ( compID==COMPONENT_Y || uiTrMode == uiTrDepth )
+  {
+    assert(uiTrMode == uiTrDepth);
+    const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+    const UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    if (rTu.ProcessComponentSection(compID))
+    {
+      const TComRectangle &tuRect=rTu.getRect(compID);
+
+      //===== copy transform coefficients =====
+      const UInt uiNumCoeff    = tuRect.width * tuRect.height;
+      TCoeff* pcCoeffSrc = m_ppcQTTempCoeff[compID] [ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+      TCoeff* pcCoeffDst = m_pcQTTempTUCoeff[compID];
+
+      ::memcpy( pcCoeffDst, pcCoeffSrc, sizeof( TCoeff ) * uiNumCoeff );
 #if ADAPTIVE_QP_SELECTION
-      Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      Int* pcArlCoeffDstU = pcCU->getArlCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
-      Int* pcArlCoeffDstV = pcCU->getArlCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
-      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
-      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
-#endif
-    }
-    
-    //===== copy reconstruction =====
-    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartLuma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
-    if( !bLumaOnly && !bSkipChroma )
-    {
-      UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
-      m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
-    }
-  }
-  else
-  {
-    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
-    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
-    {
-      xSetIntraResultQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, bLumaOnly, pcRecoYuv );
+      TCoeff* pcArlCoeffSrc = m_ppcQTTempArlCoeff[compID] [ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+      TCoeff* pcArlCoeffDst = m_ppcQTTempTUArlCoeff[compID];
+      ::memcpy( pcArlCoeffDst, pcArlCoeffSrc, sizeof( TCoeff ) * uiNumCoeff );
+#endif
+      //===== copy reconstruction =====
+      m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartComponent( compID, &m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, tuRect.width, tuRect.height );
     }
   }
 }
 
+
 Void
-TEncSearch::xStoreIntraResultQT( TComDataCU* pcCU,
-                                UInt        uiTrDepth,
-                                UInt        uiAbsPartIdx,
-                                Bool        bLumaOnly )
+TEncSearch::xLoadIntraResultQT(const ComponentID compID, TComTU &rTu)
 {
-  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
-  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
-  assert(  uiTrMode == uiTrDepth );
-  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-  UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-
-  Bool bSkipChroma  = false;
-  Bool bChromaSame  = false;
-  if( !bLumaOnly && uiLog2TrSize == 2 )
-  {
-    assert( uiTrDepth > 0 );
-    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
-    bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
-    bChromaSame  = true;
-  }
-
-  //===== copy transform coefficients =====
-  UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
-  UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
-  TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
-  TCoeff* pcCoeffDstY = m_pcQTTempTUCoeffY;
-
-  ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiTrDepth = rTu.GetTransformDepthRel();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if ( compID==COMPONENT_Y || uiTrMode == uiTrDepth )
+  {
+    assert(uiTrMode == uiTrDepth);
+    const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+    const UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    const UInt uiZOrder     = pcCU->getZorderIdxInCtu() + uiAbsPartIdx;
+
+    if (rTu.ProcessComponentSection(compID))
+    {
+      const TComRectangle &tuRect=rTu.getRect(compID);
+
+      //===== copy transform coefficients =====
+      const UInt uiNumCoeff = tuRect.width * tuRect.height;
+      TCoeff* pcCoeffDst = m_ppcQTTempCoeff[compID] [ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+      TCoeff* pcCoeffSrc = m_pcQTTempTUCoeff[compID];
+
+      ::memcpy( pcCoeffDst, pcCoeffSrc, sizeof( TCoeff ) * uiNumCoeff );
 #if ADAPTIVE_QP_SELECTION
-  Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
-  Int* pcArlCoeffDstY = m_ppcQTTempTUArlCoeffY;
-  ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
-#endif
-  if( !bLumaOnly && !bSkipChroma )
-  {
-    UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
-    UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
-    TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    TCoeff* pcCoeffDstU = m_pcQTTempTUCoeffCb;
-    TCoeff* pcCoeffDstV = m_pcQTTempTUCoeffCr;
-    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
-    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
-#if ADAPTIVE_QP_SELECTION
-    Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    Int* pcArlCoeffDstU = m_ppcQTTempTUArlCoeffCb;
-    Int* pcArlCoeffDstV = m_ppcQTTempTUArlCoeffCr;
-    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
-    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
-#endif
-  }
-
-  //===== copy reconstruction =====
-  m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartLuma( &m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
-
-  if( !bLumaOnly && !bSkipChroma )
-  {
-    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
-    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( &m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
-  }
-}
-
-Void
-TEncSearch::xLoadIntraResultQT( TComDataCU* pcCU,
-                               UInt        uiTrDepth,
-                               UInt        uiAbsPartIdx,
-                               Bool        bLumaOnly )
-{
-  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
-  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
-  assert(  uiTrMode == uiTrDepth );
-  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-  UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-
-  Bool bSkipChroma  = false;
-  Bool bChromaSame  = false;
-  if( !bLumaOnly && uiLog2TrSize == 2 )
-  {
-    assert( uiTrDepth > 0 );
-    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
-    bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
-    bChromaSame  = true;
-  }
-
-  //===== copy transform coefficients =====
-  UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
-  UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
-  TCoeff* pcCoeffDstY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
-  TCoeff* pcCoeffSrcY = m_pcQTTempTUCoeffY;
-
-  ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
-#if ADAPTIVE_QP_SELECTION
-  Int* pcArlCoeffDstY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
-  Int* pcArlCoeffSrcY = m_ppcQTTempTUArlCoeffY;
-  ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
-#endif
-  if( !bLumaOnly && !bSkipChroma )
-  {
-    UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
-    UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
-    TCoeff* pcCoeffDstU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    TCoeff* pcCoeffDstV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    TCoeff* pcCoeffSrcU = m_pcQTTempTUCoeffCb;
-    TCoeff* pcCoeffSrcV = m_pcQTTempTUCoeffCr;
-    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
-    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
-#if ADAPTIVE_QP_SELECTION
-    Int* pcArlCoeffDstU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    Int* pcArlCoeffDstV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    Int* pcArlCoeffSrcU = m_ppcQTTempTUArlCoeffCb;
-    Int* pcArlCoeffSrcV = m_ppcQTTempTUArlCoeffCr;
-    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
-    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
-#endif
-  }
-
-  //===== copy reconstruction =====
-  m_pcQTTempTransformSkipTComYuv.copyPartToPartLuma( &m_pcQTTempTComYuv[ uiQTLayer ] , uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
-
-  if( !bLumaOnly && !bSkipChroma )
-  {
-    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
-    m_pcQTTempTransformSkipTComYuv.copyPartToPartChroma( &m_pcQTTempTComYuv[ uiQTLayer ], uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
-  }
-
-  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
-  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
-  Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
-  UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
-  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
-  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
-  Pel* pRecQt     = piRecQt;
-  Pel* pRecIPred  = piRecIPred;
-  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-  {
-    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-    {
-      pRecIPred[ uiX ] = pRecQt   [ uiX ];
-    }
-    pRecQt    += uiRecQtStride;
-    pRecIPred += uiRecIPredStride;
-  }
-
-  if( !bLumaOnly && !bSkipChroma )
-  {
-    piRecIPred = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
-    piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx );
-    pRecQt     = piRecQt;
-    pRecIPred  = piRecIPred;
-    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-    {
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        pRecIPred[ uiX ] = pRecQt[ uiX ];
-      }
-      pRecQt    += uiRecQtStride;
-      pRecIPred += uiRecIPredStride;
-    }
-
-    piRecIPred = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
-    piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx );
-    pRecQt     = piRecQt;
-    pRecIPred  = piRecIPred;
-    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-    {
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        pRecIPred[ uiX ] = pRecQt[ uiX ];
-      }
-      pRecQt    += uiRecQtStride;
-      pRecIPred += uiRecIPredStride;
-    }
-  }
-}
-
-Void
-TEncSearch::xStoreIntraResultChromaQT( TComDataCU* pcCU,
-                                      UInt        uiTrDepth,
-                                      UInt        uiAbsPartIdx,
-                                      UInt        stateU0V1Both2 )
-{
-  UInt uiFullDepth = pcCU->getDepth(0) + uiTrDepth;
-  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
-  if(  uiTrMode == uiTrDepth )
-  {
-    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-
-    Bool bChromaSame = false;
-    if( uiLog2TrSize == 2 )
-    {
-      assert( uiTrDepth > 0 );
-      uiTrDepth --;
-      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth) << 1 );
-      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
-      {
-        return;
-      }
-      bChromaSame = true;
-    }
-
-    //===== copy transform coefficients =====
-    UInt uiNumCoeffC    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
-    if( !bChromaSame )
-    {
-      uiNumCoeffC     >>= 2;
-    }
-    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
-    if(stateU0V1Both2 == 0 || stateU0V1Both2 == 2)
-    {
-      TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      TCoeff* pcCoeffDstU = m_pcQTTempTUCoeffCb;
-      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
-
-#if ADAPTIVE_QP_SELECTION    
-      Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      Int* pcArlCoeffDstU = m_ppcQTTempTUArlCoeffCb;
-      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
-#endif
-    }
-    if(stateU0V1Both2 == 1 || stateU0V1Both2 == 2)
-    {
-      TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      TCoeff* pcCoeffDstV = m_pcQTTempTUCoeffCr;
-      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
-#if ADAPTIVE_QP_SELECTION    
-      Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      Int* pcArlCoeffDstV = m_ppcQTTempTUArlCoeffCr;
-      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
-#endif
-    }
-
-    //===== copy reconstruction =====
-    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
-    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma(&m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma, stateU0V1Both2 );
-  }
-}
-
-
-Void
-TEncSearch::xLoadIntraResultChromaQT( TComDataCU* pcCU,
-                                     UInt        uiTrDepth,
-                                     UInt        uiAbsPartIdx,
-                                     UInt        stateU0V1Both2 )
-{
-  UInt uiFullDepth = pcCU->getDepth(0) + uiTrDepth;
-  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
-  if(  uiTrMode == uiTrDepth )
-  {
-    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-
-    Bool bChromaSame = false;
-    if( uiLog2TrSize == 2 )
-    {
-      assert( uiTrDepth > 0 );
-      uiTrDepth --;
-      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
-      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
-      {
-        return;
-      }
-      bChromaSame = true;
-    }
-
-    //===== copy transform coefficients =====
-    UInt uiNumCoeffC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
-    if( !bChromaSame )
-    {
-      uiNumCoeffC >>= 2;
-    }
-    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
-
-    if(stateU0V1Both2 ==0 || stateU0V1Both2 == 2)
-    {
-      TCoeff* pcCoeffDstU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      TCoeff* pcCoeffSrcU = m_pcQTTempTUCoeffCb;
-      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
-#if ADAPTIVE_QP_SELECTION    
-      Int* pcArlCoeffDstU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      Int* pcArlCoeffSrcU = m_ppcQTTempTUArlCoeffCb;
-      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
-#endif
-    }
-    if(stateU0V1Both2 ==1 || stateU0V1Both2 == 2)
-    {
-      TCoeff* pcCoeffDstV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      TCoeff* pcCoeffSrcV = m_pcQTTempTUCoeffCr;
-      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
-#if ADAPTIVE_QP_SELECTION    
-      Int* pcArlCoeffDstV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-      Int* pcArlCoeffSrcV = m_ppcQTTempTUArlCoeffCr;       
-      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
-#endif
-    }
-
-    //===== copy reconstruction =====
-    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
-    m_pcQTTempTransformSkipTComYuv.copyPartToPartChroma( &m_pcQTTempTComYuv[ uiQTLayer ], uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma, stateU0V1Both2);
-
-    UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
-    UInt    uiWidth           = pcCU->getWidth   ( 0 ) >> (uiTrDepth + 1);
-    UInt    uiHeight          = pcCU->getHeight  ( 0 ) >> (uiTrDepth + 1);
-    UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getCStride  ();
-    UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride  ();
-
-    if(stateU0V1Both2 ==0 || stateU0V1Both2 == 2)
-    {
-      Pel* piRecIPred = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
-      Pel* piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx );
-      Pel* pRecQt     = piRecQt;
-      Pel* pRecIPred  = piRecIPred;
+      TCoeff* pcArlCoeffDst = m_ppcQTTempArlCoeff[compID] [ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+      TCoeff* pcArlCoeffSrc = m_ppcQTTempTUArlCoeff[compID];
+      ::memcpy( pcArlCoeffDst, pcArlCoeffSrc, sizeof( TCoeff ) * uiNumCoeff );
+#endif
+      //===== copy reconstruction =====
+      m_pcQTTempTransformSkipTComYuv.copyPartToPartComponent( compID, &m_pcQTTempTComYuv[ uiQTLayer ], uiAbsPartIdx, tuRect.width, tuRect.height );
+
+      Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), uiZOrder );
+      UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride (compID);
+      Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getAddr( compID, uiAbsPartIdx );
+      UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride  (compID);
+      UInt    uiWidth           = tuRect.width;
+      UInt    uiHeight          = tuRect.height;
+      Pel* pRecQt               = piRecQt;
+      Pel* pRecIPred            = piRecIPred;
       for( UInt uiY = 0; uiY < uiHeight; uiY++ )
       {
         for( UInt uiX = 0; uiX < uiWidth; uiX++ )
         {
-          pRecIPred[ uiX ] = pRecQt[ uiX ];
+          pRecIPred[ uiX ] = pRecQt   [ uiX ];
         }
         pRecQt    += uiRecQtStride;
@@ -2631,62 +2376,118 @@
       }
     }
-    if(stateU0V1Both2 == 1 || stateU0V1Both2 == 2)
-    {
-      Pel* piRecIPred = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
-      Pel* piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx );
-      Pel* pRecQt     = piRecQt;
-      Pel* pRecIPred  = piRecIPred;
-      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
-      {
-        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-        {
-          pRecIPred[ uiX ] = pRecQt[ uiX ];
-        }
-        pRecQt    += uiRecQtStride;
-        pRecIPred += uiRecIPredStride;
-      }
-    }
   }
 }
 
-Void 
-TEncSearch::xRecurIntraChromaCodingQT( TComDataCU*  pcCU, 
-                                      UInt         uiTrDepth,
-                                      UInt         uiAbsPartIdx, 
-                                      TComYuv*     pcOrgYuv, 
-                                      TComYuv*     pcPredYuv, 
-                                      TComYuv*     pcResiYuv, 
-                                      UInt&        ruiDist )
+Void
+TEncSearch::xStoreCrossComponentPredictionResult(       Pel    *pResiDst,
+                                                  const Pel    *pResiSrc,
+                                                        TComTU &rTu,
+                                                  const Int     xOffset,
+                                                  const Int     yOffset,
+                                                  const Int     strideDst,
+                                                  const Int     strideSrc )
 {
-  UInt uiFullDepth = pcCU->getDepth( 0 ) +  uiTrDepth;
-  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
+  const Pel *pSrc = pResiSrc + yOffset * strideSrc + xOffset;
+        Pel *pDst = pResiDst + yOffset * strideDst + xOffset;
+
+  for( Int y = 0; y < rTu.getRect( COMPONENT_Y ).height; y++ )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel) * rTu.getRect( COMPONENT_Y ).width );
+    pDst += strideDst;
+    pSrc += strideSrc;
+  }
+}
+
+Char
+TEncSearch::xCalcCrossComponentPredictionAlpha(       TComTU &rTu,
+                                                const ComponentID compID,
+                                                const Pel*        piResiL,
+                                                const Pel*        piResiC,
+                                                const Int         width,
+                                                const Int         height,
+                                                const Int         strideL,
+                                                const Int         strideC )
+{
+  const Pel *pResiL = piResiL;
+  const Pel *pResiC = piResiC;
+
+        TComDataCU *pCU = rTu.getCU();
+  const Int  absPartIdx = rTu.GetAbsPartIdxTU( compID );
+  const Int diffBitDepth = pCU->getSlice()->getSPS()->getDifferentialLumaChromaBitDepth();
+
+  Char alpha = 0;
+  Int SSxy  = 0;
+  Int SSxx  = 0;
+
+  for( UInt uiY = 0; uiY < height; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < width; uiX++ )
+    {
+      const Pel scaledResiL = rightShift( pResiL[ uiX ], diffBitDepth );
+      SSxy += ( scaledResiL * pResiC[ uiX ] );
+      SSxx += ( scaledResiL * scaledResiL   );
+    }
+
+    pResiL += strideL;
+    pResiC += strideC;
+  }
+
+  if( SSxx != 0 )
+  {
+    Double dAlpha = SSxy / Double( SSxx );
+    alpha = Char(Clip3<Int>(-16, 16, (Int)(dAlpha * 16)));
+
+    static const Char alphaQuant[17] = {0, 1, 1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8};
+
+    alpha = (alpha < 0) ? -alphaQuant[Int(-alpha)] : alphaQuant[Int(alpha)];
+  }
+  pCU->setCrossComponentPredictionAlphaPartRange( alpha, compID, absPartIdx, rTu.GetAbsPartIdxNumParts( compID ) );
+
+  return alpha;
+}
+
+Void
+TEncSearch::xRecurIntraChromaCodingQT(TComYuv*    pcOrgYuv,
+                                      TComYuv*    pcPredYuv,
+                                      TComYuv*    pcResiYuv,
+                                      Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+#if NH_3D_VSO
+                                      Dist&       ruiDist,
+#else
+                                      Distortion& ruiDist,
+#endif
+                                      TComTU&     rTu
+                                      DEBUG_STRING_FN_DECLARE(sDebug))
+{
+  TComDataCU         *pcCU                  = rTu.getCU();
+  const UInt          uiTrDepth             = rTu.GetTransformDepthRel();
+  const UInt          uiAbsPartIdx          = rTu.GetAbsPartIdxTU();
+  const ChromaFormat  format                = rTu.GetChromaFormat();
+  UInt                uiTrMode              = pcCU->getTransformIdx( uiAbsPartIdx );
+  const UInt          numberValidComponents = getNumberValidComponents(format);
+
   if(  uiTrMode == uiTrDepth )
   {
+    if (!rTu.ProcessChannelSection(CHANNEL_TYPE_CHROMA))
+    {
+      return;
+    }
+
+    const UInt uiFullDepth = rTu.GetTransformDepthTotal();
+
     Bool checkTransformSkip = pcCU->getSlice()->getPPS()->getUseTransformSkip();
-    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
-
-    UInt actualTrDepth = uiTrDepth;
-    if( uiLog2TrSize == 2 )
-    {
-      assert( uiTrDepth > 0 );
-      actualTrDepth--;
-      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + actualTrDepth) << 1 );
-      Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
-      if( !bFirstQ )
-      {
-        return;
-      }
-    }
-
-    checkTransformSkip &= (uiLog2TrSize <= 3);
+    checkTransformSkip &= TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(COMPONENT_Cb), pcCU->getSlice()->getPPS()->getPpsRangeExtension().getLog2MaxTransformSkipBlockSize());
+
     if ( m_pcEncCfg->getUseTransformSkipFast() )
     {
-      checkTransformSkip &= (uiLog2TrSize < 3);
+      checkTransformSkip &= TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(COMPONENT_Y), pcCU->getSlice()->getPPS()->getPpsRangeExtension().getLog2MaxTransformSkipBlockSize());
+
       if (checkTransformSkip)
       {
         Int nbLumaSkip = 0;
-        for(UInt absPartIdxSub = uiAbsPartIdx; absPartIdxSub < uiAbsPartIdx + 4; absPartIdxSub ++)
-        {
-          nbLumaSkip += pcCU->getTransformSkip(absPartIdxSub, TEXT_LUMA);
+        const UInt maxAbsPartIdxSub=uiAbsPartIdx + (rTu.ProcessingAllQuadrants(COMPONENT_Cb)?1:4);
+        for(UInt absPartIdxSub = uiAbsPartIdx; absPartIdxSub < maxAbsPartIdxSub; absPartIdxSub ++)
+        {
+          nbLumaSkip += pcCU->getTransformSkip(absPartIdxSub, COMPONENT_Y);
         }
         checkTransformSkip &= (nbLumaSkip > 0);
@@ -2694,45 +2495,89 @@
     }
 
-    if(checkTransformSkip)
-    {
-        //use RDO to decide whether Cr/Cb takes TS
-          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
-
-        for(Int chromaId = 0; chromaId < 2; chromaId ++)
-        {
-          Double  dSingleCost    = MAX_DOUBLE;
-          Int     bestModeId     = 0;
-          UInt    singleDistC    = 0;
-          UInt    singleCbfC     = 0;
-          UInt    singleDistCTmp = 0;
-          Double  singleCostTmp  = 0;
-          UInt    singleCbfCTmp  = 0;
-
-          Int     default0Save1Load2 = 0;
-          Int     firstCheckId       = 0;
-
-          for(Int chromaModeId = firstCheckId; chromaModeId < 2; chromaModeId ++)
+
+    for (UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      DEBUG_STRING_NEW(sDebugBestMode)
+
+      //use RDO to decide whether Cr/Cb takes TS
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
+
+      const Bool splitIntoSubTUs = rTu.getRect(compID).width != rTu.getRect(compID).height;
+
+      TComTURecurse TUIterator(rTu, false, (splitIntoSubTUs ? TComTU::VERTICAL_SPLIT : TComTU::DONT_SPLIT), true, compID);
+
+      const UInt partIdxesPerSubTU = TUIterator.GetAbsPartIdxNumParts(compID);
+
+      do
+      {
+        const UInt subTUAbsPartIdx   = TUIterator.GetAbsPartIdxTU(compID);
+
+        Double     dSingleCost               = MAX_DOUBLE;
+        Int        bestModeId                = 0;
+#if NH_3D_VSO
+        Dist       singleDistC               = 0;
+#else
+        Distortion singleDistC               = 0;
+#endif
+        UInt       singleCbfC                = 0;
+#if NH_3D_VSO
+        Dist       singleDistCTmp            = 0;
+#else
+        Distortion singleDistCTmp            = 0;
+#endif
+        Double     singleCostTmp             = 0;
+        UInt       singleCbfCTmp             = 0;
+        Char       bestCrossCPredictionAlpha = 0;
+        Int        bestTransformSkipMode     = 0;
+
+        const Bool checkCrossComponentPrediction =    (pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, subTUAbsPartIdx) == DM_CHROMA_IDX)
+                                                   &&  pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag()
+                                                   && (pcCU->getCbf(subTUAbsPartIdx,  COMPONENT_Y, uiTrDepth) != 0);
+
+        const Int  crossCPredictionModesToTest = checkCrossComponentPrediction ? 2 : 1;
+        const Int  transformSkipModesToTest    = checkTransformSkip            ? 2 : 1;
+        const Int  totalModesToTest            = crossCPredictionModesToTest * transformSkipModesToTest;
+              Int  currModeId                  = 0;
+              Int  default0Save1Load2          = 0;
+
+        for(Int transformSkipModeId = 0; transformSkipModeId < transformSkipModesToTest; transformSkipModeId++)
+        {
+          for(Int crossCPredictionModeId = 0; crossCPredictionModeId < crossCPredictionModesToTest; crossCPredictionModeId++)
           {
-            pcCU->setTransformSkipSubParts ( chromaModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth); 
-            if(chromaModeId == firstCheckId)
+            pcCU->setCrossComponentPredictionAlphaPartRange(0, compID, subTUAbsPartIdx, partIdxesPerSubTU);
+            DEBUG_STRING_NEW(sDebugMode)
+            pcCU->setTransformSkipPartRange( transformSkipModeId, compID, subTUAbsPartIdx, partIdxesPerSubTU );
+            currModeId++;
+
+            const Bool isOneMode  = (totalModesToTest == 1);
+            const Bool isLastMode = (currModeId == totalModesToTest); // currModeId is indexed from 1
+
+            if (isOneMode)
             {
-              default0Save1Load2 = 1;
+              default0Save1Load2 = 0;
+            }
+            else if (!isOneMode && (transformSkipModeId == 0) && (crossCPredictionModeId == 0))
+            {
+              default0Save1Load2 = 1; //save prediction on first mode
             }
             else
             {
-              default0Save1Load2 = 2;
+              default0Save1Load2 = 2; //load it on subsequent modes
             }
+
             singleDistCTmp = 0;
-            xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, chromaId ,default0Save1Load2);
-            singleCbfCTmp = pcCU->getCbf( uiAbsPartIdx, (TextType)(chromaId + 2), uiTrDepth);
-            
-            if(chromaModeId == 1 && singleCbfCTmp == 0)
+
+            xIntraCodingTUBlock( pcOrgYuv, pcPredYuv, pcResiYuv, resiLuma, (crossCPredictionModeId != 0), singleDistCTmp, compID, TUIterator DEBUG_STRING_PASS_INTO(sDebugMode), default0Save1Load2);
+            singleCbfCTmp = pcCU->getCbf( subTUAbsPartIdx, compID, uiTrDepth);
+
+            if (  ((crossCPredictionModeId == 1) && (pcCU->getCrossComponentPredictionAlpha(subTUAbsPartIdx, compID) == 0))
+               || ((transformSkipModeId    == 1) && (singleCbfCTmp == 0))) //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
             {
-              //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
               singleCostTmp = MAX_DOUBLE;
             }
-            else
+            else if (!isOneMode)
             {
-              UInt bitsTmp = xGetIntraBitsQTChroma( pcCU,uiTrDepth, uiAbsPartIdx,chromaId + 2, false );
+              UInt bitsTmp = xGetIntraBitsQTChroma( TUIterator, compID, false );
               singleCostTmp  = m_pcRdCost->calcRdCost( bitsTmp, singleDistCTmp);
             }
@@ -2740,172 +2585,138 @@
             if(singleCostTmp < dSingleCost)
             {
-              dSingleCost = singleCostTmp;
-              singleDistC = singleDistCTmp;
-              bestModeId  = chromaModeId;
-              singleCbfC  = singleCbfCTmp;
-
-              if(bestModeId == firstCheckId)
+              DEBUG_STRING_SWAP(sDebugBestMode, sDebugMode)
+              dSingleCost               = singleCostTmp;
+              singleDistC               = singleDistCTmp;
+              bestCrossCPredictionAlpha = (crossCPredictionModeId != 0) ? pcCU->getCrossComponentPredictionAlpha(subTUAbsPartIdx, compID) : 0;
+              bestTransformSkipMode     = transformSkipModeId;
+              bestModeId                = currModeId;
+              singleCbfC                = singleCbfCTmp;
+
+              if (!isOneMode && !isLastMode)
               {
-                xStoreIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
-                  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
-                }
+                xStoreIntraResultQT(compID, TUIterator);
+                m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
               }
-            if(chromaModeId == firstCheckId)
+            }
+
+            if (!isOneMode && !isLastMode)
             {
               m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
             }
           }
-
-          if(bestModeId == firstCheckId)
-          {
-            xLoadIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
-            pcCU->setCbfSubParts ( singleCbfC << uiTrDepth, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth(0) + actualTrDepth );
-              m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
-            } 
-          pcCU ->setTransformSkipSubParts( bestModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
-          ruiDist += singleDistC;
-
-          if(chromaId == 0)
-          {
-              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
-            }
-          }
-        }
-    else
-    {
-      pcCU ->setTransformSkipSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
-      pcCU ->setTransformSkipSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
-      xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 0 ); 
-      xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 1 ); 
+        }
+
+        if(bestModeId < totalModesToTest)
+        {
+          xLoadIntraResultQT(compID, TUIterator);
+          pcCU->setCbfPartRange( singleCbfC << uiTrDepth, compID, subTUAbsPartIdx, partIdxesPerSubTU );
+
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+        }
+
+        DEBUG_STRING_APPEND(sDebug, sDebugBestMode)
+        pcCU ->setTransformSkipPartRange                ( bestTransformSkipMode,     compID, subTUAbsPartIdx, partIdxesPerSubTU );
+        pcCU ->setCrossComponentPredictionAlphaPartRange( bestCrossCPredictionAlpha, compID, subTUAbsPartIdx, partIdxesPerSubTU );
+        ruiDist += singleDistC;
+      } while (TUIterator.nextSection(rTu));
+
+      if (splitIntoSubTUs)
+      {
+        offsetSubTUCBFs(rTu, compID);
+      }
     }
   }
   else
   {
-    UInt uiSplitCbfU     = 0;
-    UInt uiSplitCbfV     = 0;
-    UInt uiQPartsDiv     = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
-    UInt uiAbsPartIdxSub = uiAbsPartIdx;
-    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiAbsPartIdxSub += uiQPartsDiv )
-    {
-      xRecurIntraChromaCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist );
-      uiSplitCbfU |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_U, uiTrDepth + 1 );
-      uiSplitCbfV |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_V, uiTrDepth + 1 );
-    }
-    for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
-    {
-      pcCU->getCbf( TEXT_CHROMA_U )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfU << uiTrDepth );
-      pcCU->getCbf( TEXT_CHROMA_V )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfV << uiTrDepth );
+    UInt    uiSplitCbf[MAX_NUM_COMPONENT] = {0,0,0};
+
+    TComTURecurse tuRecurseChild(rTu, false);
+    const UInt uiTrDepthChild   = tuRecurseChild.GetTransformDepthRel();
+    do
+    {
+      DEBUG_STRING_NEW(sChild)
+
+      xRecurIntraChromaCodingQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLuma, ruiDist, tuRecurseChild DEBUG_STRING_PASS_INTO(sChild) );
+
+      DEBUG_STRING_APPEND(sDebug, sChild)
+      const UInt uiAbsPartIdxSub=tuRecurseChild.GetAbsPartIdxTU();
+
+      for(UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+      {
+        uiSplitCbf[ch] |= pcCU->getCbf( uiAbsPartIdxSub, ComponentID(ch), uiTrDepthChild );
+      }
+    } while ( tuRecurseChild.nextSection(rTu) );
+
+
+    UInt uiPartsDiv = rTu.GetAbsPartIdxNumParts();
+    for(UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+    {
+      if (uiSplitCbf[ch])
+      {
+        const UInt flag=1<<uiTrDepth;
+        ComponentID compID=ComponentID(ch);
+        UChar *pBase=pcCU->getCbf( compID );
+        for( UInt uiOffs = 0; uiOffs < uiPartsDiv; uiOffs++ )
+        {
+          pBase[ uiAbsPartIdx + uiOffs ] |= flag;
+        }
+      }
     }
   }
 }
 
+
+
+
 Void
-TEncSearch::xSetIntraResultChromaQT( TComDataCU* pcCU,
-                                    UInt        uiTrDepth,
-                                    UInt        uiAbsPartIdx,
-                                    TComYuv*    pcRecoYuv )
+TEncSearch::xSetIntraResultChromaQT(TComYuv*    pcRecoYuv, TComTU &rTu)
 {
-  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  if (!rTu.ProcessChannelSection(CHANNEL_TYPE_CHROMA))
+  {
+    return;
+  }
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrDepth   = rTu.GetTransformDepthRel();
   UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
   if(  uiTrMode == uiTrDepth )
   {
-    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
     UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-    
-    Bool bChromaSame  = false;
-    if( uiLog2TrSize == 2 )
-    {
-      assert( uiTrDepth > 0 );
-      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
-      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
-      {
-        return;
-      }
-      bChromaSame     = true;
-    }
-    
+
     //===== copy transform coefficients =====
-    UInt uiNumCoeffC    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
-    if( !bChromaSame )
-    {
-      uiNumCoeffC     >>= 2;
-    }
-    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
-    TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    TCoeff* pcCoeffDstU = pcCU->getCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
-    TCoeff* pcCoeffDstV = pcCU->getCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
-    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
-    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
-#if ADAPTIVE_QP_SELECTION    
-    Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
-    Int* pcArlCoeffDstU = pcCU->getArlCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
-    Int* pcArlCoeffDstV = pcCU->getArlCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
-    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
-    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
-#endif
-    
+    const TComRectangle &tuRectCb=rTu.getRect(COMPONENT_Cb);
+    UInt uiNumCoeffC    = tuRectCb.width*tuRectCb.height;//( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    const UInt offset = rTu.getCoefficientOffset(COMPONENT_Cb);
+
+    const UInt numberValidComponents = getNumberValidComponents(rTu.GetChromaFormat());
+    for (UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+    {
+      const ComponentID component = ComponentID(ch);
+      const TCoeff* src           = m_ppcQTTempCoeff[component][uiQTLayer] + offset;//(uiNumCoeffIncC*uiAbsPartIdx);
+      TCoeff* dest                = pcCU->getCoeff(component) + offset;//(uiNumCoeffIncC*uiAbsPartIdx);
+      ::memcpy( dest, src, sizeof(TCoeff)*uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+      TCoeff* pcArlCoeffSrc = m_ppcQTTempArlCoeff[component][ uiQTLayer ] + offset;//( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcArlCoeffDst = pcCU->getArlCoeff(component)                + offset;//( uiNumCoeffIncC * uiAbsPartIdx );
+      ::memcpy( pcArlCoeffDst, pcArlCoeffSrc, sizeof( TCoeff ) * uiNumCoeffC );
+#endif
+    }
+
     //===== copy reconstruction =====
-    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
-    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartComponent( COMPONENT_Cb, pcRecoYuv, uiAbsPartIdx, tuRectCb.width, tuRectCb.height );
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartComponent( COMPONENT_Cr, pcRecoYuv, uiAbsPartIdx, tuRectCb.width, tuRectCb.height );
   }
   else
   {
-    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
-    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
-    {
-      xSetIntraResultChromaQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv );
-    }
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xSetIntraResultChromaQT( pcRecoYuv, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
   }
 }
 
-
-Void 
-TEncSearch::preestChromaPredMode( TComDataCU* pcCU, 
-                                 TComYuv*    pcOrgYuv, 
-                                 TComYuv*    pcPredYuv )
-{
-  UInt  uiWidth     = pcCU->getWidth ( 0 ) >> 1;
-  UInt  uiHeight    = pcCU->getHeight( 0 ) >> 1;
-  UInt  uiStride    = pcOrgYuv ->getCStride();
-  Pel*  piOrgU      = pcOrgYuv ->getCbAddr ( 0 );
-  Pel*  piOrgV      = pcOrgYuv ->getCrAddr ( 0 );
-  Pel*  piPredU     = pcPredYuv->getCbAddr ( 0 );
-  Pel*  piPredV     = pcPredYuv->getCrAddr ( 0 );
-  
-  //===== init pattern =====
-  Bool  bAboveAvail = false;
-  Bool  bLeftAvail  = false;
-  pcCU->getPattern()->initPattern         ( pcCU, 0, 0 );
-  pcCU->getPattern()->initAdiPatternChroma( pcCU, 0, 0, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
-  Int*  pPatChromaU = pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_piYuvExt );
-  Int*  pPatChromaV = pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_piYuvExt );
-  
-  //===== get best prediction modes (using SAD) =====
-  UInt  uiMinMode   = 0;
-  UInt  uiMaxMode   = 4;
-  UInt  uiBestMode  = MAX_UINT;
-  UInt  uiMinSAD    = MAX_UINT;
-  for( UInt uiMode  = uiMinMode; uiMode < uiMaxMode; uiMode++ )
-  {
-    //--- get prediction ---
-    predIntraChromaAng( pPatChromaU, uiMode, piPredU, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
-    predIntraChromaAng( pPatChromaV, uiMode, piPredV, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
-    
-    //--- get SAD ---
-    UInt  uiSAD  = m_pcRdCost->calcHAD(g_bitDepthC, piOrgU, uiStride, piPredU, uiStride, uiWidth, uiHeight );
-    uiSAD       += m_pcRdCost->calcHAD(g_bitDepthC, piOrgV, uiStride, piPredV, uiStride, uiWidth, uiHeight );
-    //--- check ---
-    if( uiSAD < uiMinSAD )
-    {
-      uiMinSAD   = uiSAD;
-      uiBestMode = uiMode;
-    }
-  }
-  
-  //===== set chroma pred mode =====
-  pcCU->setChromIntraDirSubParts( uiBestMode, 0, pcCU->getDepth( 0 ) );
-}
 #if H_3D
 Void TEncSearch::estIntraPredDIS( TComDataCU* pcCU, 
@@ -2968,35 +2779,59 @@
 }
 #endif
-Void 
-TEncSearch::estIntraPredQT( TComDataCU* pcCU, 
-                            TComYuv*    pcOrgYuv, 
-                            TComYuv*    pcPredYuv, 
-                            TComYuv*    pcResiYuv, 
-                            TComYuv*    pcRecoYuv,
-                            UInt&       ruiDistC,
-                            Bool        bLumaOnly
+
+
+
+Void
+TEncSearch::estIntraPredLumaQT(TComDataCU* pcCU,
+                               TComYuv*    pcOrgYuv,
+                               TComYuv*    pcPredYuv,
+                               TComYuv*    pcResiYuv,
+                               TComYuv*    pcRecoYuv,
+                               Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE]
 #if H_3D_DIM
-                          , Bool        bOnlyIVP
-#endif
-                          )
+                             , Bool        bOnlyIVP
+#endif
+
+                               DEBUG_STRING_FN_DECLARE(sDebug))
 {
-  UInt    uiDepth        = pcCU->getDepth(0);
-  UInt    uiNumPU        = pcCU->getNumPartitions();
-  UInt    uiInitTrDepth  = pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1;
-  UInt    uiWidth        = pcCU->getWidth (0) >> uiInitTrDepth;
-  UInt    uiHeight       = pcCU->getHeight(0) >> uiInitTrDepth;
-  UInt    uiQNumParts    = pcCU->getTotalNumPart() >> 2;
-  UInt    uiWidthBit     = pcCU->getIntraSizeIdx(0);
-#if H_3D_VSO
-  Dist    uiOverallDistY = 0;
+  const UInt         uiDepth               = pcCU->getDepth(0);
+  const UInt         uiInitTrDepth         = pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1;
+  const UInt         uiNumPU               = 1<<(2*uiInitTrDepth);
+  const UInt         uiQNumParts           = pcCU->getTotalNumPart() >> 2;
+  const UInt         uiWidthBit            = pcCU->getIntraSizeIdx(0);
+  const ChromaFormat chFmt                 = pcCU->getPic()->getChromaFormat();
+  const UInt         numberValidComponents = getNumberValidComponents(chFmt);
+  const TComSPS     &sps                   = *(pcCU->getSlice()->getSPS());
+  const TComPPS     &pps                   = *(pcCU->getSlice()->getPPS());
+#if NH_3D_VSO
+        Dist         uiOverallDistY        = 0;
 #else
-  UInt    uiOverallDistY = 0;
-#endif
-  UInt    uiOverallDistC = 0;
-  UInt    CandNum;
-  Double  CandCostList[ FAST_UDI_MAX_RDMODE_NUM ];
-  
+        Distortion   uiOverallDistY        = 0;
+#endif
+        UInt         CandNum;
+        Double       CandCostList[ FAST_UDI_MAX_RDMODE_NUM ];
+        Pel          resiLumaPU[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
+
+        Bool    bMaintainResidual[NUMBER_OF_STORED_RESIDUAL_TYPES];
+        for (UInt residualTypeIndex = 0; residualTypeIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; residualTypeIndex++)
+        {
+          bMaintainResidual[residualTypeIndex] = true; //assume true unless specified otherwise
+        }
+
+        bMaintainResidual[RESIDUAL_ENCODER_SIDE] = !(m_pcEncCfg->getUseReconBasedCrossCPredictionEstimate());
+
+  // Lambda calculation at equivalent Qp of 4 is recommended because at that Qp, the quantisation divisor is 1.
+#if FULL_NBIT
+  const Double sqrtLambdaForFirstPass= (m_pcEncCfg->getCostMode()==COST_MIXED_LOSSLESS_LOSSY_CODING && pcCU->getCUTransquantBypass(0)) ?
+                sqrt(0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12) / 3.0)))
+              : m_pcRdCost->getSqrtLambda();
+#else
+  const Double sqrtLambdaForFirstPass= (m_pcEncCfg->getCostMode()==COST_MIXED_LOSSLESS_LOSSY_CODING && pcCU->getCUTransquantBypass(0)) ?
+                sqrt(0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12 - 6 * (sps.getBitDepth(CHANNEL_TYPE_LUMA) - 8)) / 3.0)))
+              : m_pcRdCost->getSqrtLambda();
+#endif
+
   //===== set QP and clear Cbf =====
-  if ( pcCU->getSlice()->getPPS()->getUseDQP() == true)
+  if ( pps.getUseDQP() == true)
   {
     pcCU->setQPSubParts( pcCU->getQP(0), 0, uiDepth );
@@ -3006,23 +2841,28 @@
     pcCU->setQPSubParts( pcCU->getSlice()->getSliceQp(), 0, uiDepth );
   }
-  
+
   //===== loop over partitions =====
-  UInt uiPartOffset = 0;
-  for( UInt uiPU = 0; uiPU < uiNumPU; uiPU++, uiPartOffset += uiQNumParts )
-  {
+  TComTURecurse tuRecurseCU(pcCU, 0);
+  TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);
+
+  do
+  {
+    const UInt uiPartOffset=tuRecurseWithPU.GetAbsPartIdxTU();
+//  for( UInt uiPU = 0, uiPartOffset=0; uiPU < uiNumPU; uiPU++, uiPartOffset += uiQNumParts )
+  //{
     //===== init pattern for luma prediction =====
     Bool bAboveAvail = false;
     Bool bLeftAvail  = false;
-    pcCU->getPattern()->initPattern   ( pcCU, uiInitTrDepth, uiPartOffset );
-    pcCU->getPattern()->initAdiPattern( pcCU, uiPartOffset, uiInitTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+    DEBUG_STRING_NEW(sTemp2)
 
     //===== determine set of modes to be tested (using prediction signal only) =====
     Int numModesAvailable     = 35; //total number of Intra modes
-    Pel* piOrg         = pcOrgYuv ->getLumaAddr( uiPU, uiWidth );
-    Pel* piPred        = pcPredYuv->getLumaAddr( uiPU, uiWidth );
-    UInt uiStride      = pcPredYuv->getStride();
     UInt uiRdModeList[FAST_UDI_MAX_RDMODE_NUM];
-    Int numModesForFullRD = g_aucIntraModeNumFast[ uiWidthBit ];
-
+    Int numModesForFullRD = m_pcEncCfg->getFastUDIUseMPMEnabled()?g_aucIntraModeNumFast_UseMPM[ uiWidthBit ] : g_aucIntraModeNumFast_NotUseMPM[ uiWidthBit ];
+
+    if (tuRecurseWithPU.ProcessComponentSection(COMPONENT_Y))
+    {
+      initIntraPatternChType( tuRecurseWithPU, bAboveAvail, bLeftAvail, COMPONENT_Y, true DEBUG_STRING_PASS_INTO(sTemp2) );
+    }
 #if H_3D_DIM
     if( bOnlyIVP )
@@ -3033,95 +2873,118 @@
     {
 #endif
-      Bool doFastSearch = (numModesForFullRD != numModesAvailable);
-      if (doFastSearch)
-      {
-        assert(numModesForFullRD < numModesAvailable);
-
-        for( Int i=0; i < numModesForFullRD; i++ ) 
-        {
-          CandCostList[ i ] = MAX_DOUBLE;
-        }
-        CandNum = 0;
-
-        for( Int modeIdx = 0; modeIdx < numModesAvailable; modeIdx++ )
-        {
-          UInt uiMode = modeIdx;
-
-          predIntraLumaAng( pcCU->getPattern(), uiMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
-#if H_3D_VSO // M34
-          Dist uiSad; 
-          if ( m_pcRdCost->getUseVSO() )
-          {
-            if ( m_pcRdCost->getUseEstimatedVSD() )
-            {          
-              uiSad = (Dist) ( m_pcRdCost->getDistPartVSD( pcCU, uiPartOffset, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, true ) );
-            }
-            else
-            {    
-              uiSad = m_pcRdCost->getDistPartVSO(pcCU, uiPartOffset, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, true );
-            }
+
+    Bool doFastSearch = (numModesForFullRD != numModesAvailable);
+    if (doFastSearch)
+    {
+      assert(numModesForFullRD < numModesAvailable);
+
+      for( Int i=0; i < numModesForFullRD; i++ )
+      {
+        CandCostList[ i ] = MAX_DOUBLE;
+      }
+      CandNum = 0;
+
+      const TComRectangle &puRect=tuRecurseWithPU.getRect(COMPONENT_Y);
+      const UInt uiAbsPartIdx=tuRecurseWithPU.GetAbsPartIdxTU();
+
+      Pel* piOrg         = pcOrgYuv ->getAddr( COMPONENT_Y, uiAbsPartIdx );
+      Pel* piPred        = pcPredYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
+      UInt uiStride      = pcPredYuv->getStride( COMPONENT_Y );
+      DistParam distParam;
+      const Bool bUseHadamard=pcCU->getCUTransquantBypass(0) == 0;
+      m_pcRdCost->setDistParam(distParam, sps.getBitDepth(CHANNEL_TYPE_LUMA), piOrg, uiStride, piPred, uiStride, puRect.width, puRect.height, bUseHadamard);
+      distParam.bApplyWeight = false;
+      for( Int modeIdx = 0; modeIdx < numModesAvailable; modeIdx++ )
+      {
+        UInt       uiMode = modeIdx;
+#if !NH_3D_VSO
+        Distortion uiSad  = 0;
+#endif
+
+        const Bool bUseFilter=TComPrediction::filteringIntraReferenceSamples(COMPONENT_Y, uiMode, puRect.width, puRect.height, chFmt, sps.getSpsRangeExtension().getIntraSmoothingDisabledFlag());
+
+        predIntraAng( COMPONENT_Y, uiMode, piOrg, uiStride, piPred, uiStride, tuRecurseWithPU, bAboveAvail, bLeftAvail, bUseFilter, TComPrediction::UseDPCMForFirstPassIntraEstimation(tuRecurseWithPU, uiMode) );
+#if NH_3D_VSO // M34
+        Dist uiSad;           
+        if ( m_pcRdCost->getUseVSO() )
+        {
+          if ( m_pcRdCost->getUseEstimatedVSD() )
+          {          
+            uiSad = (Dist) ( m_pcRdCost->getDistPartVSD( pcCU, uiPartOffset, distParam.bitDepth , piPred, uiStride, piOrg, uiStride, distParam.iCols, distParam.iRows, true ) );
           }
           else
-          {
-            uiSad = m_pcRdCost->calcHAD(g_bitDepthY, piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+          {    
+            uiSad = m_pcRdCost->getDistPartVSO( pcCU, uiPartOffset, distParam.bitDepth , piPred, uiStride, piOrg, uiStride, distParam.iCols, distParam.iRows, true );
           }
+        }
+        else
+        {
+          uiSad = distParam.DistFunc(&distParam);
+        }
 #else        
-          // use hadamard transform here
-          UInt uiSad = m_pcRdCost->calcHAD(g_bitDepthY, piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
-#endif
-
-          UInt   iModeBits = xModeBitsIntra( pcCU, uiMode, uiPU, uiPartOffset, uiDepth, uiInitTrDepth );
-#if H_3D_VSO // M35
-          Double dLambda;
-          if ( m_pcRdCost->getUseLambdaScaleVSO() )
-          {
-            dLambda = m_pcRdCost->getUseRenModel() ? m_pcRdCost->getLambdaVSO() : m_pcRdCost->getSqrtLambdaVSO();
-          }
-          else        
-          {
-            dLambda = m_pcRdCost->getSqrtLambda();        
-          }
-
-          Double cost      = (Double)uiSad + (Double)iModeBits * dLambda;
+        // use hadamard transform here
+        uiSad+=distParam.DistFunc(&distParam);
+#endif
+
+        UInt   iModeBits = 0;
+
+        // NB xModeBitsIntra will not affect the mode for chroma that may have already been pre-estimated.
+        iModeBits+=xModeBitsIntra( pcCU, uiMode, uiPartOffset, uiDepth, CHANNEL_TYPE_LUMA );
+
+#if NH_3D_VSO // M35
+        Double dLambda;
+        if ( m_pcRdCost->getUseLambdaScaleVSO() )
+        {
+          dLambda = m_pcRdCost->getUseRenModel() ? m_pcRdCost->getLambdaVSO() : sqrtLambdaForFirstPass;
+        }
+        else        
+        {
+          dLambda = m_pcRdCost->getSqrtLambda();        
+        }
+
+        Double cost      = (Double)uiSad + (Double)iModeBits * dLambda;
 #else
-          Double cost      = (Double)uiSad + (Double)iModeBits * m_pcRdCost->getSqrtLambda();
-#endif
-
-          CandNum += xUpdateCandList( uiMode, cost, numModesForFullRD, uiRdModeList, CandCostList );
-        }
-
-#if FAST_UDI_USE_MPM
-        Int uiPreds[3] = {-1, -1, -1};
-        Int iMode = -1;
-        Int numCand = pcCU->getIntraDirLumaPredictor( uiPartOffset, uiPreds, &iMode );
-        if( iMode >= 0 )
-        {
-          numCand = iMode;
-        }
-
-        for( Int j=0; j < numCand; j++)
-
-        {
-          Bool mostProbableModeIncluded = false;
-          Int mostProbableMode = uiPreds[j];
-
-          for( Int i=0; i < numModesForFullRD; i++)
-          {
-            mostProbableModeIncluded |= (mostProbableMode == uiRdModeList[i]);
-          }
-          if (!mostProbableModeIncluded)
-          {
-            uiRdModeList[numModesForFullRD++] = mostProbableMode;
-          }
-        }
-#endif // FAST_UDI_USE_MPM
-      }
-      else
-      {
+        Double cost      = (Double)uiSad + (Double)iModeBits * sqrtLambdaForFirstPass;
+#endif
+
+#if DEBUG_INTRA_SEARCH_COSTS
+        std::cout << "1st pass mode " << uiMode << " SAD = " << uiSad << ", mode bits = " << iModeBits << ", cost = " << cost << "\n";
+#endif
+
+        CandNum += xUpdateCandList( uiMode, cost, numModesForFullRD, uiRdModeList, CandCostList );
+      }
+
+      if (m_pcEncCfg->getFastUDIUseMPMEnabled())
+      {
+      Int uiPreds[NUM_MOST_PROBABLE_MODES] = {-1, -1, -1};
+
+      Int iMode = -1;
+      pcCU->getIntraDirPredictor( uiPartOffset, uiPreds, COMPONENT_Y, &iMode );
+
+      const Int numCand = ( iMode >= 0 ) ? iMode : Int(NUM_MOST_PROBABLE_MODES);
+
+      for( Int j=0; j < numCand; j++)
+      {
+        Bool mostProbableModeIncluded = false;
+        Int mostProbableMode = uiPreds[j];
+
         for( Int i=0; i < numModesForFullRD; i++)
         {
-          uiRdModeList[i] = i;
-        }
-      }
+          mostProbableModeIncluded |= (mostProbableMode == uiRdModeList[i]);
+        }
+        if (!mostProbableModeIncluded)
+        {
+          uiRdModeList[numModesForFullRD++] = mostProbableMode;
+        }
+      }
+    }
+    }
+    else
+    {
+      for( Int i=0; i < numModesForFullRD; i++)
+      {
+        uiRdModeList[i] = i;
+      }
+    }
 #if H_3D_DIM
     }
@@ -3240,4 +3103,6 @@
     }
 #endif
+
+
     //===== check modes (using r-d costs) =====
 #if HHI_RQT_INTRA_SPEEDUP_MOD
@@ -3245,6 +3110,6 @@
     Double dSecondBestPUCost = MAX_DOUBLE;
 #endif
-
-    UInt    uiBestPUMode  = 0;
+    DEBUG_STRING_NEW(sPU)
+    UInt       uiBestPUMode  = 0;
 #if H_3D_FAST_INTRA_SDC
     UInt    uiBestPUModeConv  = 0;
@@ -3253,11 +3118,10 @@
 #endif
 
-#if H_3D_VSO
-    Dist    uiBestPUDistY = 0;
+#if NH_3D_VSO
+    Dist       uiBestPUDistY = 0;
 #else
-    UInt    uiBestPUDistY = 0;
-#endif
-    UInt    uiBestPUDistC = 0;
-    Double  dBestPUCost   = MAX_DOUBLE;
+    Distortion uiBestPUDistY = 0;
+#endif
+    Double     dBestPUCost   = MAX_DOUBLE;
 
 #if H_3D_FAST_INTRA_SDC
@@ -3266,5 +3130,4 @@
     UInt rdSDC = m_pcEncCfg->getIsDepth() ? numModesForFullRD : 0;
 #endif
-
 #if H_3D_DIM_SDC
     Bool    bBestUseSDC   = false;
@@ -3274,10 +3137,21 @@
     for( UInt uiMode = 0; uiMode < numModesForFullRD + rdSDC; uiMode++ )
 #else
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+    UInt max=numModesForFullRD;
+
+    if (DebugOptionList::ForceLumaMode.isSet())
+    {
+      max=0;  // we are forcing a direction, so don't bother with mode check
+    }
+    for ( UInt uiMode = 0; uiMode < max; uiMode++)
+#else
     for( UInt uiMode = 0; uiMode < numModesForFullRD; uiMode++ )
+#endif
+
 #endif
     {
       // set luma prediction mode
 #if !H_3D_FAST_INTRA_SDC
-      UInt uiOrgMode = uiRdModeList[uiMode];  
+      UInt uiOrgMode = uiRdModeList[uiMode];
 #endif
 
@@ -3305,5 +3179,5 @@
 #endif
 
-      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+      pcCU->setIntraDirSubParts ( CHANNEL_TYPE_LUMA, uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
 
 #if H_3D_DIM_SDC
@@ -3352,5 +3226,4 @@
           }
 #endif
-
 #if H_3D_DIM_ENC || H_3D_DIM_SDC
           Bool bTestZeroResi = false;
@@ -3371,20 +3244,21 @@
           {
 #endif
-            // set context models
-            m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-
-            // determine residual for partition
-#if H_3D_VSO
-            Dist   uiPUDistY = 0;
+
+      DEBUG_STRING_NEW(sMode)
+      // set context models
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+
+      // determine residual for partition
+#if NH_3D_VSO
+      Dist       uiPUDistY = 0;
 #else
-            UInt   uiPUDistY = 0;
-#endif
-            UInt   uiPUDistC = 0;
-            Double dPUCost   = 0.0;
-#if H_3D_VSO // M36
-            if( m_pcRdCost->getUseRenModel() )
-            {
-              m_pcRdCost->setRenModelData( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight );
-            }
+      Distortion uiPUDistY = 0;
+#endif
+      Double     dPUCost   = 0.0;
+#if NH_3D_VSO // M36
+      if( m_pcRdCost->getUseRenModel() )
+      {
+        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, pcOrgYuv, &tuRecurseWithPU );
+      }
 #endif
 #if H_3D_DIM_SDC
@@ -3404,4 +3278,5 @@
             {
 #endif
+
 #if HHI_RQT_INTRA_SPEEDUP
 #if H_3D_DIM_ENC
@@ -3417,5 +3292,5 @@
 #endif
 #else
-              xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, true, dPUCost );
+      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, true, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
 #endif
 #else
@@ -3423,5 +3298,5 @@
               xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, dPUCost, (testZeroResi != 0) );
 #else
-              xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, dPUCost );
+      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
 #endif
 #endif
@@ -3430,15 +3305,20 @@
 #endif
 
-            // check r-d cost
-            if( dPUCost < dBestPUCost )
-            {
+
+#if DEBUG_INTRA_SEARCH_COSTS
+      std::cout << "2nd pass [luma,chroma] mode [" << Int(pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiPartOffset)) << "," << Int(pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, uiPartOffset)) << "] cost = " << dPUCost << "\n";
+#endif
+
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+        DEBUG_STRING_SWAP(sPU, sMode)
 #if HHI_RQT_INTRA_SPEEDUP_MOD
-              uiSecondBestMode  = uiBestPUMode;
-              dSecondBestPUCost = dBestPUCost;
-#endif
-              uiBestPUMode  = uiOrgMode;
-              uiBestPUDistY = uiPUDistY;
-              uiBestPUDistC = uiPUDistC;
-              dBestPUCost   = dPUCost;
+        uiSecondBestMode  = uiBestPUMode;
+        dSecondBestPUCost = dBestPUCost;
+#endif
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        dBestPUCost   = dPUCost;
 
 #if H_3D_DIM_SDC
@@ -3458,24 +3338,39 @@
                 bBestUseSDC = false;
 #endif
-                xSetIntraResultQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcRecoYuv );
-
-                UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
-                ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-                ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-                ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-                ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-                ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-                ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-                ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        xSetIntraResultLumaQT( pcRecoYuv, tuRecurseWithPU );
+
+        if (pps.getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
+        {
+          const Int xOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).x0;
+          const Int yOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).y0;
+          for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+          {
+            if (bMaintainResidual[storedResidualIndex])
+            {
+              xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaPU[storedResidualIndex], tuRecurseWithPU, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE );
+            }
+          }
+        }
+
+        UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
+
+        ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        for (UInt component = 0; component < numberValidComponents; component++)
+        {
+          const ComponentID compID = ComponentID(component);
+          ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID  ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+          ::memcpy( m_puhQTTempTransformSkipFlag[compID],  pcCU->getTransformSkip(compID)  + uiPartOffset, uiQPartNum * sizeof( UChar ) );
 #if H_3D_DIM_SDC
               }
 #endif
-            }
+
+        }
+      }
 #if HHI_RQT_INTRA_SPEEDUP_MOD
-            else if( dPUCost < dSecondBestPUCost )
-            {
-              uiSecondBestMode  = uiOrgMode;
-              dSecondBestPUCost = dPUCost;
-            }
+      else if( dPUCost < dSecondBestPUCost )
+      {
+        uiSecondBestMode  = uiOrgMode;
+        dSecondBestPUCost = dPUCost;
+      }
 #endif
 #if H_3D_DIM_ENC || H_3D_DIM_SDC
@@ -3486,4 +3381,5 @@
       } // SDC loop
 #endif
+
     } // Mode loop
 
@@ -3503,35 +3399,45 @@
 #endif
 
-      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      if (DebugOptionList::ForceLumaMode.isSet())
+      {
+        uiOrgMode = DebugOptionList::ForceLumaMode.getInt();
+      }
+#endif
+
+      pcCU->setIntraDirSubParts ( CHANNEL_TYPE_LUMA, uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
 #if H_3D_DIM_SDC
       pcCU->setSDCFlagSubParts(false, uiPartOffset, uiDepth + uiInitTrDepth);
 #endif
 
+      DEBUG_STRING_NEW(sModeTree)
+
       // set context models
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
 
       // determine residual for partition
-#if H_3D_VSO
-      Dist   uiPUDistY = 0;
+#if NH_3D_VSO
+      Dist       uiPUDistY = 0;
 #else
-      UInt   uiPUDistY = 0;
-#endif
-      UInt   uiPUDistC = 0;
-      Double dPUCost   = 0.0;
-#if H_3D_VSO // M37
+      Distortion uiPUDistY = 0;
+#endif
+      Double     dPUCost   = 0.0;
+#if NH_3D_VSO // M37  //check if necessary
       // reset Model
       if( m_pcRdCost->getUseRenModel() )
       {
-        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight );
-      }
-#endif
-      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, false, dPUCost );
+        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, pcOrgYuv, &tuRecurseWithPU );        
+      }
+#endif
+
+      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, false, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sModeTree));
 
       // check r-d cost
       if( dPUCost < dBestPUCost )
       {
+        DEBUG_STRING_SWAP(sPU, sModeTree)
         uiBestPUMode  = uiOrgMode;
         uiBestPUDistY = uiPUDistY;
-        uiBestPUDistC = uiPUDistC;
         dBestPUCost   = dPUCost;
 #if H_3D_DIM_SDC
@@ -3539,22 +3445,37 @@
 #endif
 
-        xSetIntraResultQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcRecoYuv );
-
-        UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
+
+        xSetIntraResultLumaQT( pcRecoYuv, tuRecurseWithPU );
+
+        if (pps.getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
+        {
+          const Int xOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).x0;
+          const Int yOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).y0;
+          for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+          {
+            if (bMaintainResidual[storedResidualIndex])
+            {
+              xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaPU[storedResidualIndex], tuRecurseWithPU, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE );
+            }
+          }
+        }
+
+        const UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
         ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-        ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-        ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-        ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-        ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-        ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-        ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+
+        for (UInt component = 0; component < numberValidComponents; component++)
+        {
+          const ComponentID compID = ComponentID(component);
+          ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID  ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+          ::memcpy( m_puhQTTempTransformSkipFlag[compID],  pcCU->getTransformSkip(compID)  + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        }
       }
     } // Mode loop
 #endif
+
+    DEBUG_STRING_APPEND(sDebug, sPU)
 
     //--- update overall distortion ---
     uiOverallDistY += uiBestPUDistY;
-    uiOverallDistC += uiBestPUDistC;
-
 #if H_3D_DIM_SDC
     if( bBestUseSDC )
@@ -3570,36 +3491,32 @@
     {
 #endif
-      //--- update transform index and cbf ---
-      UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
-      ::memcpy( pcCU->getTransformIdx()       + uiPartOffset, m_puhQTTempTrIdx,  uiQPartNum * sizeof( UChar ) );
-      ::memcpy( pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, m_puhQTTempCbf[0], uiQPartNum * sizeof( UChar ) );
-      ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, m_puhQTTempCbf[1], uiQPartNum * sizeof( UChar ) );
-      ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, m_puhQTTempCbf[2], uiQPartNum * sizeof( UChar ) );
-      ::memcpy( pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, m_puhQTTempTransformSkipFlag[0], uiQPartNum * sizeof( UChar ) );
-      ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, m_puhQTTempTransformSkipFlag[1], uiQPartNum * sizeof( UChar ) );
-      ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, m_puhQTTempTransformSkipFlag[2], uiQPartNum * sizeof( UChar ) );
+
+    //--- update transform index and cbf ---
+    const UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
+    ::memcpy( pcCU->getTransformIdx()       + uiPartOffset, m_puhQTTempTrIdx,  uiQPartNum * sizeof( UChar ) );
+    for (UInt component = 0; component < numberValidComponents; component++)
+    {
+      const ComponentID compID = ComponentID(component);
+      ::memcpy( pcCU->getCbf( compID  ) + uiPartOffset, m_puhQTTempCbf[compID], uiQPartNum * sizeof( UChar ) );
+      ::memcpy( pcCU->getTransformSkip( compID  ) + uiPartOffset, m_puhQTTempTransformSkipFlag[compID ], uiQPartNum * sizeof( UChar ) );
 #if H_3D_DIM_SDC
     }
 #endif
+
+    }
+
     //--- set reconstruction for next intra prediction blocks ---
-    if( uiPU != uiNumPU - 1 )
-    {
-      Bool bSkipChroma  = false;
-      Bool bChromaSame  = false;
-      UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> ( pcCU->getDepth(0) + uiInitTrDepth ) ] + 2;
-      if( !bLumaOnly && uiLog2TrSize == 2 )
-      {
-        assert( uiInitTrDepth  > 0 );
-        bSkipChroma  = ( uiPU != 0 );
-        bChromaSame  = true;
-      }
-
-      UInt    uiCompWidth   = pcCU->getWidth ( 0 ) >> uiInitTrDepth;
-      UInt    uiCompHeight  = pcCU->getHeight( 0 ) >> uiInitTrDepth;
-      UInt    uiZOrder      = pcCU->getZorderIdxInCU() + uiPartOffset;
-      Pel*    piDes         = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
-      UInt    uiDesStride   = pcCU->getPic()->getPicYuvRec()->getStride();
-      Pel*    piSrc         = pcRecoYuv->getLumaAddr( uiPartOffset );
-      UInt    uiSrcStride   = pcRecoYuv->getStride();
+    if( !tuRecurseWithPU.IsLastSection() )
+    {
+      const TComRectangle &puRect=tuRecurseWithPU.getRect(COMPONENT_Y);
+      const UInt  uiCompWidth   = puRect.width;
+      const UInt  uiCompHeight  = puRect.height;
+
+      const UInt  uiZOrder      = pcCU->getZorderIdxInCtu() + uiPartOffset;
+            Pel*  piDes         = pcCU->getPic()->getPicYuvRec()->getAddr( COMPONENT_Y, pcCU->getCtuRsAddr(), uiZOrder );
+      const UInt  uiDesStride   = pcCU->getPic()->getPicYuvRec()->getStride( COMPONENT_Y);
+      const Pel*  piSrc         = pcRecoYuv->getAddr( COMPONENT_Y, uiPartOffset );
+      const UInt  uiSrcStride   = pcRecoYuv->getStride( COMPONENT_Y);
+
       for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
       {
@@ -3609,51 +3526,22 @@
         }
       }
-#if H_3D_VSO // M38
+#if NH_3D_VSO // M38
       // set model
       if( m_pcRdCost->getUseRenModel() )
-      {
-        piSrc = pcRecoYuv->getLumaAddr( uiPartOffset );
-        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, piSrc, uiSrcStride, uiCompWidth, uiCompHeight);
-      }
-#endif
-      if( !bLumaOnly && !bSkipChroma )
-      {
-        if( !bChromaSame )
-        {
-          uiCompWidth   >>= 1;
-          uiCompHeight  >>= 1;
-        }
-        piDes         = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
-        uiDesStride   = pcCU->getPic()->getPicYuvRec()->getCStride();
-        piSrc         = pcRecoYuv->getCbAddr( uiPartOffset );
-        uiSrcStride   = pcRecoYuv->getCStride();
-        for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
-        {
-          for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
-          {
-            piDes[ uiX ] = piSrc[ uiX ];
-          }
-        }
-        piDes         = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
-        piSrc         = pcRecoYuv->getCrAddr( uiPartOffset );
-        for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
-        {
-          for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
-          {
-            piDes[ uiX ] = piSrc[ uiX ];
-          }
-        }
-      }
+      {        
+        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, pcRecoYuv, &tuRecurseWithPU );
+      }
+#endif
     }
 
     //=== update PU data ====
-    pcCU->setLumaIntraDirSubParts     ( uiBestPUMode, uiPartOffset, uiDepth + uiInitTrDepth );
+    pcCU->setIntraDirSubParts     ( CHANNEL_TYPE_LUMA, uiBestPUMode, uiPartOffset, uiDepth + uiInitTrDepth );
 #if H_3D_DIM_SDC
     pcCU->setSDCFlagSubParts          ( bBestUseSDC, uiPartOffset, uiDepth + uiInitTrDepth );
 #endif
-    pcCU->copyToPic                   ( uiDepth, uiPU, uiInitTrDepth );
-  } // PU loop
-  
-  
+
+  } while (tuRecurseWithPU.nextSection(tuRecurseCU));
+
+
   if( uiNumPU > 1 )
   { // set Cbf for all blocks
@@ -3664,171 +3552,230 @@
     for( UInt uiPart = 0; uiPart < 4; uiPart++, uiPartIdx += uiQNumParts )
     {
-      uiCombCbfY |= pcCU->getCbf( uiPartIdx, TEXT_LUMA,     1 );
-      uiCombCbfU |= pcCU->getCbf( uiPartIdx, TEXT_CHROMA_U, 1 );
-      uiCombCbfV |= pcCU->getCbf( uiPartIdx, TEXT_CHROMA_V, 1 );
+      uiCombCbfY |= pcCU->getCbf( uiPartIdx, COMPONENT_Y,  1 );
+      uiCombCbfU |= pcCU->getCbf( uiPartIdx, COMPONENT_Cb, 1 );
+      uiCombCbfV |= pcCU->getCbf( uiPartIdx, COMPONENT_Cr, 1 );
     }
     for( UInt uiOffs = 0; uiOffs < 4 * uiQNumParts; uiOffs++ )
     {
-      pcCU->getCbf( TEXT_LUMA     )[ uiOffs ] |= uiCombCbfY;
-      pcCU->getCbf( TEXT_CHROMA_U )[ uiOffs ] |= uiCombCbfU;
-      pcCU->getCbf( TEXT_CHROMA_V )[ uiOffs ] |= uiCombCbfV;
-    }
-  }
-  
+      pcCU->getCbf( COMPONENT_Y  )[ uiOffs ] |= uiCombCbfY;
+      pcCU->getCbf( COMPONENT_Cb )[ uiOffs ] |= uiCombCbfU;
+      pcCU->getCbf( COMPONENT_Cr )[ uiOffs ] |= uiCombCbfV;
+    }
+  }
+
   //===== reset context models =====
-    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-  
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
   //===== set distortion (rate and r-d costs are determined later) =====
-  ruiDistC                   = uiOverallDistC;
-  pcCU->getTotalDistortion() = uiOverallDistY + uiOverallDistC;
+  pcCU->getTotalDistortion() = uiOverallDistY;
 }
 
 
 
-Void 
-TEncSearch::estIntraPredChromaQT( TComDataCU* pcCU, 
-                                 TComYuv*    pcOrgYuv, 
-                                 TComYuv*    pcPredYuv, 
-                                 TComYuv*    pcResiYuv, 
+
+Void
+TEncSearch::estIntraPredChromaQT(TComDataCU* pcCU,
+                                 TComYuv*    pcOrgYuv,
+                                 TComYuv*    pcPredYuv,
+                                 TComYuv*    pcResiYuv,
                                  TComYuv*    pcRecoYuv,
-                                 UInt        uiPreCalcDistC )
+                                 Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE]
+                                 DEBUG_STRING_FN_DECLARE(sDebug))
 {
-  UInt    uiDepth     = pcCU->getDepth(0);
-  UInt    uiBestMode  = 0;
-  UInt    uiBestDist  = 0;
-  Double  dBestCost   = MAX_DOUBLE;
-  
-  //----- init mode list -----
-  UInt  uiMinMode = 0;
-  UInt  uiModeList[ NUM_CHROMA_MODE ];
-  pcCU->getAllowedChromaDir( 0, uiModeList );
-  UInt  uiMaxMode = NUM_CHROMA_MODE;
-
-  //----- check chroma modes -----
-  for( UInt uiMode = uiMinMode; uiMode < uiMaxMode; uiMode++ )
-  {
-    //----- restore context models -----
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-    
-    //----- chroma coding -----
-    UInt    uiDist = 0;
-    pcCU->setChromIntraDirSubParts  ( uiModeList[uiMode], 0, uiDepth );
-    xRecurIntraChromaCodingQT       ( pcCU,   0, 0, pcOrgYuv, pcPredYuv, pcResiYuv, uiDist );
-    if( pcCU->getSlice()->getPPS()->getUseTransformSkip() )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-    }
-    UInt    uiBits = xGetIntraBitsQT( pcCU,   0, 0, false, true, false );
-    Double  dCost  = m_pcRdCost->calcRdCost( uiBits, uiDist );
-    
-    //----- compare -----
-    if( dCost < dBestCost )
-    {
-      dBestCost   = dCost;
-      uiBestDist  = uiDist;
-      uiBestMode  = uiModeList[uiMode];
-      UInt  uiQPN = pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 );
-      xSetIntraResultChromaQT( pcCU, 0, 0, pcRecoYuv );
-      ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ), uiQPN * sizeof( UChar ) );
-      ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ), uiQPN * sizeof( UChar ) );
-      ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip( TEXT_CHROMA_U ), uiQPN * sizeof( UChar ) );
-      ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip( TEXT_CHROMA_V ), uiQPN * sizeof( UChar ) );
-    }
-  }
-  
-  //----- set data -----
-  UInt  uiQPN = pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 );
-  ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ), m_puhQTTempCbf[1], uiQPN * sizeof( UChar ) );
-  ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ), m_puhQTTempCbf[2], uiQPN * sizeof( UChar ) );
-  ::memcpy( pcCU->getTransformSkip( TEXT_CHROMA_U ), m_puhQTTempTransformSkipFlag[1], uiQPN * sizeof( UChar ) );
-  ::memcpy( pcCU->getTransformSkip( TEXT_CHROMA_V ), m_puhQTTempTransformSkipFlag[2], uiQPN * sizeof( UChar ) );
-  pcCU->setChromIntraDirSubParts( uiBestMode, 0, uiDepth );
-  pcCU->getTotalDistortion      () += uiBestDist - uiPreCalcDistC;
-  
+  const UInt    uiInitTrDepth  = pcCU->getPartitionSize(0) != SIZE_2Nx2N && enable4ChromaPUsInIntraNxNCU(pcOrgYuv->getChromaFormat()) ? 1 : 0;
+
+  TComTURecurse tuRecurseCU(pcCU, 0);
+  TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);
+  const UInt    uiQNumParts    = tuRecurseWithPU.GetAbsPartIdxNumParts();
+  const UInt    uiDepthCU=tuRecurseWithPU.getCUDepth();
+  const UInt    numberValidComponents = pcCU->getPic()->getNumberValidComponents();
+
+  do
+  {
+    UInt       uiBestMode  = 0;
+#if NH_3D_VSO
+    Dist       uiBestDist  = 0;
+#else
+    Distortion uiBestDist  = 0;
+#endif
+    Double     dBestCost   = MAX_DOUBLE;
+
+    //----- init mode list -----
+    if (tuRecurseWithPU.ProcessChannelSection(CHANNEL_TYPE_CHROMA))
+    {
+      UInt uiModeList[FAST_UDI_MAX_RDMODE_NUM];
+      const UInt  uiQPartNum     = uiQNumParts;
+      const UInt  uiPartOffset   = tuRecurseWithPU.GetAbsPartIdxTU();
+      {
+        UInt  uiMinMode = 0;
+        UInt  uiMaxMode = NUM_CHROMA_MODE;
+
+        //----- check chroma modes -----
+        pcCU->getAllowedChromaDir( uiPartOffset, uiModeList );
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+        if (DebugOptionList::ForceChromaMode.isSet())
+        {
+          uiMinMode=DebugOptionList::ForceChromaMode.getInt();
+          if (uiModeList[uiMinMode]==34)
+          {
+            uiMinMode=4; // if the fixed mode has been renumbered because DM_CHROMA covers it, use DM_CHROMA.
+          }
+          uiMaxMode=uiMinMode+1;
+        }
+#endif
+
+        DEBUG_STRING_NEW(sPU)
+
+        for( UInt uiMode = uiMinMode; uiMode < uiMaxMode; uiMode++ )
+        {
+          //----- restore context models -----
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepthCU][CI_CURR_BEST] );
+          
+          DEBUG_STRING_NEW(sMode)
+          //----- chroma coding -----
+#if NH_3D_VSO
+          Dist       uiDist = 0;
+#else
+          Distortion uiDist = 0;
+#endif
+          pcCU->setIntraDirSubParts  ( CHANNEL_TYPE_CHROMA, uiModeList[uiMode], uiPartOffset, uiDepthCU+uiInitTrDepth );
+          xRecurIntraChromaCodingQT       ( pcOrgYuv, pcPredYuv, pcResiYuv, resiLuma, uiDist, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
+
+          if( pcCU->getSlice()->getPPS()->getUseTransformSkip() )
+          {
+            m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepthCU][CI_CURR_BEST] );
+          }
+
+          UInt    uiBits = xGetIntraBitsQT( tuRecurseWithPU, false, true, false );
+          Double  dCost  = m_pcRdCost->calcRdCost( uiBits, uiDist );
+
+          //----- compare -----
+          if( dCost < dBestCost )
+          {
+            DEBUG_STRING_SWAP(sPU, sMode);
+            dBestCost   = dCost;
+            uiBestDist  = uiDist;
+            uiBestMode  = uiModeList[uiMode];
+
+            xSetIntraResultChromaQT( pcRecoYuv, tuRecurseWithPU );
+            for (UInt componentIndex = COMPONENT_Cb; componentIndex < numberValidComponents; componentIndex++)
+            {
+              const ComponentID compID = ComponentID(componentIndex);
+              ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID )+uiPartOffset, uiQPartNum * sizeof( UChar ) );
+              ::memcpy( m_puhQTTempTransformSkipFlag[compID], pcCU->getTransformSkip( compID )+uiPartOffset, uiQPartNum * sizeof( UChar ) );
+              ::memcpy( m_phQTTempCrossComponentPredictionAlpha[compID], pcCU->getCrossComponentPredictionAlpha(compID)+uiPartOffset, uiQPartNum * sizeof( Char ) );
+            }
+          }
+        }
+
+        DEBUG_STRING_APPEND(sDebug, sPU)
+
+        //----- set data -----
+        for (UInt componentIndex = COMPONENT_Cb; componentIndex < numberValidComponents; componentIndex++)
+        {
+          const ComponentID compID = ComponentID(componentIndex);
+          ::memcpy( pcCU->getCbf( compID )+uiPartOffset, m_puhQTTempCbf[compID], uiQPartNum * sizeof( UChar ) );
+          ::memcpy( pcCU->getTransformSkip( compID )+uiPartOffset, m_puhQTTempTransformSkipFlag[compID], uiQPartNum * sizeof( UChar ) );
+          ::memcpy( pcCU->getCrossComponentPredictionAlpha(compID)+uiPartOffset, m_phQTTempCrossComponentPredictionAlpha[compID], uiQPartNum * sizeof( Char ) );
+        }
+      }
+
+      if( ! tuRecurseWithPU.IsLastSection() )
+      {
+        for (UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+        {
+          const ComponentID compID    = ComponentID(ch);
+          const TComRectangle &tuRect = tuRecurseWithPU.getRect(compID);
+          const UInt  uiCompWidth     = tuRect.width;
+          const UInt  uiCompHeight    = tuRect.height;
+          const UInt  uiZOrder        = pcCU->getZorderIdxInCtu() + tuRecurseWithPU.GetAbsPartIdxTU();
+                Pel*  piDes           = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), uiZOrder );
+          const UInt  uiDesStride     = pcCU->getPic()->getPicYuvRec()->getStride( compID);
+          const Pel*  piSrc           = pcRecoYuv->getAddr( compID, uiPartOffset );
+          const UInt  uiSrcStride     = pcRecoYuv->getStride( compID);
+
+          for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+          {
+            for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+            {
+              piDes[ uiX ] = piSrc[ uiX ];
+            }
+          }
+        }
+      }
+
+      pcCU->setIntraDirSubParts( CHANNEL_TYPE_CHROMA, uiBestMode, uiPartOffset, uiDepthCU+uiInitTrDepth );
+      pcCU->getTotalDistortion      () += uiBestDist;
+    }
+
+  } while (tuRecurseWithPU.nextSection(tuRecurseCU));
+
   //----- restore context models -----
-    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-  }
+
+  if( uiInitTrDepth != 0 )
+  { // set Cbf for all blocks
+    UInt uiCombCbfU = 0;
+    UInt uiCombCbfV = 0;
+    UInt uiPartIdx  = 0;
+    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiPartIdx += uiQNumParts )
+    {
+      uiCombCbfU |= pcCU->getCbf( uiPartIdx, COMPONENT_Cb, 1 );
+      uiCombCbfV |= pcCU->getCbf( uiPartIdx, COMPONENT_Cr, 1 );
+    }
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQNumParts; uiOffs++ )
+    {
+      pcCU->getCbf( COMPONENT_Cb )[ uiOffs ] |= uiCombCbfU;
+      pcCU->getCbf( COMPONENT_Cr )[ uiOffs ] |= uiCombCbfV;
+    }
+  }
+
+  m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepthCU][CI_CURR_BEST] );
+}
+
+
+
 
 /** Function for encoding and reconstructing luma/chroma samples of a PCM mode CU.
  * \param pcCU pointer to current CU
  * \param uiAbsPartIdx part index
- * \param piOrg pointer to original sample arrays
- * \param piPCM pointer to PCM code arrays
- * \param piPred pointer to prediction signal arrays
- * \param piResi pointer to residual signal arrays
- * \param piReco pointer to reconstructed sample arrays
+ * \param pOrg pointer to original sample arrays
+ * \param pPCM pointer to PCM code arrays
+ * \param pPred pointer to prediction signal arrays
+ * \param pResi pointer to residual signal arrays
+ * \param pReco pointer to reconstructed sample arrays
  * \param uiStride stride of the original/prediction/residual sample arrays
  * \param uiWidth block width
  * \param uiHeight block height
- * \param ttText texture component type
- * \returns Void
+ * \param compID texture component type
  */
-Void TEncSearch::xEncPCM (TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piOrg, Pel* piPCM, Pel* piPred, Pel* piResi, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType eText )
+Void TEncSearch::xEncPCM (TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* pOrg, Pel* pPCM, Pel* pPred, Pel* pResi, Pel* pReco, UInt uiStride, UInt uiWidth, UInt uiHeight, const ComponentID compID )
 {
-  UInt uiX, uiY;
-  UInt uiReconStride;
-  Pel* pOrg  = piOrg;
-  Pel* pPCM  = piPCM;
-  Pel* pPred = piPred;
-  Pel* pResi = piResi;
-  Pel* pReco = piReco;
-  Pel* pRecoPic;
-  Int shiftPcm;
-
-  if( eText == TEXT_LUMA)
-  {
-    uiReconStride = pcCU->getPic()->getPicYuvRec()->getStride();
-    pRecoPic      = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
-    shiftPcm = g_bitDepthY - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
-  }
-  else
-  {
-    uiReconStride = pcCU->getPic()->getPicYuvRec()->getCStride();
-
-    if( eText == TEXT_CHROMA_U )
-    {
-      pRecoPic = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
-    }
-    else
-    {
-      pRecoPic = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
-    }
-    shiftPcm = g_bitDepthC - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
-  }
-
-  // Reset pred and residual
-  for( uiY = 0; uiY < uiHeight; uiY++ )
-  {
-    for( uiX = 0; uiX < uiWidth; uiX++ )
-    {
+  const UInt uiReconStride   = pcCU->getPic()->getPicYuvRec()->getStride(compID);
+  const UInt uiPCMBitDepth   = pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
+  const Int  channelBitDepth = pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+  Pel* pRecoPic = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu()+uiAbsPartIdx);
+
+  const Int pcmShiftRight=(channelBitDepth - Int(uiPCMBitDepth));
+
+  assert(pcmShiftRight >= 0);
+
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      // Reset pred and residual
       pPred[uiX] = 0;
       pResi[uiX] = 0;
+      // Encode
+      pPCM[uiX] = (pOrg[uiX]>>pcmShiftRight);
+      // Reconstruction
+      pReco   [uiX] = (pPCM[uiX]<<(pcmShiftRight));
+      pRecoPic[uiX] = pReco[uiX];
     }
     pPred += uiStride;
     pResi += uiStride;
-  }
-
-  // Encode
-  for( uiY = 0; uiY < uiHeight; uiY++ )
-  {
-    for( uiX = 0; uiX < uiWidth; uiX++ )
-    {
-      pPCM[uiX] = pOrg[uiX]>> shiftPcm;
-    }
     pPCM += uiWidth;
     pOrg += uiStride;
-  }
-
-  pPCM  = piPCM;
-
-  // Reconstruction
-  for( uiY = 0; uiY < uiHeight; uiY++ )
-  {
-    for( uiX = 0; uiX < uiWidth; uiX++ )
-    {
-      pReco   [uiX] = pPCM[uiX]<< shiftPcm;
-      pRecoPic[uiX] = pReco[uiX];
-    }
-    pPCM += uiWidth;
     pReco += uiStride;
     pRecoPic += uiReconStride;
@@ -3836,77 +3783,48 @@
 }
 
-/**  Function for PCM mode estimation.
- * \param pcCU
- * \param pcOrgYuv
- * \param rpcPredYuv
- * \param rpcResiYuv
- * \param rpcRecoYuv
- * \returns Void
- */
-Void TEncSearch::IPCMSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv )
+
+//!  Function for PCM mode estimation.
+Void TEncSearch::IPCMSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, TComYuv* pcRecoYuv )
 {
-  UInt   uiDepth        = pcCU->getDepth(0);
-  UInt   uiWidth        = pcCU->getWidth(0);
-  UInt   uiHeight       = pcCU->getHeight(0);
-  UInt   uiStride       = rpcPredYuv->getStride();
-  UInt   uiStrideC      = rpcPredYuv->getCStride();
-  UInt   uiWidthC       = uiWidth  >> 1;
-  UInt   uiHeightC      = uiHeight >> 1;
-  UInt   uiDistortion = 0;
-  UInt   uiBits;
+  UInt        uiDepth      = pcCU->getDepth(0);
+  const UInt  uiDistortion = 0;
+  UInt        uiBits;
 
   Double dCost;
 
-  Pel*    pOrig;
-  Pel*    pResi;
-  Pel*    pReco;
-  Pel*    pPred;
-  Pel*    pPCM;
-
-  UInt uiAbsPartIdx = 0;
-
-  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
-  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
-  UInt uiChromaOffset = uiLumaOffset>>2;
-
-  // Luminance
-  pOrig    = pcOrgYuv->getLumaAddr(0, uiWidth);
-  pResi    = rpcResiYuv->getLumaAddr(0, uiWidth);
-  pPred    = rpcPredYuv->getLumaAddr(0, uiWidth);
-  pReco    = rpcRecoYuv->getLumaAddr(0, uiWidth);
-  pPCM     = pcCU->getPCMSampleY() + uiLumaOffset;
-
-  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStride, uiWidth, uiHeight, TEXT_LUMA );
-
-  // Chroma U
-  pOrig    = pcOrgYuv->getCbAddr();
-  pResi    = rpcResiYuv->getCbAddr();
-  pPred    = rpcPredYuv->getCbAddr();
-  pReco    = rpcRecoYuv->getCbAddr();
-  pPCM     = pcCU->getPCMSampleCb() + uiChromaOffset;
-
-  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStrideC, uiWidthC, uiHeightC, TEXT_CHROMA_U );
-
-  // Chroma V
-  pOrig    = pcOrgYuv->getCrAddr();
-  pResi    = rpcResiYuv->getCrAddr();
-  pPred    = rpcPredYuv->getCrAddr();
-  pReco    = rpcRecoYuv->getCrAddr();
-  pPCM     = pcCU->getPCMSampleCr() + uiChromaOffset;
-
-  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStrideC, uiWidthC, uiHeightC, TEXT_CHROMA_V );
+  for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+  {
+    const ComponentID compID  = ComponentID(ch);
+    const UInt width  = pcCU->getWidth(0)  >> pcCU->getPic()->getComponentScaleX(compID);
+    const UInt height = pcCU->getHeight(0) >> pcCU->getPic()->getComponentScaleY(compID);
+    const UInt stride = pcPredYuv->getStride(compID);
+
+    Pel * pOrig    = pcOrgYuv->getAddr  (compID, 0, width);
+    Pel * pResi    = pcResiYuv->getAddr(compID, 0, width);
+    Pel * pPred    = pcPredYuv->getAddr(compID, 0, width);
+    Pel * pReco    = pcRecoYuv->getAddr(compID, 0, width);
+    Pel * pPCM     = pcCU->getPCMSample (compID);
+
+    xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, stride, width, height, compID );
+
+  }
 
   m_pcEntropyCoder->resetBits();
-  xEncIntraHeader ( pcCU, uiDepth, uiAbsPartIdx, true, false);
+  xEncIntraHeader ( pcCU, uiDepth, 0, true, false);
+
   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
 
-#if H_3D_VSO // M43
+#if NH_3D_VSO // M43
+
+  // GT:  This needs to be checked distortion is not necessarily 0 in case of VSO.
   if( m_pcRdCost->getUseLambdaScaleVSO() )  
+  {
     dCost =  m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );  
+  }
   else
 #endif
-  dCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
-
-    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+    dCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
 
   pcCU->getTotalBits()       = uiBits;
@@ -3914,8 +3832,11 @@
   pcCU->getTotalDistortion() = uiDistortion;
 
-  pcCU->copyToPic(uiDepth, 0, 0);
+  pcCU->copyToPic(uiDepth);
 }
 
-Void TEncSearch::xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, UInt& ruiErr, Bool bHadamard )
+
+
+
+Void TEncSearch::xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, Distortion& ruiErr, Bool /*bHadamard*/ )
 {
   motionCompensation( pcCU, &m_tmpYuvPred, REF_PIC_LIST_X, iPartIdx );
@@ -3930,8 +3851,10 @@
   cDistParam.bApplyWeight = false;
 
-  m_pcRdCost->setDistParam( cDistParam, g_bitDepthY,
-                            pcYuvOrg->getLumaAddr( uiAbsPartIdx ), pcYuvOrg->getStride(), 
-                            m_tmpYuvPred .getLumaAddr( uiAbsPartIdx ), m_tmpYuvPred .getStride(), 
-                            iWidth, iHeight, m_pcEncCfg->getUseHADME() );
+
+  m_pcRdCost->setDistParam( cDistParam, pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA),
+                            pcYuvOrg->getAddr( COMPONENT_Y, uiAbsPartIdx ), pcYuvOrg->getStride(COMPONENT_Y),
+                            m_tmpYuvPred .getAddr( COMPONENT_Y, uiAbsPartIdx ), m_tmpYuvPred.getStride(COMPONENT_Y),
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME() && (pcCU->getCUTransquantBypass(iPartIdx) == 0) );
+
 #if H_3D_IC
   cDistParam.bUseIC = false;
@@ -3940,21 +3863,10 @@
   cDistParam.bUseSDCMRSAD = false;
 #endif
+
   ruiErr = cDistParam.DistFunc( &cDistParam );
 }
 
-/** estimation of best merge coding
- * \param pcCU
- * \param pcYuvOrg
- * \param iPUIdx
- * \param uiInterDir
- * \param pacMvField
- * \param uiMergeIndex
- * \param ruiCost
- * \param ruiBits
- * \param puhNeighCands
- * \param bValid 
- * \returns Void
- */
-Void TEncSearch::xMergeEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPUIdx, UInt& uiInterDir, TComMvField* pacMvField, UInt& uiMergeIndex, UInt& ruiCost, TComMvField* cMvFieldNeighbours, UChar* uhInterDirNeighbours
+//! estimation of best merge coding
+Void TEncSearch::xMergeEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPUIdx, UInt& uiInterDir, TComMvField* pacMvField, UInt& uiMergeIndex, Distortion& ruiCost, TComMvField* cMvFieldNeighbours, UChar* uhInterDirNeighbours, Int& numValidMergeCand 
 #if H_3D_VSP
                                  , Int* vspFlag
@@ -3963,14 +3875,13 @@
                                  , Bool* pbSPIVMPFlag, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
 #endif
-                                 , Int& numValidMergeCand
-                                 )
+)
 {
   UInt uiAbsPartIdx = 0;
   Int iWidth = 0;
-  Int iHeight = 0; 
+  Int iHeight = 0;
 
   pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
   UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
-  
+
 #if H_3D_DBBP
   DbbpTmpData* pDBBPTmpData = pcCU->getDBBPTmpData();
@@ -4003,5 +3914,5 @@
   }
 #endif
-  
+
   PartSize partSize = pcCU->getPartitionSize( 0 );
 #if H_3D_DBBP
@@ -4011,7 +3922,7 @@
 #endif
   {
-    pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
     if ( iPUIdx == 0 )
     {
+      pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth ); // temporarily set
 #if H_3D
       pcCU->initAvailableFlags();
@@ -4036,6 +3947,6 @@
       pcCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
 #endif
-    }
-    pcCU->setPartSizeSubParts( partSize, 0, uiDepth );
+      pcCU->setPartSizeSubParts( partSize, 0, uiDepth ); // restore
+    }
   }
   else
@@ -4061,8 +3972,8 @@
       );
 #else
-    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand
-                                 );
-#endif
-  }
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+#endif
+  }
+
   xRestrictBipredMergeCand( pcCU, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
 
@@ -4083,12 +3994,11 @@
 #endif
 
-  ruiCost = MAX_UINT;
+  ruiCost = std::numeric_limits<Distortion>::max();
   for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
   {
-    UInt uiCostCand = MAX_UINT;
-    UInt uiBitsCand = 0;
+    Distortion uiCostCand = std::numeric_limits<Distortion>::max();
+    UInt       uiBitsCand = 0;
 
     PartSize ePartSize = pcCU->getPartitionSize( 0 );
-
 #if H_3D_VSP
     pcCU->setVSPFlagSubParts( vspFlag[uiMergeCand], uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx ) );
@@ -4148,27 +4058,29 @@
       {
 #endif
-        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
-        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
+
+    pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
+    pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
 #if H_3D_VSP
       }
 #endif
 
-      xGetInterPredictionError( pcCU, pcYuvOrg, iPUIdx, uiCostCand, m_pcEncCfg->getUseHADME() );
-      uiBitsCand = uiMergeCand + 1;
-      if (uiMergeCand == m_pcEncCfg->getMaxNumMergeCand() -1)
-      {
+
+    xGetInterPredictionError( pcCU, pcYuvOrg, iPUIdx, uiCostCand, m_pcEncCfg->getUseHADME() );
+    uiBitsCand = uiMergeCand + 1;
+    if (uiMergeCand == m_pcEncCfg->getMaxNumMergeCand() -1)
+    {
         uiBitsCand--;
-      }
-      uiCostCand = uiCostCand + m_pcRdCost->getCost( uiBitsCand );
-      if ( uiCostCand < ruiCost )
-      {
-        ruiCost = uiCostCand;
-        pacMvField[0] = cMvFieldNeighbours[0 + 2*uiMergeCand];
-        pacMvField[1] = cMvFieldNeighbours[1 + 2*uiMergeCand];
-        uiInterDir = uhInterDirNeighbours[uiMergeCand];
-        uiMergeIndex = uiMergeCand;
-      }
-  }
-  }
+    }
+    uiCostCand = uiCostCand + m_pcRdCost->getCost( uiBitsCand );
+    if ( uiCostCand < ruiCost )
+    {
+      ruiCost = uiCostCand;
+      pacMvField[0] = cMvFieldNeighbours[0 + 2*uiMergeCand];
+      pacMvField[1] = cMvFieldNeighbours[1 + 2*uiMergeCand];
+      uiInterDir = uhInterDirNeighbours[uiMergeCand];
+      uiMergeIndex = uiMergeCand;
+    }
+  }
+}
 
 /** convert bi-pred merge candidates to uni-pred
@@ -4195,80 +4107,68 @@
 }
 
-/** search of the best candidate for inter prediction
- * \param pcCU
- * \param pcOrgYuv
- * \param rpcPredYuv
- * \param rpcResiYuv
- * \param rpcRecoYuv
- * \param bUseRes
- * \returns Void
- */
+//! search of the best candidate for inter prediction
 #if AMP_MRG
 #if  H_3D_FAST_TEXTURE_ENCODING
 Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bFMD, Bool bUseRes, Bool bUseMRG )
 #else
-Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes, Bool bUseMRG )
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, TComYuv* pcRecoYuv DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseRes, Bool bUseMRG )
 #endif
 #else
-Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes )
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, TComYuv* pcRecoYuv, Bool bUseRes )
 #endif
 {
-  m_acYuvPred[0].clear();
-  m_acYuvPred[1].clear();
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acYuvPred[i].clear();
+  }
   m_cYuvPredTemp.clear();
-  rpcPredYuv->clear();
-  
+  pcPredYuv->clear();
+
   if ( !bUseRes )
   {
-    rpcResiYuv->clear();
-  }
-  
-  rpcRecoYuv->clear();
-  
-  TComMv        cMvSrchRngLT;
-  TComMv        cMvSrchRngRB;
-  
-  TComMv        cMvZero;
-  TComMv        TempMv; //kolya
-  
-  TComMv        cMv[2];
-  TComMv        cMvBi[2];
-  TComMv        cMvTemp[2][33];
-  
-  Int           iNumPart    = pcCU->getNumPartitions();
-  Int           iNumPredDir = pcCU->getSlice()->isInterP() ? 1 : 2;
-  
-  TComMv        cMvPred[2][33];
-  
-  TComMv        cMvPredBi[2][33];
-  Int           aaiMvpIdxBi[2][33];
-  
-  Int           aaiMvpIdx[2][33];
-  Int           aaiMvpNum[2][33];
-  
-  AMVPInfo aacAMVPInfo[2][33];
-  
-  Int           iRefIdx[2]={0,0}; //If un-initialized, may cause SEGV in bi-directional prediction iterative stage.
-  Int           iRefIdxBi[2];
-  
-  UInt          uiPartAddr;
-  Int           iRoiWidth, iRoiHeight;
-  
-  UInt          uiMbBits[3] = {1, 1, 0};
-  
-  UInt          uiLastMode = 0;
-  Int           iRefStart, iRefEnd;
-  
-  PartSize      ePartSize = pcCU->getPartitionSize( 0 );
-
-  Int           bestBiPRefIdxL1 = 0;
-  Int           bestBiPMvpL1 = 0;
-  UInt          biPDistTemp = MAX_INT;
-
-#if ZERO_MVD_EST
-  Int           aiZeroMvdMvpIdx[2] = {-1, -1};
-  Int           aiZeroMvdRefIdx[2] = {0, 0};
-  Int           iZeroMvdDir = -1;
-#endif
+    pcResiYuv->clear();
+  }
+
+  pcRecoYuv->clear();
+
+  TComMv       cMvSrchRngLT;
+  TComMv       cMvSrchRngRB;
+
+  TComMv       cMvZero;
+  TComMv       TempMv; //kolya
+
+  TComMv       cMv[2];
+  TComMv       cMvBi[2];
+  TComMv       cMvTemp[2][33];
+
+  Int          iNumPart    = pcCU->getNumPartitions();
+  Int          iNumPredDir = pcCU->getSlice()->isInterP() ? 1 : 2;
+
+  TComMv       cMvPred[2][33];
+
+  TComMv       cMvPredBi[2][33];
+  Int          aaiMvpIdxBi[2][33];
+
+  Int          aaiMvpIdx[2][33];
+  Int          aaiMvpNum[2][33];
+
+  AMVPInfo     aacAMVPInfo[2][33];
+
+  Int          iRefIdx[2]={0,0}; //If un-initialized, may cause SEGV in bi-directional prediction iterative stage.
+  Int          iRefIdxBi[2];
+
+  UInt         uiPartAddr;
+  Int          iRoiWidth, iRoiHeight;
+
+  UInt         uiMbBits[3] = {1, 1, 0};
+
+  UInt         uiLastMode = 0;
+  Int          iRefStart, iRefEnd;
+
+  PartSize     ePartSize = pcCU->getPartitionSize( 0 );
+
+  Int          bestBiPRefIdxL1 = 0;
+  Int          bestBiPMvpL1 = 0;
+  Distortion   biPDistTemp = std::numeric_limits<Distortion>::max();
 
 #if H_3D_IV_MERGE
@@ -4279,43 +4179,36 @@
   UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
 #endif
+
   Int numValidMergeCand = 0 ;
 
   for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
   {
-    UInt          uiCost[2] = { MAX_UINT, MAX_UINT };
-    UInt          uiCostBi  =   MAX_UINT;
-    UInt          uiCostTemp;
-    
-    UInt          uiBits[3];
-    UInt          uiBitsTemp;
-#if ZERO_MVD_EST
-    UInt          uiZeroMvdCost = MAX_UINT;
-    UInt          uiZeroMvdCostTemp;
-    UInt          uiZeroMvdBitsTemp;
-    UInt          uiZeroMvdDistTemp = MAX_UINT;
-    UInt          auiZeroMvdBits[3];
-#endif
-    UInt          bestBiPDist = MAX_INT;
-
-    UInt          uiCostTempL0[MAX_NUM_REF];
+    Distortion   uiCost[2] = { std::numeric_limits<Distortion>::max(), std::numeric_limits<Distortion>::max() };
+    Distortion   uiCostBi  =   std::numeric_limits<Distortion>::max();
+    Distortion   uiCostTemp;
+
+    UInt         uiBits[3];
+    UInt         uiBitsTemp;
+    Distortion   bestBiPDist = std::numeric_limits<Distortion>::max();
+
+    Distortion   uiCostTempL0[MAX_NUM_REF];
     for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++)
     {
-      uiCostTempL0[iNumRef] = MAX_UINT;
-    }
-    UInt          uiBitsTempL0[MAX_NUM_REF];
-
-    TComMv        mvValidList1;
-    Int           refIdxValidList1 = 0;
-    UInt          bitsValidList1 = MAX_UINT;
-    UInt          costValidList1 = MAX_UINT;
+      uiCostTempL0[iNumRef] = std::numeric_limits<Distortion>::max();
+    }
+    UInt         uiBitsTempL0[MAX_NUM_REF];
+
+    TComMv       mvValidList1;
+    Int          refIdxValidList1 = 0;
+    UInt         bitsValidList1 = MAX_UINT;
+    Distortion   costValidList1 = std::numeric_limits<Distortion>::max();
 
     xGetBlkBits( ePartSize, pcCU->getSlice()->isInterP(), iPartIdx, uiLastMode, uiMbBits);
-    
+
     pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
-
 #if H_3D_VSP
     pcCU->setVSPFlagSubParts( 0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr) );
 #endif
-    
+
 #if AMP_MRG
     Bool bTestNormalMC = true;
@@ -4325,8 +4218,9 @@
     if ( bUseMRG && pcCU->getWidth( 0 ) > 8 && iNumPart == 2 )
 #endif
+
     {
       bTestNormalMC = false;
     }
-    
+
     if (bTestNormalMC)
     {
@@ -4337,5 +4231,5 @@
     {
       RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
-      
+
       for ( Int iRefIdxTemp = 0; iRefIdxTemp < pcCU->getSlice()->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
       {
@@ -4344,14 +4238,13 @@
         {
           uiBitsTemp += iRefIdxTemp+1;
-          if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
-        }
-#if ZERO_MVD_EST
-        xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], false, &biPDistTemp, &uiZeroMvdDistTemp);
-#else
+          if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 )
+          {
+            uiBitsTemp--;
+          }
+        }
         xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], false, &biPDistTemp);
-#endif
         aaiMvpIdx[iRefList][iRefIdxTemp] = pcCU->getMVPIdx(eRefPicList, uiPartAddr);
         aaiMvpNum[iRefList][iRefIdxTemp] = pcCU->getMVPNum(eRefPicList, uiPartAddr);
-        
+
         if(pcCU->getSlice()->getMvdL1ZeroFlag() && iRefList==1 && biPDistTemp < bestBiPDist)
         {
@@ -4362,26 +4255,6 @@
 
         uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
-#if ZERO_MVD_EST
-        if ( iRefList == 0 || pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) < 0 )
-        {
-          uiZeroMvdBitsTemp = uiBitsTemp;
-          uiZeroMvdBitsTemp += 2; //zero mvd bits
-
-          m_pcRdCost->getMotionCost( 1, 0 );
-          uiZeroMvdCostTemp = uiZeroMvdDistTemp + m_pcRdCost->getCost(uiZeroMvdBitsTemp);
-
-          if (uiZeroMvdCostTemp < uiZeroMvdCost)
-          {
-            uiZeroMvdCost = uiZeroMvdCostTemp;
-            iZeroMvdDir = iRefList + 1;
-            aiZeroMvdRefIdx[iRefList] = iRefIdxTemp;
-            aiZeroMvdMvpIdx[iRefList] = aaiMvpIdx[iRefList][iRefIdxTemp];
-            auiZeroMvdBits[iRefList] = uiZeroMvdBitsTemp;
-          }          
-        }
-#endif
-        
-#if GPB_SIMPLE_UNI
-        if ( iRefList == 1 )    // list 1
+
+        if ( m_pcEncCfg->getFastMEForGenBLowDelayEnabled() && iRefList == 1 )    // list 1
         {
           if ( pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) >= 0 )
@@ -4406,7 +4279,4 @@
           xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
         }
-#else
-        xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
-#endif
         xCopyAMVPInfo(pcCU->getCUMvField(eRefPicList)->getAMVPInfo(), &aacAMVPInfo[iRefList][iRefIdxTemp]); // must always be done ( also when AMVP_MODE = AM_NONE )
         xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
@@ -4438,14 +4308,15 @@
       }
     }
+
     //  Bi-directional prediction
     if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) )
     {
-      
+
       cMvBi[0] = cMv[0];            cMvBi[1] = cMv[1];
       iRefIdxBi[0] = iRefIdx[0];    iRefIdxBi[1] = iRefIdx[1];
-      
+
       ::memcpy(cMvPredBi, cMvPred, sizeof(cMvPred));
       ::memcpy(aaiMvpIdxBi, aaiMvpIdx, sizeof(aaiMvpIdx));
-      
+
       UInt uiMotBits[2];
 
@@ -4461,5 +4332,5 @@
         pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
         pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-        TComYuv* pcYuvPred = &m_acYuvPred[1];
+        TComYuv* pcYuvPred = &m_acYuvPred[REF_PIC_LIST_1];
         motionCompensation( pcCU, pcYuvPred, REF_PIC_LIST_1, iPartIdx );
 
@@ -4470,5 +4341,8 @@
         {
           uiMotBits[1] += bestBiPRefIdxL1+1;
-          if ( bestBiPRefIdxL1 == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1 ) uiMotBits[1]--;
+          if ( bestBiPRefIdxL1 == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1 )
+          {
+            uiMotBits[1]--;
+          }
         }
 
@@ -4488,5 +4362,5 @@
       // 4-times iteration (default)
       Int iNumIter = 4;
-      
+
       // fast encoder setting: only one iteration
       if ( m_pcEncCfg->getUseFastEnc() || pcCU->getSlice()->getMvdL1ZeroFlag())
@@ -4494,9 +4368,9 @@
         iNumIter = 1;
       }
-      
+
       for ( Int iIter = 0; iIter < iNumIter; iIter++ )
       {
-        
         Int         iRefList    = iIter % 2;
+
         if ( m_pcEncCfg->getUseFastEnc() )
         {
@@ -4521,4 +4395,5 @@
           motionCompensation ( pcCU, pcYuvPred, RefPicList(1-iRefList), iPartIdx );
         }
+
         RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
 
@@ -4530,8 +4405,8 @@
 
         Bool bChanged = false;
-        
+
         iRefStart = 0;
         iRefEnd   = pcCU->getSlice()->getNumRefIdx(eRefPicList)-1;
-        
+
         for ( Int iRefIdxTemp = iRefStart; iRefIdxTemp <= iRefEnd; iRefIdxTemp++ )
         {
@@ -4540,9 +4415,13 @@
           {
             uiBitsTemp += iRefIdxTemp+1;
-            if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
+            if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 )
+            {
+              uiBitsTemp--;
+            }
           }
           uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdxBi[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
           // call ME
           xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPredBi[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp, true );
+
           xCopyAMVPInfo(&aacAMVPInfo[iRefList][iRefIdxTemp], pcCU->getCUMvField(eRefPicList)->getAMVPInfo());
           xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPredBi[iRefList][iRefIdxTemp], aaiMvpIdxBi[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
@@ -4551,12 +4430,12 @@
           {
             bChanged = true;
-            
+
             cMvBi[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
             iRefIdxBi[iRefList] = iRefIdxTemp;
-            
+
             uiCostBi            = uiCostTemp;
             uiMotBits[iRefList] = uiBitsTemp - uiMbBits[2] - uiMotBits[1-iRefList];
             uiBits[2]           = uiBitsTemp;
-            
+
             if(iNumIter!=1)
             {
@@ -4570,5 +4449,5 @@
           }
         } // for loop-iRefIdxTemp
-        
+
         if ( !bChanged )
         {
@@ -4587,55 +4466,4 @@
       } // for loop-iter
     } // if (B_SLICE)
-#if ZERO_MVD_EST
-    if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) )
-    {
-      m_pcRdCost->getMotionCost( 1, 0 );
-
-      for ( Int iL0RefIdxTemp = 0; iL0RefIdxTemp <= pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0)-1; iL0RefIdxTemp++ )
-      for ( Int iL1RefIdxTemp = 0; iL1RefIdxTemp <= pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1; iL1RefIdxTemp++ )
-      {
-        UInt uiRefIdxBitsTemp = 0;
-        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0) > 1 )
-        {
-          uiRefIdxBitsTemp += iL0RefIdxTemp+1;
-          if ( iL0RefIdxTemp == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0)-1 ) uiRefIdxBitsTemp--;
-        }
-        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1) > 1 )
-        {
-          uiRefIdxBitsTemp += iL1RefIdxTemp+1;
-          if ( iL1RefIdxTemp == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1 ) uiRefIdxBitsTemp--;
-        }
-
-        Int iL0MVPIdx = 0;
-        Int iL1MVPIdx = 0;
-
-        for (iL0MVPIdx = 0; iL0MVPIdx < aaiMvpNum[0][iL0RefIdxTemp]; iL0MVPIdx++)
-        {
-          for (iL1MVPIdx = 0; iL1MVPIdx < aaiMvpNum[1][iL1RefIdxTemp]; iL1MVPIdx++)
-          {
-            uiZeroMvdBitsTemp = uiRefIdxBitsTemp;
-            uiZeroMvdBitsTemp += uiMbBits[2];
-            uiZeroMvdBitsTemp += m_auiMVPIdxCost[iL0MVPIdx][aaiMvpNum[0][iL0RefIdxTemp]] + m_auiMVPIdxCost[iL1MVPIdx][aaiMvpNum[1][iL1RefIdxTemp]];
-            uiZeroMvdBitsTemp += 4; //zero mvd for both directions
-            pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( aacAMVPInfo[0][iL0RefIdxTemp].m_acMvCand[iL0MVPIdx], iL0RefIdxTemp, ePartSize, uiPartAddr, iPartIdx, 0 );
-            pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( aacAMVPInfo[1][iL1RefIdxTemp].m_acMvCand[iL1MVPIdx], iL1RefIdxTemp, ePartSize, uiPartAddr, iPartIdx, 0 );
-  
-            xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiZeroMvdDistTemp, m_pcEncCfg->getUseHADME() );
-            uiZeroMvdCostTemp = uiZeroMvdDistTemp + m_pcRdCost->getCost( uiZeroMvdBitsTemp );
-            if (uiZeroMvdCostTemp < uiZeroMvdCost)
-            {
-              uiZeroMvdCost = uiZeroMvdCostTemp;
-              iZeroMvdDir = 3;
-              aiZeroMvdMvpIdx[0] = iL0MVPIdx;
-              aiZeroMvdMvpIdx[1] = iL1MVPIdx;
-              aiZeroMvdRefIdx[0] = iL0RefIdxTemp;
-              aiZeroMvdRefIdx[1] = iL1RefIdxTemp;
-              auiZeroMvdBits[2] = uiZeroMvdBitsTemp;
-            }
-          }
-        }
-      }
-    }
-#endif
 
 #if AMP_MRG
@@ -4652,5 +4480,5 @@
     pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
     pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-    
+
     UInt uiMEBits = 0;
     // Set Motion Field_
@@ -4659,73 +4487,25 @@
     uiBits[1] = bitsValidList1;
     uiCost[1] = costValidList1;
+
 #if AMP_MRG
     if (bTestNormalMC)
     {
 #endif
-#if ZERO_MVD_EST
-    if (uiZeroMvdCost <= uiCostBi && uiZeroMvdCost <= uiCost[0] && uiZeroMvdCost <= uiCost[1])
-    {
-      if (iZeroMvdDir == 3)
-      {
-        uiLastMode = 2;
-
-        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( aacAMVPInfo[0][aiZeroMvdRefIdx[0]].m_acMvCand[aiZeroMvdMvpIdx[0]], aiZeroMvdRefIdx[0], ePartSize, uiPartAddr, iPartIdx, 0 );
-        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( aacAMVPInfo[1][aiZeroMvdRefIdx[1]].m_acMvCand[aiZeroMvdMvpIdx[1]], aiZeroMvdRefIdx[1], ePartSize, uiPartAddr, iPartIdx, 0 );
-  
-        pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
-        
-        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[0], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        pcCU->setMVPNumSubParts( aaiMvpNum[0][aiZeroMvdRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[1], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        pcCU->setMVPNumSubParts( aaiMvpNum[1][aiZeroMvdRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        uiMEBits = auiZeroMvdBits[2];
-      }
-      else if (iZeroMvdDir == 1)
-      {        
-        uiLastMode = 0;
-
-        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( aacAMVPInfo[0][aiZeroMvdRefIdx[0]].m_acMvCand[aiZeroMvdMvpIdx[0]], aiZeroMvdRefIdx[0], ePartSize, uiPartAddr, iPartIdx, 0 );
-
-        pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
-        
-        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[0], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        pcCU->setMVPNumSubParts( aaiMvpNum[0][aiZeroMvdRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        uiMEBits = auiZeroMvdBits[0];
-      }
-      else if (iZeroMvdDir == 2)
-      {
-        uiLastMode = 1;
-
-        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( aacAMVPInfo[1][aiZeroMvdRefIdx[1]].m_acMvCand[aiZeroMvdMvpIdx[1]], aiZeroMvdRefIdx[1], ePartSize, uiPartAddr, iPartIdx, 0 );
-
-        pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
-        
-        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[1], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        pcCU->setMVPNumSubParts( aaiMvpNum[1][aiZeroMvdRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        uiMEBits = auiZeroMvdBits[1];
-      }
-      else
-      {
-        assert(0);
-      }
-    }
-    else
-#endif
     if ( uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1])
     {
       uiLastMode = 2;
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
-      
-        TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      
-        TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
-            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
-      
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+
+      TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+
+      TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+
       pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
-      
+
       pcCU->setMVPIdxSubParts( aaiMvpIdxBi[0][iRefIdxBi[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
       pcCU->setMVPNumSubParts( aaiMvpNum[0][iRefIdxBi[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
@@ -4738,10 +4518,12 @@
     {
       uiLastMode = 0;
-          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
-        TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
-            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
+
+      TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
+      pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+
       pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
-      
+
       pcCU->setMVPIdxSubParts( aaiMvpIdx[0][iRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
       pcCU->setMVPNumSubParts( aaiMvpNum[0][iRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
@@ -4754,6 +4536,8 @@
       pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
       pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
+
       TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
       pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+
       pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
 
@@ -4766,5 +4550,4 @@
     } // end if bTestNormalMC
 #endif
-
 #if H_3D_DBBP
     // test merge mode for DBBP (2Nx2N)
@@ -4774,5 +4557,5 @@
 #endif
     {
-      UInt uiMRGInterDir = 0;     
+      UInt uiMRGInterDir = 0;
       TComMvField cMRGMvField[2];
       UInt uiMRGIndex = 0;
@@ -4781,9 +4564,10 @@
       TComMvField cMEMvField[2];
 
-      m_pcRdCost->getMotionCost( 1, 0 );
+      m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
+
 #if AMP_MRG
       // calculate ME cost
-      UInt uiMEError = MAX_UINT;
-      UInt uiMECost = MAX_UINT;
+      Distortion uiMEError = std::numeric_limits<Distortion>::max();
+      Distortion uiMECost  = std::numeric_limits<Distortion>::max();
 
       if (bTestNormalMC)
@@ -4794,8 +4578,8 @@
 #else
       // calculate ME cost
-      UInt uiMEError = MAX_UINT;
+      Distortion uiMEError = std::numeric_limits<Distortion>::max();
       xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
-      UInt uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
-#endif 
+      Distortion uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
+#endif
       // save ME result.
       uiMEInterDir = pcCU->getInterDir( uiPartAddr );
@@ -4804,5 +4588,6 @@
 
       // find Merge result
-      UInt uiMRGCost = MAX_UINT;
+      Distortion uiMRGCost = std::numeric_limits<Distortion>::max();
+
 #if H_3D_VSP
       Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
@@ -4823,4 +4608,5 @@
 #endif
       xMergeEstimation( pcCU, pcOrgYuv, iPartIdx, uiMRGInterDir, cMRGMvField, uiMRGIndex, uiMRGCost, cMvFieldNeighbours, uhInterDirNeighbours
+
 #if H_3D_VSP
                       , vspFlag
@@ -4829,6 +4615,6 @@
                       , bSPIVMPFlag, pcMvFieldSP, puhInterDirSP
 #endif 
-                      , numValidMergeCand
-                      );
+, numValidMergeCand);
+
       if ( uiMRGCost < uiMECost )
       {
@@ -4896,7 +4682,7 @@
           {
 #endif
-          pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-            pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
-            pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
 #if H_3D
           }
@@ -4922,7 +4708,7 @@
         pcCU->setDvInfoSubParts(OriginalDvInfo, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
 #endif
-          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
-          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-        }
+        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      }
 #if H_3D_SPIVMP
       delete[] pcMvFieldSP;
@@ -4932,6 +4718,6 @@
 
     //  MC
-    motionCompensation ( pcCU, rpcPredYuv, REF_PIC_LIST_X, iPartIdx );
-    
+    motionCompensation ( pcCU, pcPredYuv, REF_PIC_LIST_X, iPartIdx );
+
   } //  end of for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
 
@@ -4941,26 +4727,24 @@
 }
 
+
 // AMVP
-#if ZERO_MVD_EST
-Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, UInt* puiDistBiP, UInt* puiDist  )
-#else
-Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, UInt* puiDistBiP )
-#endif
+Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, Distortion* puiDistBiP )
 {
-  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
-  
-  TComMv  cBestMv;
-  Int     iBestIdx = 0;
-  TComMv  cZeroMv;
-  TComMv  cMvPred;
-  UInt    uiBestCost = MAX_INT;
-  UInt    uiPartAddr = 0;
-  Int     iRoiWidth, iRoiHeight;
-  Int     i;
-  
+  AMVPInfo*  pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+
+  TComMv     cBestMv;
+  Int        iBestIdx   = 0;
+  TComMv     cZeroMv;
+  TComMv     cMvPred;
+  Distortion uiBestCost = std::numeric_limits<Distortion>::max();
+  UInt       uiPartAddr = 0;
+  Int        iRoiWidth, iRoiHeight;
+  Int        i;
+
   pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
   // Fill the MV Candidates
   if (!bFilled)
   {
+
 #if H_3D_DBBP
     DbbpTmpData* pDBBPTmpData = pcCU->getDBBPTmpData();
@@ -4993,7 +4777,6 @@
     }
 #endif
-    
+
     pcCU->fillMvpCand( uiPartIdx, uiPartAddr, eRefPicList, iRefIdx, pcAMVPInfo );
-    
 #if H_3D_DBBP
     if( pcCU->getDBBPFlag(0) )
@@ -5009,14 +4792,14 @@
     }
 #endif
-  }
-  
+
+  }
+
   // initialize Mvp index & Mvp
   iBestIdx = 0;
   cBestMv  = pcAMVPInfo->m_acMvCand[0];
-#if !ZERO_MVD_EST
   if (pcAMVPInfo->iN <= 1)
   {
     rcMvPred = cBestMv;
-    
+
     pcCU->setMVPIdxSubParts( iBestIdx, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
     pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
@@ -5024,13 +4807,9 @@
     if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefPicList==REF_PIC_LIST_1)
     {
-#if ZERO_MVD_EST
-      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
-#else
-      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
-#endif
+      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
     }
     return;
   }
-#endif  
+
   if (bFilled)
   {
@@ -5039,18 +4818,11 @@
     return;
   }
-  
+
   m_cYuvPredTemp.clear();
-#if ZERO_MVD_EST
-  UInt uiDist;
-#endif
   //-- Check Minimum Cost.
   for ( i = 0 ; i < pcAMVPInfo->iN; i++)
   {
-    UInt uiTmpCost;
-#if ZERO_MVD_EST
-    uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
-#else
-    uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
-#endif      
+    Distortion uiTmpCost;
+    uiTmpCost = xGetTemplateCost( pcCU, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
     if ( uiBestCost > uiTmpCost )
     {
@@ -5059,12 +4831,9 @@
       iBestIdx  = i;
       (*puiDistBiP) = uiTmpCost;
-#if ZERO_MVD_EST
-      (*puiDist) = uiDist;
-#endif
     }
   }
 
   m_cYuvPredTemp.clear();
-  
+
   // Setting Best MVP
   rcMvPred = cBestMv;
@@ -5077,10 +4846,10 @@
 {
   assert(iIdx >= 0 && iNum >= 0 && iIdx < iNum);
-  
+
   if (iNum == 1)
   {
     return 0;
   }
-  
+
   UInt uiLength = 1;
   Int iTemp = iIdx;
@@ -5089,14 +4858,14 @@
     return uiLength;
   }
-  
+
   Bool bCodeLast = ( iNum-1 > iTemp );
-  
+
   uiLength += (iTemp-1);
-  
+
   if( bCodeLast )
   {
     uiLength++;
   }
-  
+
   return uiLength;
 }
@@ -5160,31 +4929,37 @@
 }
 
-Void TEncSearch::xCheckBestMVP ( TComDataCU* pcCU, RefPicList eRefPicList, TComMv cMv, TComMv& rcMvPred, Int& riMVPIdx, UInt& ruiBits, UInt& ruiCost )
+Void TEncSearch::xCheckBestMVP ( TComDataCU* pcCU, RefPicList eRefPicList, TComMv cMv, TComMv& rcMvPred, Int& riMVPIdx, UInt& ruiBits, Distortion& ruiCost )
 {
   AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
-  
+
   assert(pcAMVPInfo->m_acMvCand[riMVPIdx] == rcMvPred);
-  
-  if (pcAMVPInfo->iN < 2) return;
-  
-  m_pcRdCost->getMotionCost( 1, 0 );
+
+  if (pcAMVPInfo->iN < 2)
+  {
+    return;
+  }
+
+  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(0) );
   m_pcRdCost->setCostScale ( 0    );
-  
+
   Int iBestMVPIdx = riMVPIdx;
-  
+
   m_pcRdCost->setPredictor( rcMvPred );
   Int iOrgMvBits  = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
   iOrgMvBits += m_auiMVPIdxCost[riMVPIdx][AMVP_MAX_NUM_CANDS];
   Int iBestMvBits = iOrgMvBits;
-  
+
   for (Int iMVPIdx = 0; iMVPIdx < pcAMVPInfo->iN; iMVPIdx++)
   {
-    if (iMVPIdx == riMVPIdx) continue;
-    
+    if (iMVPIdx == riMVPIdx)
+    {
+      continue;
+    }
+
     m_pcRdCost->setPredictor( pcAMVPInfo->m_acMvCand[iMVPIdx] );
-    
+
     Int iMvBits = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
     iMvBits += m_auiMVPIdxCost[iMVPIdx][AMVP_MAX_NUM_CANDS];
-    
+
     if (iMvBits < iBestMvBits)
     {
@@ -5193,9 +4968,9 @@
     }
   }
-  
+
   if (iBestMVPIdx != riMVPIdx)  //if changed
   {
     rcMvPred = pcAMVPInfo->m_acMvCand[iBestMVPIdx];
-    
+
     riMVPIdx = iBestMVPIdx;
     UInt uiOrgBits = ruiBits;
@@ -5205,25 +4980,22 @@
 }
 
-UInt TEncSearch::xGetTemplateCost( TComDataCU* pcCU,
-                                  UInt        uiPartIdx,
-                                  UInt      uiPartAddr,
-                                  TComYuv*    pcOrgYuv,
-                                  TComYuv*    pcTemplateCand,
-                                  TComMv      cMvCand,
-                                  Int         iMVPIdx,
-                                  Int     iMVPNum,
-                                  RefPicList  eRefPicList,
-                                  Int         iRefIdx,
-                                  Int         iSizeX,
-                                  Int         iSizeY
-                               #if ZERO_MVD_EST
-                                , UInt&       ruiDist
-                               #endif
-                                  )
+
+Distortion TEncSearch::xGetTemplateCost( TComDataCU* pcCU,
+                                         UInt        uiPartAddr,
+                                         TComYuv*    pcOrgYuv,
+                                         TComYuv*    pcTemplateCand,
+                                         TComMv      cMvCand,
+                                         Int         iMVPIdx,
+                                         Int         iMVPNum,
+                                         RefPicList  eRefPicList,
+                                         Int         iRefIdx,
+                                         Int         iSizeX,
+                                         Int         iSizeY
+                                         )
 {
-  UInt uiCost  = MAX_INT;
-  
+  Distortion uiCost = std::numeric_limits<Distortion>::max();
+
   TComPicYuv* pcPicYuvRef = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec();
-  
+
   pcCU->clipMv( cMvCand );
 
@@ -5233,11 +5005,11 @@
 
   // prediction pattern
-  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
-  {
-    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, true );
+  if ( pcCU->getSlice()->testWeightPred() && pcCU->getSlice()->getSliceType()==P_SLICE )
+  {
+    xPredInterBlk( COMPONENT_Y, pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, true, pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) );
   }
   else
   {
-    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, false
+    xPredInterBlk( COMPONENT_Y, pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, false, pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) 
 #if H_3D_ARP
       , false
@@ -5246,8 +5018,9 @@
     , bICFlag
 #endif
-      );
-  }
-
-  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+
+);
+  }
+
+  if ( pcCU->getSlice()->testWeightPred() && pcCU->getSlice()->getSliceType()==P_SLICE )
   {
     xWeightedPredictionUni( pcCU, pcTemplateCand, uiPartAddr, iSizeX, iSizeY, eRefPicList, pcTemplateCand, iRefIdx );
@@ -5255,40 +5028,36 @@
 
   // calc distortion
-#if ZERO_MVD_EST
-  m_pcRdCost->getMotionCost( 1, 0 );
-  DistParam cDistParam;
-  m_pcRdCost->setDistParam( cDistParam, g_bitDepthY,
-                            pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), 
-                            pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), 
-                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
-  ruiDist = cDistParam.DistFunc( &cDistParam );
-  uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
-#else
-  uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, TEXT_LUMA, DF_SAD );
+
+  uiCost = m_pcRdCost->getDistPart( pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA), pcTemplateCand->getAddr(COMPONENT_Y, uiPartAddr), pcTemplateCand->getStride(COMPONENT_Y), pcOrgYuv->getAddr(COMPONENT_Y, uiPartAddr), pcOrgYuv->getStride(COMPONENT_Y), iSizeX, iSizeY, COMPONENT_Y, DF_SAD );
   uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
-#endif
   return uiCost;
 }
 
-Void TEncSearch::xMotionEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, RefPicList eRefPicList, TComMv* pcMvPred, Int iRefIdxPred, TComMv& rcMv, UInt& ruiBits, UInt& ruiCost, Bool bBi  )
+
+
+
+Void TEncSearch::xMotionEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, RefPicList eRefPicList, TComMv* pcMvPred, Int iRefIdxPred, TComMv& rcMv, UInt& ruiBits, Distortion& ruiCost, Bool bBi  )
 {
   UInt          uiPartAddr;
   Int           iRoiWidth;
   Int           iRoiHeight;
-  
+
   TComMv        cMvHalf, cMvQter;
   TComMv        cMvSrchRngLT;
   TComMv        cMvSrchRngRB;
-  
+
   TComYuv*      pcYuv = pcYuvOrg;
+
+  assert(eRefPicList < MAX_NUM_REF_LIST_ADAPT_SR && iRefIdxPred<Int(MAX_IDX_ADAPT_SR));
   m_iSearchRange = m_aaiAdaptSR[eRefPicList][iRefIdxPred];
-  
+
   Int           iSrchRng      = ( bBi ? m_bipredSearchRange : m_iSearchRange );
-  TComPattern*  pcPatternKey  = pcCU->getPattern        ();
-  
+  TComPattern   tmpPattern;
+  TComPattern*  pcPatternKey  = &tmpPattern;
+
   Double        fWeight       = 1.0;
-  
+
   pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
-  
+
 #if H_3D_IC
   Bool bICFlag = pcCU->getICFlag( uiPartAddr ) && ( pcCU->getSlice()->getViewIndex() != pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getViewIndex() );
@@ -5303,51 +5072,52 @@
     TComYuv*  pcYuvOther = &m_acYuvPred[1-(Int)eRefPicList];
     pcYuv                = &m_cYuvPredTemp;
-    
+
     pcYuvOrg->copyPartToPartYuv( pcYuv, uiPartAddr, iRoiWidth, iRoiHeight );
-    
-    pcYuv->removeHighFreq( pcYuvOther, uiPartAddr, iRoiWidth, iRoiHeight );
-    
+
+    pcYuv->removeHighFreq( pcYuvOther, uiPartAddr, iRoiWidth, iRoiHeight, pcCU->getSlice()->getSPS()->getBitDepths().recon, m_pcEncCfg->getClipForBiPredMeEnabled() );
+
     fWeight = 0.5;
   }
+
+  //  Search key pattern initialization
+  pcPatternKey->initPattern( pcYuv->getAddr  ( COMPONENT_Y, uiPartAddr ),
+                             iRoiWidth,
+                             iRoiHeight,
+                             pcYuv->getStride(COMPONENT_Y),
+                             pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) );
+
+  Pel*        piRefY      = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getAddr( COMPONENT_Y, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu() + uiPartAddr );
+  Int         iRefStride  = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getStride(COMPONENT_Y);
+
+  TComMv      cMvPred = *pcMvPred;
+#if NH_MV
+  m_vertRestriction =  m_pcEncCfg->getUseDisparitySearchRangeRestriction()  && ( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPOC() == pcCU->getSlice()->getPOC() );
+#endif
   
-  //  Search key pattern initialization
-  pcPatternKey->initPattern( pcYuv->getLumaAddr( uiPartAddr ),
-                            pcYuv->getCbAddr  ( uiPartAddr ),
-                            pcYuv->getCrAddr  ( uiPartAddr ),
-                            iRoiWidth,
-                            iRoiHeight,
-                            pcYuv->getStride(),
-                            0, 0 );
-  
-  Pel*        piRefY      = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr );
-  Int         iRefStride  = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getStride();
-  
-  TComMv      cMvPred = *pcMvPred;
-  
-#if H_MV
-  Bool motVecVertRngRestricted = false;
-  if( m_pcEncCfg->getUseDisparitySearchRangeRestriction()
-       &&
-      pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPOC() == pcCU->getSlice()->getPOC()
-    )
-  {
-      motVecVertRngRestricted = true;
-  }
-  if ( bBi )  xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB, motVecVertRngRestricted, m_pcEncCfg->getVerticalDisparitySearchRange() );
-  else        xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB, motVecVertRngRestricted, m_pcEncCfg->getVerticalDisparitySearchRange() );
-#else
-  if ( bBi )  xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
-  else        xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
-#endif
-  
-  m_pcRdCost->getMotionCost ( 1, 0 );
-  
+  if ( bBi )
+  {
+    xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  }
+  else
+  {
+    xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  }
+
+  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
+
   m_pcRdCost->setPredictor  ( *pcMvPred );
 #if H_3D_IC
   if( pcCU->getSlice()->getIsDepth() )
+  {
     m_pcRdCost->setCostScale  ( 0 );
+  }
   else
-#endif
-  m_pcRdCost->setCostScale  ( 2 );
+  {
+#endif
+    m_pcRdCost->setCostScale  ( 2 );    
+#if H_3D_IC
+  }
+#endif
+
 
   setWpScalingDistParam( pcCU, iRefIdxPred, eRefPicList );
@@ -5360,8 +5130,17 @@
   {
     rcMv = *pcMvPred;
-    xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
-  }
-  
-  m_pcRdCost->getMotionCost( 1, 0 );
+    const TComMv *pIntegerMv2Nx2NPred=0;
+    if (pcCU->getPartitionSize(0) != SIZE_2Nx2N || pcCU->getDepth(0) != 0)
+    {
+      pIntegerMv2Nx2NPred = &(m_integerMv2Nx2N[eRefPicList][iRefIdxPred]);
+    }
+    xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost, pIntegerMv2Nx2NPred );
+    if (pcCU->getPartitionSize(0) == SIZE_2Nx2N)
+    {
+      m_integerMv2Nx2N[eRefPicList][iRefIdxPred] = rcMv;
+    }
+  }
+
+  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
 #if H_3D_IC
   if( ! pcCU->getSlice()->getIsDepth() )
@@ -5369,9 +5148,8 @@
 #endif
   m_pcRdCost->setCostScale ( 1 );
-  
-    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost,bBi );
-  
-  
-  
+
+  const Bool bIsLosslessCoded = pcCU->getCUTransquantBypass(uiPartAddr) != 0;
+  xPatternSearchFracDIF( bIsLosslessCoded, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost );
+
   m_pcRdCost->setCostScale( 0 );
   rcMv <<= 2;
@@ -5381,25 +5159,25 @@
   }
 #endif
-  
+
   UInt uiMvBits = m_pcRdCost->getBits( rcMv.getHor(), rcMv.getVer() );
 #if H_3D_IC
   if( pcCU->getSlice()->getIsDepth() )
+  {
     ruiCost += m_pcRdCost->getCost( uiMvBits );
+  }
 #endif
   ruiBits      += uiMvBits;
-  ruiCost       = (UInt)( floor( fWeight * ( (Double)ruiCost - (Double)m_pcRdCost->getCost( uiMvBits ) ) ) + (Double)m_pcRdCost->getCost( ruiBits ) );
+  ruiCost       = (Distortion)( floor( fWeight * ( (Double)ruiCost - (Double)m_pcRdCost->getCost( uiMvBits ) ) ) + (Double)m_pcRdCost->getCost( ruiBits ) );
 }
 
 
-#if H_MV
-Void TEncSearch::xSetSearchRange ( TComDataCU* pcCU, TComMv& cMvPred, Int iSrchRng, TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB, Bool bMv_VRng_Restricted, Int iVerDispSrchRng )
-#else
 Void TEncSearch::xSetSearchRange ( TComDataCU* pcCU, TComMv& cMvPred, Int iSrchRng, TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB )
-#endif
 {
   Int  iMvShift = 2;
 #if H_3D_IC
   if( pcCU->getSlice()->getIsDepth() )
+  {
     iMvShift = 0;
+  }
 #endif
   TComMv cTmpMvPred = cMvPred;
@@ -5408,13 +5186,15 @@
   rcMvSrchRngLT.setHor( cTmpMvPred.getHor() - (iSrchRng << iMvShift) );
   rcMvSrchRngLT.setVer( cTmpMvPred.getVer() - (iSrchRng << iMvShift) );
-  
+
   rcMvSrchRngRB.setHor( cTmpMvPred.getHor() + (iSrchRng << iMvShift) );
   rcMvSrchRngRB.setVer( cTmpMvPred.getVer() + (iSrchRng << iMvShift) );
   
-#if H_MV
-  if ( bMv_VRng_Restricted ) {
-    Int iRestrictMvVrange = ( iVerDispSrchRng - 1 ) << iMvShift ; // -1 to consider subpel search
-    if ( rcMvSrchRngRB.getVer() >= iRestrictMvVrange  ){
-      rcMvSrchRngRB.setVer( iRestrictMvVrange ); //only positive side is restricted
+#if NH_MV
+  if ( m_vertRestriction )
+  {
+    Int mvRestricted = ( m_pcEncCfg->getVerticalDisparitySearchRange() - 1 ) << iMvShift ; // -1 to consider subpel search
+    if ( rcMvSrchRngRB.getVer() >= mvRestricted  )
+    {
+      rcMvSrchRngRB.setVer( mvRestricted ); //only positive side is restricted
     }
   }
@@ -5423,10 +5203,13 @@
   pcCU->clipMv        ( rcMvSrchRngLT );
   pcCU->clipMv        ( rcMvSrchRngRB );
-  
+
   rcMvSrchRngLT >>= iMvShift;
   rcMvSrchRngRB >>= iMvShift;
 }
 
-Void TEncSearch::xPatternSearch( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+
+
+
+Void TEncSearch::xPatternSearch( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, Distortion& ruiSAD )
 {
   Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
@@ -5434,15 +5217,15 @@
   Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
   Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
-  
-  UInt  uiSad;
-  UInt  uiSadBest         = MAX_UINT;
-  Int   iBestX = 0;
-  Int   iBestY = 0;
-  
+
+  Distortion  uiSad;
+  Distortion  uiSadBest = std::numeric_limits<Distortion>::max();
+  Int         iBestX = 0;
+  Int         iBestY = 0;
+
   Pel*  piRefSrch;
-  
+
   //-- jclee for using the SAD function pointer
   m_pcRdCost->setDistParam( pcPatternKey, piRefY, iRefStride,  m_cDistParam );
-  
+
   // fast encoder decision: use subsampled SAD for integer ME
   if ( m_pcEncCfg->getUseFastEnc() )
@@ -5453,5 +5236,5 @@
     }
   }
-  
+
   piRefY += (iSrchRngVerTop * iRefStride);
   for ( Int y = iSrchRngVerTop; y <= iSrchRngVerBottom; y++ )
@@ -5463,5 +5246,8 @@
       m_cDistParam.pCur = piRefSrch;
 
-      setDistParamComp(0);
+      setDistParamComp(COMPONENT_Y);
+
+      m_cDistParam.bitDepth = pcPatternKey->getBitDepthY();
+
 #if H_3D_IC
       m_cDistParam.bUseIC = pcPatternKey->getICFlag();
@@ -5470,10 +5256,10 @@
       m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
 #endif
-      m_cDistParam.bitDepth = g_bitDepthY;
+
       uiSad = m_cDistParam.DistFunc( &m_cDistParam );
-      
+
       // motion cost
       uiSad += m_pcRdCost->getCost( x, y );
-      
+
       if ( uiSad < uiSadBest )
       {
@@ -5485,23 +5271,39 @@
     piRefY += iRefStride;
   }
-  
+
   rcMv.set( iBestX, iBestY );
-  
+
   ruiSAD = uiSadBest - m_pcRdCost->getCost( iBestX, iBestY );
   return;
 }
 
-Void TEncSearch::xPatternSearchFast( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+
+
+Void TEncSearch::xPatternSearchFast( TComDataCU*   pcCU,
+                                     TComPattern*  pcPatternKey,
+                                     Pel*          piRefY,
+                                     Int           iRefStride,
+                                     TComMv*       pcMvSrchRngLT,
+                                     TComMv*       pcMvSrchRngRB,
+                                     TComMv       &rcMv,
+                                     Distortion   &ruiSAD,
+                                     const TComMv* pIntegerMv2Nx2NPred )
 {
-  pcCU->getMvPredLeft       ( m_acMvPredictors[0] );
-  pcCU->getMvPredAbove      ( m_acMvPredictors[1] );
-  pcCU->getMvPredAboveRight ( m_acMvPredictors[2] );
-  
+  assert (MD_LEFT < NUM_MV_PREDICTORS);
+  pcCU->getMvPredLeft       ( m_acMvPredictors[MD_LEFT] );
+  assert (MD_ABOVE < NUM_MV_PREDICTORS);
+  pcCU->getMvPredAbove      ( m_acMvPredictors[MD_ABOVE] );
+  assert (MD_ABOVE_RIGHT < NUM_MV_PREDICTORS);
+  pcCU->getMvPredAboveRight ( m_acMvPredictors[MD_ABOVE_RIGHT] );
+
   switch ( m_iFastSearch )
   {
     case 1:
-      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD );
+      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD, pIntegerMv2Nx2NPred );
       break;
-      
+
+    case 2:
+      xTZSearchSelective( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD, pIntegerMv2Nx2NPred );
+      break;
     default:
       break;
@@ -5509,5 +5311,16 @@
 }
 
-Void TEncSearch::xTZSearch( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+
+
+
+Void TEncSearch::xTZSearch( TComDataCU*  pcCU,
+                            TComPattern* pcPatternKey,
+                            Pel*         piRefY,
+                            Int          iRefStride,
+                            TComMv*      pcMvSrchRngLT,
+                            TComMv*      pcMvSrchRngRB,
+                            TComMv      &rcMv,
+                            Distortion  &ruiSAD,
+                            const TComMv* pIntegerMv2Nx2NPred )
 {
   Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
@@ -5515,7 +5328,7 @@
   Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
   Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
-  
+
   TZ_SEARCH_CONFIGURATION
-  
+
   UInt uiSearchRange = m_iSearchRange;
   pcCU->clipMv( rcMv );
@@ -5523,5 +5336,5 @@
   if( ! pcCU->getSlice()->getIsDepth() )
 #endif
-    rcMv >>= 2;
+  rcMv >>= 2;
   // init TZSearchStruct
   IntTZSearchStruct cStruct;
@@ -5529,12 +5342,12 @@
   cStruct.piRefY      = piRefY;
   cStruct.uiBestSad   = MAX_UINT;
-  
+
   // set rcMv (Median predictor) as start point and as best point
   xTZSearchHelp( pcPatternKey, cStruct, rcMv.getHor(), rcMv.getVer(), 0, 0 );
-  
+
   // test whether one of PRED_A, PRED_B, PRED_C MV is better start point than Median predictor
   if ( bTestOtherPredictedMV )
   {
-    for ( UInt index = 0; index < 3; index++ )
+    for ( UInt index = 0; index < NUM_MV_PREDICTORS; index++ )
     {
       TComMv cMv = m_acMvPredictors[index];
@@ -5542,10 +5355,15 @@
 #if H_3D_IC
       if( ! pcCU->getSlice()->getIsDepth() )
-#endif
-      cMv >>= 2;
+      {      
+#endif
+        cMv >>= 2;
+#if H_3D_IC
+      }
+#endif
+
       xTZSearchHelp( pcPatternKey, cStruct, cMv.getHor(), cMv.getVer(), 0, 0 );
     }
   }
-  
+
   // test whether zero Mv is better start point than Median predictor
   if ( bTestZeroVector )
@@ -5553,10 +5371,31 @@
     xTZSearchHelp( pcPatternKey, cStruct, 0, 0, 0, 0 );
   }
-  
+
+  if (pIntegerMv2Nx2NPred != 0)
+  {
+    TComMv integerMv2Nx2NPred = *pIntegerMv2Nx2NPred;
+    integerMv2Nx2NPred <<= 2;
+    pcCU->clipMv( integerMv2Nx2NPred );
+    integerMv2Nx2NPred >>= 2;
+    xTZSearchHelp(pcPatternKey, cStruct, integerMv2Nx2NPred.getHor(), integerMv2Nx2NPred.getVer(), 0, 0);
+
+    // reset search range
+    TComMv cMvSrchRngLT;
+    TComMv cMvSrchRngRB;
+    Int iSrchRng = m_iSearchRange;
+    TComMv currBestMv(cStruct.iBestX, cStruct.iBestY );
+    currBestMv <<= 2;
+    xSetSearchRange( pcCU, currBestMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+    iSrchRngHorLeft   = cMvSrchRngLT.getHor();
+    iSrchRngHorRight  = cMvSrchRngRB.getHor();
+    iSrchRngVerTop    = cMvSrchRngLT.getVer();
+    iSrchRngVerBottom = cMvSrchRngRB.getVer();
+  }
+
   // start search
   Int  iDist = 0;
   Int  iStartX = cStruct.iBestX;
   Int  iStartY = cStruct.iBestY;
-  
+
   // first search
   for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
@@ -5570,5 +5409,5 @@
       xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
     }
-    
+
     if ( bFirstSearchStop && ( cStruct.uiBestRound >= uiFirstSearchRounds ) ) // stop criterion
     {
@@ -5576,5 +5415,5 @@
     }
   }
-  
+
   // test whether zero Mv is a better start point than Median predictor
   if ( bTestZeroVectorStart && ((cStruct.iBestX != 0) || (cStruct.iBestY != 0)) )
@@ -5594,5 +5433,5 @@
     }
   }
-  
+
   // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
   if ( cStruct.uiBestDistance == 1 )
@@ -5601,5 +5440,5 @@
     xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
   }
-  
+
   // raster search if distance is too big
   if ( bEnableRasterSearch && ( ((Int)(cStruct.uiBestDistance) > iRaster) || bAlwaysRasterSearch ) )
@@ -5614,5 +5453,5 @@
     }
   }
-  
+
   // raster refinement
   if ( bRasterRefinementEnable && cStruct.uiBestDistance > 0 )
@@ -5634,5 +5473,5 @@
         }
       }
-      
+
       // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
       if ( cStruct.uiBestDistance == 1 )
@@ -5646,5 +5485,5 @@
     }
   }
-  
+
   // start refinement
   if ( bStarRefinementEnable && cStruct.uiBestDistance > 0 )
@@ -5671,5 +5510,5 @@
         }
       }
-      
+
       // calculate only 2 missing points instead 8 points if cStrukt.uiBestDistance == 1
       if ( cStruct.uiBestDistance == 1 )
@@ -5683,5 +5522,5 @@
     }
   }
-  
+
   // write out best match
   rcMv.set( cStruct.iBestX, cStruct.iBestY );
@@ -5689,103 +5528,255 @@
 }
 
-Void TEncSearch::xPatternSearchFracDIF(TComDataCU* pcCU,
+
+Void TEncSearch::xTZSearchSelective( TComDataCU*   pcCU,
+                                     TComPattern*  pcPatternKey,
+                                     Pel*          piRefY,
+                                     Int           iRefStride,
+                                     TComMv*       pcMvSrchRngLT,
+                                     TComMv*       pcMvSrchRngRB,
+                                     TComMv       &rcMv,
+                                     Distortion   &ruiSAD,
+                                     const TComMv* pIntegerMv2Nx2NPred )
+{
+  SEL_SEARCH_CONFIGURATION
+
+  Int   iSrchRngHorLeft         = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight        = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop          = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom       = pcMvSrchRngRB->getVer();
+  Int   iFirstSrchRngHorLeft    = 0;
+  Int   iFirstSrchRngHorRight   = 0;
+  Int   iFirstSrchRngVerTop     = 0;
+  Int   iFirstSrchRngVerBottom  = 0;
+  Int   iStartX                 = 0;
+  Int   iStartY                 = 0;
+  Int   iBestX                  = 0;
+  Int   iBestY                  = 0;
+  Int   iDist                   = 0;
+
+  pcCU->clipMv( rcMv );
+  rcMv >>= 2;
+  // init TZSearchStruct
+  IntTZSearchStruct cStruct;
+  cStruct.iYStride    = iRefStride;
+  cStruct.piRefY      = piRefY;
+  cStruct.uiBestSad   = MAX_UINT;
+  cStruct.iBestX = 0;
+  cStruct.iBestY = 0;
+
+
+  // set rcMv (Median predictor) as start point and as best point
+  xTZSearchHelp( pcPatternKey, cStruct, rcMv.getHor(), rcMv.getVer(), 0, 0 );
+
+  // test whether one of PRED_A, PRED_B, PRED_C MV is better start point than Median predictor
+  if ( bTestOtherPredictedMV )
+  {
+    for ( UInt index = 0; index < NUM_MV_PREDICTORS; index++ )
+    {
+      TComMv cMv = m_acMvPredictors[index];
+      pcCU->clipMv( cMv );
+      cMv >>= 2;
+      xTZSearchHelp( pcPatternKey, cStruct, cMv.getHor(), cMv.getVer(), 0, 0 );
+    }
+  }
+
+  // test whether zero Mv is better start point than Median predictor
+  if ( bTestZeroVector )
+  {
+    xTZSearchHelp( pcPatternKey, cStruct, 0, 0, 0, 0 );
+  }
+
+  if ( pIntegerMv2Nx2NPred != 0 )
+  {
+    TComMv integerMv2Nx2NPred = *pIntegerMv2Nx2NPred;
+    integerMv2Nx2NPred <<= 2;
+    pcCU->clipMv( integerMv2Nx2NPred );
+    integerMv2Nx2NPred >>= 2;
+    xTZSearchHelp(pcPatternKey, cStruct, integerMv2Nx2NPred.getHor(), integerMv2Nx2NPred.getVer(), 0, 0);
+
+    // reset search range
+    TComMv cMvSrchRngLT;
+    TComMv cMvSrchRngRB;
+    Int iSrchRng = m_iSearchRange;
+    TComMv currBestMv(cStruct.iBestX, cStruct.iBestY );
+    currBestMv <<= 2;
+    xSetSearchRange( pcCU, currBestMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+    iSrchRngHorLeft   = cMvSrchRngLT.getHor();
+    iSrchRngHorRight  = cMvSrchRngRB.getHor();
+    iSrchRngVerTop    = cMvSrchRngLT.getVer();
+    iSrchRngVerBottom = cMvSrchRngRB.getVer();
+  }
+
+  // Initial search
+  iBestX = cStruct.iBestX;
+  iBestY = cStruct.iBestY; 
+  iFirstSrchRngHorLeft    = ((iBestX - uiSearchRangeInitial) > iSrchRngHorLeft)   ? (iBestX - uiSearchRangeInitial) : iSrchRngHorLeft;
+  iFirstSrchRngVerTop     = ((iBestY - uiSearchRangeInitial) > iSrchRngVerTop)    ? (iBestY - uiSearchRangeInitial) : iSrchRngVerTop;
+  iFirstSrchRngHorRight   = ((iBestX + uiSearchRangeInitial) < iSrchRngHorRight)  ? (iBestX + uiSearchRangeInitial) : iSrchRngHorRight;  
+  iFirstSrchRngVerBottom  = ((iBestY + uiSearchRangeInitial) < iSrchRngVerBottom) ? (iBestY + uiSearchRangeInitial) : iSrchRngVerBottom;    
+
+  for ( iStartY = iFirstSrchRngVerTop; iStartY <= iFirstSrchRngVerBottom; iStartY += uiSearchStep )
+  {
+    for ( iStartX = iFirstSrchRngHorLeft; iStartX <= iFirstSrchRngHorRight; iStartX += uiSearchStep )
+    {
+      xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, 0 );
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, 1 );
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, 2 );
+    }
+  }
+
+  Int iMaxMVDistToPred = (abs(cStruct.iBestX - iBestX) > iMVDistThresh || abs(cStruct.iBestY - iBestY) > iMVDistThresh);
+
+  //full search with early exit if MV is distant from predictors
+  if ( bEnableRasterSearch && (iMaxMVDistToPred || bAlwaysRasterSearch) )
+  {
+    for ( iStartY = iSrchRngVerTop; iStartY <= iSrchRngVerBottom; iStartY += 1 )
+    {
+      for ( iStartX = iSrchRngHorLeft; iStartX <= iSrchRngHorRight; iStartX += 1 )
+      {
+        xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, 1 );
+      }
+    }
+  }
+  //Smaller MV, refine around predictor
+  else if ( bStarRefinementEnable && cStruct.uiBestDistance > 0 )
+  {
+    // start refinement
+    while ( cStruct.uiBestDistance > 0 )
+    {
+      iStartX = cStruct.iBestX;
+      iStartY = cStruct.iBestY;
+      cStruct.uiBestDistance = 0;
+      cStruct.ucPointNr = 0;
+      for ( iDist = 1; iDist < (Int)uiSearchRange + 1; iDist*=2 )
+      {
+        if ( bStarRefinementDiamond == 1 )
+        {
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        else
+        {
+          xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        if ( bStarRefinementStop && (cStruct.uiBestRound >= uiStarRefinementRounds) ) // stop criterion
+        {
+          break;
+        }
+      }
+
+      // calculate only 2 missing points instead 8 points if cStrukt.uiBestDistance == 1
+      if ( cStruct.uiBestDistance == 1 )
+      {
+        cStruct.uiBestDistance = 0;
+        if ( cStruct.ucPointNr != 0 )
+        {
+          xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+        }
+      }
+    }
+  }
+
+  // write out best match
+  rcMv.set( cStruct.iBestX, cStruct.iBestY );
+  ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCost( cStruct.iBestX, cStruct.iBestY );
+
+}
+
+
+Void TEncSearch::xPatternSearchFracDIF(
+                                       Bool         bIsLosslessCoded,
                                        TComPattern* pcPatternKey,
-                                       Pel* piRefY,
-                                       Int iRefStride,
-                                       TComMv* pcMvInt,
-                                       TComMv& rcMvHalf,
-                                       TComMv& rcMvQter,
-                                       UInt& ruiCost
-                                       ,Bool biPred
-                                       )
+                                       Pel*         piRefY,
+                                       Int          iRefStride,
+                                       TComMv*      pcMvInt,
+                                       TComMv&      rcMvHalf,
+                                       TComMv&      rcMvQter,
+                                       Distortion&  ruiCost
+                                      )
 {
   //  Reference pattern initialization (integer scale)
   TComPattern cPatternRoi;
   Int         iOffset    = pcMvInt->getHor() + pcMvInt->getVer() * iRefStride;
-  cPatternRoi.initPattern( piRefY +  iOffset,
-                          NULL,
-                          NULL,
+  cPatternRoi.initPattern(piRefY + iOffset,
                           pcPatternKey->getROIYWidth(),
                           pcPatternKey->getROIYHeight(),
                           iRefStride,
-                          0, 0 );
-  
+                          pcPatternKey->getBitDepthY());
+
   //  Half-pel refinement
-  xExtDIFUpSamplingH ( &cPatternRoi, biPred );
-  
+  xExtDIFUpSamplingH ( &cPatternRoi );
+
   rcMvHalf = *pcMvInt;   rcMvHalf <<= 1;    // for mv-cost
   TComMv baseRefMv(0, 0);
-  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 2, rcMvHalf   );
-  
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 2, rcMvHalf, !bIsLosslessCoded );
+
   m_pcRdCost->setCostScale( 0 );
-  
-  xExtDIFUpSamplingQ ( &cPatternRoi, rcMvHalf, biPred );
+
+  xExtDIFUpSamplingQ ( &cPatternRoi, rcMvHalf );
   baseRefMv = rcMvHalf;
   baseRefMv <<= 1;
-  
+
   rcMvQter = *pcMvInt;   rcMvQter <<= 1;    // for mv-cost
   rcMvQter += rcMvHalf;  rcMvQter <<= 1;
-  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 1, rcMvQter );
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 1, rcMvQter, !bIsLosslessCoded );
 }
 
-/** encode residual and calculate rate-distortion for a CU block
- * \param pcCU
- * \param pcYuvOrg
- * \param pcYuvPred
- * \param rpcYuvResi
- * \param rpcYuvResiBest
- * \param rpcYuvRec
- * \param bSkipRes
- * \returns Void
- */
-Void TEncSearch::encodeResAndCalcRdInterCU( TComDataCU* pcCU, TComYuv* pcYuvOrg, TComYuv* pcYuvPred, TComYuv*& rpcYuvResi, TComYuv*& rpcYuvResiBest, TComYuv*& rpcYuvRec, Bool bSkipRes )
+
+//! encode residual and calculate rate-distortion for a CU block
+Void TEncSearch::encodeResAndCalcRdInterCU( TComDataCU* pcCU, TComYuv* pcYuvOrg, TComYuv* pcYuvPred,
+                                            TComYuv* pcYuvResi, TComYuv* pcYuvResiBest, TComYuv* pcYuvRec,
+                                            Bool bSkipResidual DEBUG_STRING_FN_DECLARE(sDebug) )
 {
-  if ( pcCU->isIntra(0) )
-  {
-    return;
-  }
-  
-  Bool      bHighPass    = pcCU->getSlice()->getDepth() ? true : false;
-  UInt      uiBits       = 0, uiBitsBest = 0;
-#if H_3D_VSO
-  Dist      uiDistortion = 0, uiDistortionBest = 0;
+  assert ( !pcCU->isIntra(0) );
+
+  const UInt cuWidthPixels      = pcCU->getWidth ( 0 );
+  const UInt cuHeightPixels     = pcCU->getHeight( 0 );
+  const Int  numValidComponents = pcCU->getPic()->getNumberValidComponents();
+  const TComSPS &sps=*(pcCU->getSlice()->getSPS());
+
+  // The pcCU is not marked as skip-mode at this point, and its m_pcTrCoeff, m_pcArlCoeff, m_puhCbf, m_puhTrIdx will all be 0.
+  // due to prior calls to TComDataCU::initEstData(  );
+
+  if ( bSkipResidual ) //  No residual coding : SKIP mode
+  {
+    pcCU->setSkipFlagSubParts( true, 0, pcCU->getDepth(0) );
+
+    pcYuvResi->clear();
+
+    pcYuvPred->copyToPartYuv( pcYuvRec, 0 );
+#if NH_3D_VSO
+    Dist       distortion = 0;
 #else
-  UInt      uiDistortion = 0, uiDistortionBest = 0;
-#endif
-  
-  UInt      uiWidth      = pcCU->getWidth ( 0 );
-  UInt      uiHeight     = pcCU->getHeight( 0 );
-  
-  //  No residual coding : SKIP mode
-  if ( bSkipRes )
-  {
-    pcCU->setSkipFlagSubParts( true, 0, pcCU->getDepth(0) );
-
-    rpcYuvResi->clear();
-    
-    pcYuvPred->copyToPartYuv( rpcYuvRec, 0 );
-
-#if H_3D_VSO // M13
-    if ( m_pcRdCost->getUseVSO() )
-    {
-      uiDistortion = m_pcRdCost->getDistPartVSO( pcCU, 0, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight     , false );
-    }
-    else    
-    {
-#endif
-    uiDistortion = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
-#if H_3D_VSO // MIgnore
-    }
-#endif
-
-      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
-    
+    Distortion distortion = 0;
+#endif
+
+    for (Int comp=0; comp < numValidComponents; comp++)
+    {
+      const ComponentID compID=ComponentID(comp);
+      const UInt csx=pcYuvOrg->getComponentScaleX(compID);
+      const UInt csy=pcYuvOrg->getComponentScaleY(compID);
+#if NH_3D_VSO // M13
+      if ( m_pcRdCost->getUseVSO() )
+      {
+        distortion += m_pcRdCost->getDistPartVSO( pcCU, 0, sps.getBitDepth(toChannelType(compID)), pcYuvRec->getAddr(compID), pcYuvRec->getStride(compID), pcYuvOrg->getAddr(compID),
+          pcYuvOrg->getStride(compID), cuWidthPixels >> csx, cuHeightPixels >> csy, false );
+      }
+      else    
+      {
+#endif
+        distortion += m_pcRdCost->getDistPart( sps.getBitDepth(toChannelType(compID)), pcYuvRec->getAddr(compID), pcYuvRec->getStride(compID), pcYuvOrg->getAddr(compID),
+          pcYuvOrg->getStride(compID), cuWidthPixels >> csx, cuHeightPixels >> csy, compID);
+#if NH_3D_VSO // MIgnore
+      }
+#endif
+    }
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
     m_pcEntropyCoder->resetBits();
+
     if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
     {
       m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
     }
+
     m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
     m_pcEntropyCoder->encodeMergeIndex( pcCU, 0, true );
@@ -5796,245 +5787,186 @@
     m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
 #endif
-    uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    UInt uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
     pcCU->getTotalBits()       = uiBits;
-    pcCU->getTotalDistortion() = uiDistortion;
-#if H_3D_VSO //M 14
+    pcCU->getTotalDistortion() = distortion;
+#if NH_3D_VSO //M 14
     if ( m_pcRdCost->getUseLambdaScaleVSO() )    
-      pcCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );    
+    {
+      pcCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( uiBits, distortion );    
+    }
     else
 #endif    
-    pcCU->getTotalCost() = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
-
-      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
-    
-    pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
-    pcCU->setTrIdxSubParts( 0, 0, pcCU->getDepth(0) );
-
-#if H_3D_VSO // necessary? // M15
+      pcCU->getTotalCost()       = m_pcRdCost->calcRdCost( uiBits, distortion );
+
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
+
+#if DEBUG_STRING
+    pcYuvResiBest->clear(); // Clear the residual image, if we didn't code it.
+    for(UInt i=0; i<MAX_NUM_COMPONENT+1; i++)
+    {
+      sDebug+=debug_reorder_data_inter_token[i];
+    }
+#endif
+
+#if NH_3D_VSO // necessary? // M15
     // set Model
-    if( !m_pcRdCost->getUseEstimatedVSD()&& m_pcRdCost->getUseRenModel() )
-    {
-      Pel*  piSrc       = rpcYuvRec->getLumaAddr();
-      UInt  uiSrcStride = rpcYuvRec->getStride();
-      m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
-    }
-#endif
-
+    if( !m_pcRdCost->getUseEstimatedVSD() && m_pcRdCost->getUseRenModel() )
+    {      
+      const UInt csx    = pcYuvRec->getComponentScaleX( COMPONENT_Y );
+      const UInt csy    = pcYuvRec->getComponentScaleY( COMPONENT_Y );
+
+      Pel*  piSrc       = pcYuvRec->getAddr  ( COMPONENT_Y );
+      UInt  uiSrcStride = pcYuvRec->getStride( COMPONENT_Y );
+      m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, cuWidthPixels >> csx, cuHeightPixels >> csy);
+    }
+#endif
     return;
   }
-  
+
   //  Residual coding.
-  Int    qp, qpBest = 0, qpMin, qpMax;
-  Double  dCost, dCostBest = MAX_DOUBLE;
-  
-  UInt uiTrLevel = 0;
-  if( (pcCU->getWidth(0) > pcCU->getSlice()->getSPS()->getMaxTrSize()) )
-  {
-    while( pcCU->getWidth(0) > (pcCU->getSlice()->getSPS()->getMaxTrSize()<<uiTrLevel) ) uiTrLevel++;
-  }
-  UInt uiMaxTrMode = 1 + uiTrLevel;
-  
-  while((uiWidth>>uiMaxTrMode) < (g_uiMaxCUWidth>>g_uiMaxCUDepth)) uiMaxTrMode--;
-  
-  qpMin =  bHighPass ? Clip3( -pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, pcCU->getQP(0) - m_iMaxDeltaQP ) : pcCU->getQP( 0 );
-  qpMax =  bHighPass ? Clip3( -pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, pcCU->getQP(0) + m_iMaxDeltaQP ) : pcCU->getQP( 0 );
-
-  rpcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, uiWidth );
-
-  for ( qp = qpMin; qp <= qpMax; qp++ )
-  {
-    dCost = 0.;
-    uiBits = 0;
-    uiDistortion = 0;
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
-
-#if H_3D_VSO // M16 // M18
-    Dist uiZeroDistortion = 0;
-    if ( m_pcRdCost->getUseVSO() )  // This creating and destroying need to be fixed. 
-    {
-      m_cYuvRecTemp.create( pcYuvPred->getWidth(), pcYuvPred->getHeight()  );
-    }
-
-    xEstimateResidualQT( pcCU, 0, 0, 0, pcYuvOrg, pcYuvPred, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
-    
-    if ( m_pcRdCost->getUseVSO() )
-    {
-      m_cYuvRecTemp.destroy();
-    }
+
+   pcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, cuWidthPixels );
+
+  TComTURecurse tuLevel0(pcCU, 0);
+
+  Double     nonZeroCost       = 0;
+  UInt       nonZeroBits       = 0;
+#if NH_3D_VSO
+  Dist       nonZeroDistortion = 0;
+  Dist       zeroDistortion    = 0;
 #else
-    UInt uiZeroDistortion = 0;
-    xEstimateResidualQT( pcCU, 0, 0, 0, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
-#endif
-    
-    m_pcEntropyCoder->resetBits();
-    m_pcEntropyCoder->encodeQtRootCbfZero( pcCU );
-    UInt zeroResiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
-
-#if H_3D_VSO  // M19
-    Double dZeroCost; 
+  Distortion nonZeroDistortion = 0;
+  Distortion zeroDistortion    = 0;
+#endif
+
+  m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
+#if NH_3D_VSO // M16 // M18  
+  if ( m_pcRdCost->getUseVSO() )  // This creating and destroying need to be fixed. 
+  {
+    m_cYuvRecTemp.create( pcYuvPred->getWidth( COMPONENT_Y ), pcYuvPred->getHeight( COMPONENT_Y ), CHROMA_400  );
+  }
+
+  xEstimateInterResidualQT( pcYuvResi,  pcYuvOrg, pcYuvPred, nonZeroCost, nonZeroBits, nonZeroDistortion, &zeroDistortion, tuLevel0 DEBUG_STRING_PASS_INTO(sDebug) );    
+
+  if ( m_pcRdCost->getUseVSO() )
+  {
+    m_cYuvRecTemp.destroy();
+  }
+#else
+  xEstimateInterResidualQT( pcYuvResi,  nonZeroCost, nonZeroBits, nonZeroDistortion, &zeroDistortion, tuLevel0 DEBUG_STRING_PASS_INTO(sDebug) );
+#endif
+  // -------------------------------------------------------
+  // set the coefficients in the pcCU, and also calculates the residual data.
+  // If a block full of 0's is efficient, then just use 0's.
+  // The costs at this point do not include header bits.
+
+  m_pcEntropyCoder->resetBits();
+  m_pcEntropyCoder->encodeQtRootCbfZero( );
+  const UInt   zeroResiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+#if NH_3D_VSO  // M19
+    Double zeroCost; 
     if( m_pcRdCost->getUseLambdaScaleVSO() )    
-      dZeroCost = m_pcRdCost->calcRdCostVSO( 0, uiZeroDistortion );
+    {
+      zeroCost = (pcCU->isLosslessCoded( 0 )) ? (nonZeroCost+1) : (m_pcRdCost->calcRdCostVSO( zeroResiBits, zeroDistortion ));
+    }
     else
-      dZeroCost = m_pcRdCost->calcRdCost( zeroResiBits, uiZeroDistortion );
+    {
+      zeroCost = (pcCU->isLosslessCoded( 0 )) ? (nonZeroCost+1) : (m_pcRdCost->calcRdCost( zeroResiBits, zeroDistortion ));
+    }
 #else 
-    Double dZeroCost = m_pcRdCost->calcRdCost( zeroResiBits, uiZeroDistortion );
-#endif
-    if(pcCU->isLosslessCoded( 0 ))
-    {  
-      dZeroCost = dCost + 1;
-    }
+  const Double zeroCost     = (pcCU->isLosslessCoded( 0 )) ? (nonZeroCost+1) : (m_pcRdCost->calcRdCost( zeroResiBits, zeroDistortion ));
+#endif
 #if H_3D_SPIVMP
     if ( dZeroCost < dCost || pcCU->getQtRootCbf(0)==0)
 #else
-    if ( dZeroCost < dCost )
-#endif
-    {
-      dCost        = dZeroCost;
-      uiBits       = 0;
-      uiDistortion = uiZeroDistortion;
-      
-      const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
-      ::memset( pcCU->getTransformIdx()      , 0, uiQPartNum * sizeof(UChar) );
-      ::memset( pcCU->getCbf( TEXT_LUMA )    , 0, uiQPartNum * sizeof(UChar) );
-      ::memset( pcCU->getCbf( TEXT_CHROMA_U ), 0, uiQPartNum * sizeof(UChar) );
-      ::memset( pcCU->getCbf( TEXT_CHROMA_V ), 0, uiQPartNum * sizeof(UChar) );
-      ::memset( pcCU->getCoeffY()            , 0, uiWidth * uiHeight * sizeof( TCoeff )      );
-      ::memset( pcCU->getCoeffCb()           , 0, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
-      ::memset( pcCU->getCoeffCr()           , 0, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
-      pcCU->setTransformSkipSubParts ( 0, 0, 0, 0, pcCU->getDepth(0) );
+  if ( zeroCost < nonZeroCost || !pcCU->getQtRootCbf(0) )
+#endif
+  {
+    const UInt uiQPartNum = tuLevel0.GetAbsPartIdxNumParts();
+    ::memset( pcCU->getTransformIdx()     , 0, uiQPartNum * sizeof(UChar) );
+    for (Int comp=0; comp < numValidComponents; comp++)
+    {
+      const ComponentID component = ComponentID(comp);
+      ::memset( pcCU->getCbf( component ) , 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCrossComponentPredictionAlpha(component), 0, ( uiQPartNum * sizeof(Char) ) );
+    }
+    static const UInt useTS[MAX_NUM_COMPONENT]={0,0,0};
+    pcCU->setTransformSkipSubParts ( useTS, 0, pcCU->getDepth(0) );
+#if DEBUG_STRING
+    sDebug.clear();
+    for(UInt i=0; i<MAX_NUM_COMPONENT+1; i++)
+    {
+      sDebug+=debug_reorder_data_inter_token[i];
+    }
+#endif
+  }
+  else
+  {
+    xSetInterResidualQTData( NULL, false, tuLevel0); // Call first time to set coefficients.
+  }
+
+  // all decisions now made. Fully encode the CU, including the headers:
+  m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+
+  UInt finalBits = 0;
+  xAddSymbolBitsInter( pcCU, finalBits );
+  // we've now encoded the pcCU, and so have a valid bit cost
+
+  if ( !pcCU->getQtRootCbf( 0 ) )
+  {
+    pcYuvResiBest->clear(); // Clear the residual image, if we didn't code it.
+  }
+  else
+  {
+    xSetInterResidualQTData( pcYuvResiBest, true, tuLevel0 ); // else set the residual image data pcYUVResiBest from the various temp images.
+  }
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+
+  pcYuvRec->addClip ( pcYuvPred, pcYuvResiBest, 0, cuWidthPixels, sps.getBitDepths() );
+
+  // update with clipped distortion and cost (previously unclipped reconstruction values were used)
+
+#if NH_3D_VSO
+  Dist finalDistortion = 0;
+#else
+  Distortion finalDistortion = 0;
+#endif
+  for(Int comp=0; comp<numValidComponents; comp++)
+  {  
+    const ComponentID compID=ComponentID(comp);
+#if NH_3D_VSO    // M22 // GT: might be removed since VSO already provided clipped distortion
+    if ( m_pcRdCost->getUseVSO() )
+    {
+      finalDistortion += m_pcRdCost->getDistPartVSO  ( pcCU, 0, sps.getBitDepth(toChannelType(compID)),  pcYuvRec->getAddr( compID ), pcYuvRec->getStride( compID ),  pcYuvOrg->getAddr( compID ), pcYuvOrg->getStride( compID ), cuWidthPixels >> pcYuvOrg->getComponentScaleX(compID), cuHeightPixels >> pcYuvOrg->getComponentScaleY(compID), false );
     }
     else
     {
-      xSetResidualQTData( pcCU, 0, 0, 0, NULL, pcCU->getDepth(0), false );
-    }
-    
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
-
-    uiBits = 0;
-    {
-      TComYuv *pDummy = NULL;
-      xAddSymbolBitsInter( pcCU, 0, 0, uiBits, pDummy, NULL, pDummy );
-    }
-    
-#if H_3D_VSO // M20
-    Double dExactCost; 
-    if( m_pcRdCost->getUseLambdaScaleVSO() )    
-      dExactCost = m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );    
-    else
-      dExactCost = m_pcRdCost->calcRdCost   ( uiBits, uiDistortion );
-#else    
-    Double dExactCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
-#endif
-    dCost = dExactCost;
-    
-    if ( dCost < dCostBest )
-    {
-      if ( !pcCU->getQtRootCbf( 0 ) )
-      {
-        rpcYuvResiBest->clear();
-      }
-      else
-      {
-        xSetResidualQTData( pcCU, 0, 0, 0, rpcYuvResiBest, pcCU->getDepth(0), true );
-      }
-      
-      if( qpMin != qpMax && qp != qpMax )
-      {
-        const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
-        ::memcpy( m_puhQTTempTrIdx, pcCU->getTransformIdx(),        uiQPartNum * sizeof(UChar) );
-        ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA ),     uiQPartNum * sizeof(UChar) );
-        ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ), uiQPartNum * sizeof(UChar) );
-        ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ), uiQPartNum * sizeof(UChar) );
-        ::memcpy( m_pcQTTempCoeffY,  pcCU->getCoeffY(),  uiWidth * uiHeight * sizeof( TCoeff )      );
-        ::memcpy( m_pcQTTempCoeffCb, pcCU->getCoeffCb(), uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
-        ::memcpy( m_pcQTTempCoeffCr, pcCU->getCoeffCr(), uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
-#if ADAPTIVE_QP_SELECTION
-        ::memcpy( m_pcQTTempArlCoeffY,  pcCU->getArlCoeffY(),  uiWidth * uiHeight * sizeof( Int )      );
-        ::memcpy( m_pcQTTempArlCoeffCb, pcCU->getArlCoeffCb(), uiWidth * uiHeight * sizeof( Int ) >> 2 );
-        ::memcpy( m_pcQTTempArlCoeffCr, pcCU->getArlCoeffCr(), uiWidth * uiHeight * sizeof( Int ) >> 2 );
-#endif
-        ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA),     uiQPartNum * sizeof( UChar ) );
-        ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U), uiQPartNum * sizeof( UChar ) );
-        ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V), uiQPartNum * sizeof( UChar ) );
-      }
-      uiBitsBest       = uiBits;
-      uiDistortionBest = uiDistortion;
-      dCostBest        = dCost;
-      qpBest           = qp;
-        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
-      }
-#if H_3D_VSO // M21
-    if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
-    {
-      Pel*  piSrc       = pcYuvOrg->getLumaAddr();
-      UInt  uiSrcStride = pcYuvOrg->getStride();
-      m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
-    }
-#endif
-  }
-  assert ( dCostBest != MAX_DOUBLE );
-  
-  if( qpMin != qpMax && qpBest != qpMax )
-  {
-      assert( 0 ); // check
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
-    // copy best cbf and trIdx to pcCU
-    const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
-    ::memcpy( pcCU->getTransformIdx(),       m_puhQTTempTrIdx,  uiQPartNum * sizeof(UChar) );
-    ::memcpy( pcCU->getCbf( TEXT_LUMA ),     m_puhQTTempCbf[0], uiQPartNum * sizeof(UChar) );
-    ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ), m_puhQTTempCbf[1], uiQPartNum * sizeof(UChar) );
-    ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ), m_puhQTTempCbf[2], uiQPartNum * sizeof(UChar) );
-    ::memcpy( pcCU->getCoeffY(),  m_pcQTTempCoeffY,  uiWidth * uiHeight * sizeof( TCoeff )      );
-    ::memcpy( pcCU->getCoeffCb(), m_pcQTTempCoeffCb, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
-    ::memcpy( pcCU->getCoeffCr(), m_pcQTTempCoeffCr, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
-#if ADAPTIVE_QP_SELECTION
-    ::memcpy( pcCU->getArlCoeffY(),  m_pcQTTempArlCoeffY,  uiWidth * uiHeight * sizeof( Int )      );
-    ::memcpy( pcCU->getArlCoeffCb(), m_pcQTTempArlCoeffCb, uiWidth * uiHeight * sizeof( Int ) >> 2 );
-    ::memcpy( pcCU->getArlCoeffCr(), m_pcQTTempArlCoeffCr, uiWidth * uiHeight * sizeof( Int ) >> 2 );
-#endif
-    ::memcpy( pcCU->getTransformSkip(TEXT_LUMA),     m_puhQTTempTransformSkipFlag[0], uiQPartNum * sizeof( UChar ) );
-    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_U), m_puhQTTempTransformSkipFlag[1], uiQPartNum * sizeof( UChar ) );
-    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_V), m_puhQTTempTransformSkipFlag[2], uiQPartNum * sizeof( UChar ) );
-  }
-  rpcYuvRec->addClip ( pcYuvPred, rpcYuvResiBest, 0, uiWidth );
-
-#if H_3D_VSO  // M22 // GT: might be removed since VSO already provided clipped distortion
-  if ( m_pcRdCost->getUseVSO() )
-  {
-    uiDistortionBest = m_pcRdCost->getDistPartVSO  ( pcCU, 0, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight, false );
+#endif      
+      finalDistortion += m_pcRdCost->getDistPart( sps.getBitDepth(toChannelType(compID)), pcYuvRec->getAddr(compID ), pcYuvRec->getStride(compID ), pcYuvOrg->getAddr(compID ), pcYuvOrg->getStride(compID), cuWidthPixels >> pcYuvOrg->getComponentScaleX(compID), cuHeightPixels >> pcYuvOrg->getComponentScaleY(compID), compID);
+#if NH_3D_VSO // M23
+    }
+#endif
+  }
+
+  pcCU->getTotalBits()       = finalBits;
+  pcCU->getTotalDistortion() = finalDistortion;
+#if NH_3D_VSO 
+  if ( m_pcRdCost->getUseLambdaScaleVSO() )
+  {
+    pcCU->getTotalCost()       = m_pcRdCost->calcRdCostVSO( finalBits, finalDistortion );
   }
   else
-  {
-#endif
-  // update with clipped distortion and cost (qp estimation loop uses unclipped values)
-    uiDistortionBest = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
-    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
-#if H_3D_VSO // M23
-  }
-  if ( m_pcRdCost->getUseLambdaScaleVSO() )
-    dCostBest = m_pcRdCost->calcRdCostVSO( uiBitsBest, uiDistortionBest );
-  else
-#endif
-  dCostBest = m_pcRdCost->calcRdCost( uiBitsBest, uiDistortionBest );
-  
-  pcCU->getTotalBits()       = uiBitsBest;
-  pcCU->getTotalDistortion() = uiDistortionBest;
-  pcCU->getTotalCost()       = dCostBest;
-  
-  if ( pcCU->isSkipped(0) )
-  {
-    pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
-  }
-  
-  pcCU->setQPSubParts( qpBest, 0, pcCU->getDepth(0) );
-#if H_3D_VSO // M24 // necessary??
+#endif
+    pcCU->getTotalCost()       = m_pcRdCost->calcRdCost( finalBits, finalDistortion );
+
+#if NH_3D_VSO // M24 // necessary??
   if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
   {
-    Pel*  piSrc       = rpcYuvRec->getLumaAddr();
-    UInt  uiSrcStride = rpcYuvRec->getStride();
-    m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
-  }
-#endif
+    Pel*  piSrc       = pcYuvRec->getAddr  ( COMPONENT_Y );
+    UInt  uiSrcStride = pcYuvRec->getStride( COMPONENT_Y );
+    m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, cuWidthPixels >> pcYuvOrg->getComponentScaleX(COMPONENT_Y), cuHeightPixels >> pcYuvOrg->getComponentScaleY(COMPONENT_Y));
+  }
+#endif
+
 }
 
@@ -6179,762 +6111,558 @@
 #endif
 
-#if H_3D_VSO // M25
-Void TEncSearch::xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, Dist &ruiDist, Dist *puiZeroDist )
+
+Void TEncSearch::xEstimateInterResidualQT( TComYuv    *pcResi,
+#if NH_3D_VSO // M25
+                                           TComYuv    *pcOrg,
+                                           TComYuv    *pcPred,
+#endif
+                                           Double     &rdCost,
+                                           UInt       &ruiBits,
+#if NH_3D_VSO
+                                           Dist       &ruiDist,
+                                           Dist       *puiZeroDist,
 #else
-Void TEncSearch::xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist )
-#endif
+                                           Distortion &ruiDist,
+                                           Distortion *puiZeroDist,
+#endif
+                                           TComTU     &rTu
+                                           DEBUG_STRING_FN_DECLARE(sDebug) )
 {
-  const UInt uiTrMode = uiDepth - pcCU->getDepth( 0 );
-  
+  TComDataCU *pcCU        = rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiDepth      = rTu.GetTransformDepthTotal();
+  const UInt uiTrMode     = rTu.GetTransformDepthRel();
+  const UInt subTUDepth   = uiTrMode + 1;
+  const UInt numValidComp = pcCU->getPic()->getNumberValidComponents();
+  DEBUG_STRING_NEW(sSingleStringComp[MAX_NUM_COMPONENT])
+
   assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
-  const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
-  
-  UInt SplitFlag = ((pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ));
+  const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+
+  UInt SplitFlag = ((pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && pcCU->isInter(uiAbsPartIdx) && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ));
+#if DEBUG_STRING
+  const Int debugPredModeMask = DebugStringGetPredModeMask(pcCU->getPredictionMode(uiAbsPartIdx));
+#endif
+
   Bool bCheckFull;
+
   if ( SplitFlag && uiDepth == pcCU->getDepth(uiAbsPartIdx) && ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) ) )
   {
-     bCheckFull = false;
+    bCheckFull = false;
   }
   else
   {
-     bCheckFull =  ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+    bCheckFull =  ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
   }
 
   const Bool bCheckSplit  = ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
-  
+
   assert( bCheckFull || bCheckSplit );
-  
-  Bool  bCodeChroma   = true;
-  UInt  uiTrModeC     = uiTrMode;
-  UInt  uiLog2TrSizeC = uiLog2TrSize-1;
-  if( uiLog2TrSize == 2 )
-  {
-    uiLog2TrSizeC++;
-    uiTrModeC    --;
-    UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
-    bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
-  }
-  
-  const UInt uiSetCbf = 1 << uiTrMode;
+
   // code full block
-  Double dSingleCost = MAX_DOUBLE;
-  UInt uiSingleBits = 0;
-#if H_3D_VSO
-  Dist uiSingleDist = 0;
+  Double     dSingleCost = MAX_DOUBLE;
+  UInt       uiSingleBits                                                                                                        = 0;
+#if NH_3D_VSO
+  Dist       uiSingleDistComp            [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+  Dist       uiSingleDist                                                                                                       = 0;
 #else
-  UInt uiSingleDist = 0;
-#endif
-  UInt uiAbsSumY = 0, uiAbsSumU = 0, uiAbsSumV = 0;
-  UInt uiBestTransformMode[3] = {0};
-
-    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-  
+  Distortion uiSingleDistComp            [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+  Distortion uiSingleDist                                                                                                        = 0;
+#endif
+  TCoeff     uiAbsSum                    [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+  UInt       uiBestTransformMode         [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+  //  Stores the best explicit RDPCM mode for a TU encoded without split
+  UInt       bestExplicitRdpcmModeUnSplit[MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{3,3}, {3,3}, {3,3}};
+  Char       bestCrossCPredictionAlpha   [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+
   if( bCheckFull )
   {
-    const UInt uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+    Double minCost[MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/];
+    Bool checkTransformSkip[MAX_NUM_COMPONENT];
+    pcCU->setTrIdxSubParts( uiTrMode, uiAbsPartIdx, uiDepth );
+
+    m_pcEntropyCoder->resetBits();
+
+    memset( m_pTempPel, 0, sizeof( Pel ) * rTu.getRect(COMPONENT_Y).width * rTu.getRect(COMPONENT_Y).height ); // not necessary needed for inside of recursion (only at the beginning)
+
     const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-    TCoeff *pcCoeffCurrY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
-    TCoeff *pcCoeffCurrU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-    TCoeff *pcCoeffCurrV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-#if ADAPTIVE_QP_SELECTION    
-    Int *pcArlCoeffCurrY = m_ppcQTTempArlCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
-    Int *pcArlCoeffCurrU = m_ppcQTTempArlCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-    Int *pcArlCoeffCurrV = m_ppcQTTempArlCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);   
-#endif
-    
-    Int trWidth = 0, trHeight = 0, trWidthC = 0, trHeightC = 0;
-    UInt absTUPartIdxC = uiAbsPartIdx;
-
-    trWidth  = trHeight  = 1 << uiLog2TrSize;
-    trWidthC = trHeightC = 1 <<uiLog2TrSizeC;
-    pcCU->setTrIdxSubParts( uiDepth - pcCU->getDepth( 0 ), uiAbsPartIdx, uiDepth );
-    Double minCostY = MAX_DOUBLE;
-    Double minCostU = MAX_DOUBLE;
-    Double minCostV = MAX_DOUBLE;
-    Bool checkTransformSkipY  = pcCU->getSlice()->getPPS()->getUseTransformSkip() && trWidth == 4 && trHeight == 4;
-    Bool checkTransformSkipUV = pcCU->getSlice()->getPPS()->getUseTransformSkip() && trWidthC == 4 && trHeightC == 4;
-
-    checkTransformSkipY         &= (!pcCU->isLosslessCoded(0));
-    checkTransformSkipUV        &= (!pcCU->isLosslessCoded(0));
-
-    pcCU->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth ); 
-    if( bCodeChroma )
-    {
-      pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
-      pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
-    }
-
-    if (m_pcEncCfg->getUseRDOQ())
-    {
-      m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidth, trHeight, TEXT_LUMA );        
-    }
-
-    m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
-
-#if RDOQ_CHROMA_LAMBDA 
-    m_pcTrQuant->selectLambda(TEXT_LUMA);  
-#endif
-    m_pcTrQuant->transformNxN( pcCU, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride (), pcCoeffCurrY, 
+    TCoeff *pcCoeffCurr[MAX_NUM_COMPONENT];
 #if ADAPTIVE_QP_SELECTION
-                                 pcArlCoeffCurrY, 
-#endif      
-                                 trWidth,   trHeight,    uiAbsSumY, TEXT_LUMA,     uiAbsPartIdx );
-    
-    pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
-    
-    if( bCodeChroma )
-    {
-      if (m_pcEncCfg->getUseRDOQ())
-      {
-        m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidthC, trHeightC, TEXT_CHROMA );          
-      }
-
-      Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
-      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-#if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
-#endif
-
-      m_pcTrQuant->transformNxN( pcCU, pcResi->getCbAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrU, 
+    TCoeff *pcArlCoeffCurr[MAX_NUM_COMPONENT];
+#endif
+
+    for(UInt i=0; i<numValidComp; i++)
+    {
+      minCost[i][0] = MAX_DOUBLE;
+      minCost[i][1] = MAX_DOUBLE;
+    }
+
+    Pel crossCPredictedResidualBuffer[ MAX_TU_SIZE * MAX_TU_SIZE ];
+
+    for(UInt i=0; i<numValidComp; i++)
+    {
+      checkTransformSkip[i]=false;
+      const ComponentID compID=ComponentID(i);
+      const Int channelBitDepth=pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID));
+      pcCoeffCurr[compID]    = m_ppcQTTempCoeff[compID][uiQTTempAccessLayer] + rTu.getCoefficientOffset(compID);
 #if ADAPTIVE_QP_SELECTION
-                                 pcArlCoeffCurrU, 
-#endif        
-                                 trWidthC, trHeightC, uiAbsSumU, TEXT_CHROMA_U, uiAbsPartIdx );
-
-      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
-      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-      
+      pcArlCoeffCurr[compID] = m_ppcQTTempArlCoeff[compID ][uiQTTempAccessLayer] +  rTu.getCoefficientOffset(compID);
+#endif
+
+      if(rTu.ProcessComponentSection(compID))
+      {
+        const QpParam cQP(*pcCU, compID);
+
+        checkTransformSkip[compID] = pcCU->getSlice()->getPPS()->getUseTransformSkip() &&
+                                     TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(compID), pcCU->getSlice()->getPPS()->getPpsRangeExtension().getLog2MaxTransformSkipBlockSize()) &&
+                                     (!pcCU->isLosslessCoded(0));
+
+        const Bool splitIntoSubTUs = rTu.getRect(compID).width != rTu.getRect(compID).height;
+
+        TComTURecurse TUIterator(rTu, false, (splitIntoSubTUs ? TComTU::VERTICAL_SPLIT : TComTU::DONT_SPLIT), true, compID);
+
+        const UInt partIdxesPerSubTU = TUIterator.GetAbsPartIdxNumParts(compID);
+
+        do
+        {
+          const UInt           subTUIndex             = TUIterator.GetSectionNumber();
+          const UInt           subTUAbsPartIdx        = TUIterator.GetAbsPartIdxTU(compID);
+          const TComRectangle &tuCompRect             = TUIterator.getRect(compID);
+          const UInt           subTUBufferOffset      = tuCompRect.width * tuCompRect.height * subTUIndex;
+
+                TCoeff        *currentCoefficients    = pcCoeffCurr[compID] + subTUBufferOffset;
+#if ADAPTIVE_QP_SELECTION
+                TCoeff        *currentARLCoefficients = pcArlCoeffCurr[compID] + subTUBufferOffset;
+#endif
+          const Bool isCrossCPredictionAvailable      =    isChroma(compID)
+                                                         && pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag()
+                                                         && (pcCU->getCbf(subTUAbsPartIdx, COMPONENT_Y, uiTrMode) != 0);
+
+          Char preCalcAlpha = 0;
+          const Pel *pLumaResi = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( COMPONENT_Y, rTu.getRect( COMPONENT_Y ).x0, rTu.getRect( COMPONENT_Y ).y0 );
+
+          if (isCrossCPredictionAvailable)
+          {
+            const Bool bUseReconstructedResidualForEstimate = m_pcEncCfg->getUseReconBasedCrossCPredictionEstimate();
+            const Pel  *const lumaResidualForEstimate       = bUseReconstructedResidualForEstimate ? pLumaResi                                                     : pcResi->getAddrPix(COMPONENT_Y, tuCompRect.x0, tuCompRect.y0);
+            const UInt        lumaResidualStrideForEstimate = bUseReconstructedResidualForEstimate ? m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y) : pcResi->getStride(COMPONENT_Y);
+
+            preCalcAlpha = xCalcCrossComponentPredictionAlpha(TUIterator,
+                                                              compID,
+                                                              lumaResidualForEstimate,
+                                                              pcResi->getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                              tuCompRect.width,
+                                                              tuCompRect.height,
+                                                              lumaResidualStrideForEstimate,
+                                                              pcResi->getStride(compID));
+          }
+
+          const Int transformSkipModesToTest    = checkTransformSkip[compID] ? 2 : 1;
+          const Int crossCPredictionModesToTest = (preCalcAlpha != 0)        ? 2 : 1; // preCalcAlpha cannot be anything other than 0 if isCrossCPredictionAvailable is false
+
+          const Bool isOneMode                  = (crossCPredictionModesToTest == 1) && (transformSkipModesToTest == 1);
+
+          for (Int transformSkipModeId = 0; transformSkipModeId < transformSkipModesToTest; transformSkipModeId++)
+          {
+            pcCU->setTransformSkipPartRange(transformSkipModeId, compID, subTUAbsPartIdx, partIdxesPerSubTU);
+
+            for (Int crossCPredictionModeId = 0; crossCPredictionModeId < crossCPredictionModesToTest; crossCPredictionModeId++)
+            {
+              const Bool isFirstMode          = (transformSkipModeId == 0) && (crossCPredictionModeId == 0);
+              const Bool bUseCrossCPrediction = crossCPredictionModeId != 0;
+
+              m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+              m_pcEntropyCoder->resetBits();
+
+              pcCU->setTransformSkipPartRange(transformSkipModeId, compID, subTUAbsPartIdx, partIdxesPerSubTU);
+              pcCU->setCrossComponentPredictionAlphaPartRange((bUseCrossCPrediction ? preCalcAlpha : 0), compID, subTUAbsPartIdx, partIdxesPerSubTU );
+
+              if ((compID != COMPONENT_Cr) && ((transformSkipModeId == 1) ? m_pcEncCfg->getUseRDOQTS() : m_pcEncCfg->getUseRDOQ()))
+              {
+                m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, tuCompRect.width, tuCompRect.height, toChannelType(compID));
+              }
+
 #if RDOQ_CHROMA_LAMBDA
-      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
-#endif
-
-      m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
+              m_pcTrQuant->selectLambda(compID);
+#endif
+
+              Pel *pcResiCurrComp = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0);
+              UInt resiStride     = m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID);
+
+              TCoeff bestCoeffComp   [MAX_TU_SIZE*MAX_TU_SIZE];
+              Pel    bestResiComp    [MAX_TU_SIZE*MAX_TU_SIZE];
+
 #if ADAPTIVE_QP_SELECTION
-                                 pcArlCoeffCurrV, 
-#endif        
-                                 trWidthC, trHeightC, uiAbsSumV, TEXT_CHROMA_V, uiAbsPartIdx );
-
-      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-    }
-    
-    m_pcEntropyCoder->resetBits();
-    
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-    
-    m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx,  trWidth,  trHeight,    uiDepth, TEXT_LUMA );
-    const UInt uiSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
-    
-    UInt uiSingleBitsU = 0;
-    UInt uiSingleBitsV = 0;
-    if( bCodeChroma )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-      m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
-      uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();
-      
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-      m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
-      uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
-    }
-    
-    const UInt uiNumSamplesLuma = 1 << (uiLog2TrSize<<1);
-    const UInt uiNumSamplesChro = 1 << (uiLog2TrSizeC<<1);
-    
-    ::memset( m_pTempPel, 0, sizeof( Pel ) * uiNumSamplesLuma ); // not necessary needed for inside of recursion (only at the beginning)
-    
-#if H_3D_VSO // M27
-    Dist uiDistY; 
-    if ( m_pcRdCost->getUseVSO() )
-    {
-      if( m_pcRdCost->getUseEstimatedVSD() )
-      {
-        uiDistY = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPartIdx, m_pTempPel, 1<< uiLog2TrSize, pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(), 1<< uiLog2TrSize, 1<< uiLog2TrSize, false );
-      }
-      else
-      {      
-        uiDistY = m_pcRdCost->getDistPartVSO  ( pcCU, uiAbsPartIdx, pcPred->getLumaAddr( uiAbsPartIdx ), pcPred->getStride(), pcOrg->getLumaAddr( uiAbsPartIdx), pcOrg->getStride(), 1<< uiLog2TrSize, 1<< uiLog2TrSize, false ); // initialized with zero residual distortion
-      }
-    }
-    else
-    {
-      uiDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pTempPel, trWidth, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight ); // initialized with zero residual destortion
-    }
+              TCoeff bestArlCoeffComp[MAX_TU_SIZE*MAX_TU_SIZE];
+#endif
+              TCoeff     currAbsSum   = 0;
+              UInt       currCompBits = 0;
+#if NH_3D_VSO
+              Dist       currCompDist = 0;
 #else
-    UInt uiDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pTempPel, trWidth, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight ); // initialized with zero residual destortion
-#endif
-
-    if ( puiZeroDist )
-    {
-      *puiZeroDist += uiDistY;
-    }
-    if( uiAbsSumY )
-    {
-      Pel *pcResiCurrY = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getLumaAddr( absTUPartIdx );
-
-      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
-
-      Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
-      assert(scalingListType < SCALING_LIST_NUM);
-      m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
-
-#if H_3D_VSO // M28     
-      Dist uiNonzeroDistY;
-      if ( m_pcRdCost->getUseVSO() )
-      {
-        if ( m_pcRdCost->getUseEstimatedVSD() )
-        {          
-          uiNonzeroDistY = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPartIdx, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( uiAbsPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(), pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(),  1<< uiLog2TrSize,    1<< uiLog2TrSize, false );
-        }
-        else
-        {        
-          m_cYuvRecTemp.addClipPartLuma( &m_pcQTTempTComYuv[uiQTTempAccessLayer], pcPred, uiAbsPartIdx, 1<< uiLog2TrSize  );
-          uiNonzeroDistY = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPartIdx, m_cYuvRecTemp.getLumaAddr(uiAbsPartIdx), m_cYuvRecTemp.getStride(),
-            pcOrg->getLumaAddr( uiAbsPartIdx ), pcOrg->getStride(), 1<< uiLog2TrSize,   1<< uiLog2TrSize, false );
-        }
-      }
-      else
-      {
-        uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),      pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
-      }
-#else      
-      const UInt uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
-      pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
-#endif
-      if (pcCU->isLosslessCoded(0)) 
-      {
-        uiDistY = uiNonzeroDistY;
-      }
-      else
-      {
-#if H_3D_VSO // M29
-        Double singleCostY;
-        if ( m_pcRdCost->getUseLambdaScaleVSO())
-          singleCostY = m_pcRdCost->calcRdCostVSO( uiSingleBitsY, uiNonzeroDistY );
-        else
-          singleCostY = m_pcRdCost->calcRdCost( uiSingleBitsY, uiNonzeroDistY );
+              Distortion currCompDist = 0;
+#endif
+              Double     currCompCost = 0;
+              UInt       nonCoeffBits = 0;
+#if NH_3D_VSO
+              Dist       nonCoeffDist = 0;
 #else
-        const Double singleCostY = m_pcRdCost->calcRdCost( uiSingleBitsY, uiNonzeroDistY );
-#endif
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-
-        m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_LUMA,     uiTrMode );
-        const UInt uiNullBitsY   = m_pcEntropyCoder->getNumberOfWrittenBits();
-#if H_3D_VSO // M29
-        Double nullCostY;
-        if ( m_pcRdCost->getUseLambdaScaleVSO())
-          nullCostY   = m_pcRdCost->calcRdCostVSO( uiNullBitsY, uiDistY );
-        else
-          nullCostY   = m_pcRdCost->calcRdCost   ( uiNullBitsY, uiDistY );
-#else
-        const Double nullCostY   = m_pcRdCost->calcRdCost( uiNullBitsY, uiDistY );
-#endif
-        if( nullCostY < singleCostY )  
-        {    
-          uiAbsSumY = 0;
-          ::memset( pcCoeffCurrY, 0, sizeof( TCoeff ) * uiNumSamplesLuma );
-          if( checkTransformSkipY )
-          {
-            minCostY = nullCostY;
-          }
-        }
-        else
-        {
-          uiDistY = uiNonzeroDistY;
-          if( checkTransformSkipY )
-          {
-            minCostY = singleCostY;
-          }
-        }
-      }
-    }
-    else if( checkTransformSkipY )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-      m_pcEntropyCoder->resetBits();
-      m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_LUMA, uiTrMode );
-      const UInt uiNullBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
-#if H_3D_VSO // M NEW01
-      if ( m_pcRdCost->getUseRenModel() )
-        minCostY = m_pcRdCost->calcRdCostVSO( uiNullBitsY, uiDistY );
-      else
-#endif
-      minCostY = m_pcRdCost->calcRdCost( uiNullBitsY, uiDistY );
-    }
-
-    if( !uiAbsSumY )
-    {
-      Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx );
-      const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride();
-      for( UInt uiY = 0; uiY < trHeight; ++uiY )
-      {
-        ::memset( pcPtr, 0, sizeof( Pel ) * trWidth );
-        pcPtr += uiStride;
-      } 
-    }
-    
-    UInt uiDistU = 0;
-    UInt uiDistV = 0;
-    if( bCodeChroma )
-    {
-      uiDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCbAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-                                        , TEXT_CHROMA_U
-                                        ); // initialized with zero residual destortion
-      if ( puiZeroDist )
-      {
-        *puiZeroDist += uiDistU;
-      }
-      if( uiAbsSumU )
-      {
-        Pel *pcResiCurrU = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
-
-        Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
-        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
-        assert(scalingListType < SCALING_LIST_NUM);
-        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType  );
-        
-        const UInt uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
-                                                            pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-                                                            , TEXT_CHROMA_U
-                                                            );
-
-        if(pcCU->isLosslessCoded(0))  
-        {
-          uiDistU = uiNonzeroDistU;
-        }
-        else
-        {
-          const Double dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
-          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-          m_pcEntropyCoder->resetBits();
-          m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U,     uiTrMode );
-          const UInt uiNullBitsU    = m_pcEntropyCoder->getNumberOfWrittenBits();
-          const Double dNullCostU   = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
-          if( dNullCostU < dSingleCostU )
-          {
-            uiAbsSumU = 0;
-            ::memset( pcCoeffCurrU, 0, sizeof( TCoeff ) * uiNumSamplesChro );
-            if( checkTransformSkipUV )
-            {
-              minCostU = dNullCostU;
+              Distortion nonCoeffDist = 0;
+#endif
+              Double     nonCoeffCost = 0;
+
+              if(!isOneMode && !isFirstMode)
+              {
+                memcpy(bestCoeffComp,    currentCoefficients,    (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+#if ADAPTIVE_QP_SELECTION
+                memcpy(bestArlCoeffComp, currentARLCoefficients, (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+#endif
+                for(Int y = 0; y < tuCompRect.height; y++)
+                {
+                  memcpy(&bestResiComp[y * tuCompRect.width], (pcResiCurrComp + (y * resiStride)), (sizeof(Pel) * tuCompRect.width));
+                }
+              }
+
+              if (bUseCrossCPrediction)
+              {
+                TComTrQuant::crossComponentPrediction(TUIterator,
+                                                      compID,
+                                                      pLumaResi,
+                                                      pcResi->getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                      crossCPredictedResidualBuffer,
+                                                      tuCompRect.width,
+                                                      tuCompRect.height,
+                                                      m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y),
+                                                      pcResi->getStride(compID),
+                                                      tuCompRect.width,
+                                                      false);
+
+                m_pcTrQuant->transformNxN(TUIterator, compID, crossCPredictedResidualBuffer, tuCompRect.width, currentCoefficients,
+#if ADAPTIVE_QP_SELECTION
+                                          currentARLCoefficients,
+#endif
+                                          currAbsSum, cQP);
+              }
+              else
+              {
+                m_pcTrQuant->transformNxN(TUIterator, compID, pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ), pcResi->getStride(compID), currentCoefficients,
+#if ADAPTIVE_QP_SELECTION
+                                          currentARLCoefficients,
+#endif
+                                          currAbsSum, cQP);
+              }
+
+              if(isFirstMode || (currAbsSum == 0))
+              {
+                if (bUseCrossCPrediction)
+                {
+                  TComTrQuant::crossComponentPrediction(TUIterator,
+                                                        compID,
+                                                        pLumaResi,
+                                                        m_pTempPel,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                        tuCompRect.width,
+                                                        tuCompRect.height,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y),
+                                                        tuCompRect.width,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID),
+                                                        true);
+#if NH_3D_VSO      
+                  // No VSO needed here.
+                  assert( !m_pcRdCost->getUseVSO() );
+#endif
+                  nonCoeffDist = m_pcRdCost->getDistPart( channelBitDepth, m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                          m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride( compID ), pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                          pcResi->getStride(compID), tuCompRect.width, tuCompRect.height, compID); // initialized with zero residual destortion
+                }
+                else
+                {
+#if NH_3D_VSO // M27                  
+                  if ( m_pcRdCost->getUseVSO() )
+                  {
+                    if( m_pcRdCost->getUseEstimatedVSD() )
+                    {
+                      nonCoeffDist = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPartIdx, channelBitDepth, m_pTempPel, tuCompRect.width, pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                          pcResi->getStride( compID ), tuCompRect.width, tuCompRect.height, false );
+                    }
+                    else
+                    {      
+                      nonCoeffDist = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPartIdx, channelBitDepth, pcPred->getAddr( compID, uiAbsPartIdx ), 
+                                                          pcPred->getStride( compID ), pcOrg->getAddr( compID, uiAbsPartIdx), pcOrg->getStride( compID ), 
+                                                          tuCompRect.width, tuCompRect.height, false ); // initialized with zero residual distortion
+                    }
+                  }
+                  else
+#endif
+                    nonCoeffDist = m_pcRdCost->getDistPart( channelBitDepth, m_pTempPel, tuCompRect.width, pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                          pcResi->getStride(compID), tuCompRect.width, tuCompRect.height, compID); // initialized with zero residual destortion
+                    
+                }
+
+                m_pcEntropyCoder->encodeQtCbfZero( TUIterator, toChannelType(compID) );
+
+                if ( isCrossCPredictionAvailable )
+                {
+                  m_pcEntropyCoder->encodeCrossComponentPrediction( TUIterator, compID );
+                }
+
+                nonCoeffBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+#if NH_3D_VSO // M29                
+                if ( m_pcRdCost->getUseLambdaScaleVSO())
+                {
+                   nonCoeffCost = m_pcRdCost->calcRdCostVSO( nonCoeffBits, nonCoeffDist );        
+                }          
+                else          
+#endif
+                  nonCoeffCost = m_pcRdCost->calcRdCost( nonCoeffBits, nonCoeffDist );
+              }
+
+              if((puiZeroDist != NULL) && isFirstMode)
+              {
+                *puiZeroDist += nonCoeffDist; // initialized with zero residual destortion
+              }
+
+              DEBUG_STRING_NEW(sSingleStringTest)
+
+              if( currAbsSum > 0 ) //if non-zero coefficients are present, a residual needs to be derived for further prediction
+              {
+                if (isFirstMode)
+                {
+                  m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+                  m_pcEntropyCoder->resetBits();
+                }
+
+                m_pcEntropyCoder->encodeQtCbf( TUIterator, compID, true );
+
+                if (isCrossCPredictionAvailable)
+                {
+                  m_pcEntropyCoder->encodeCrossComponentPrediction( TUIterator, compID );
+                }
+
+                m_pcEntropyCoder->encodeCoeffNxN( TUIterator, currentCoefficients, compID );
+                currCompBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+                pcResiCurrComp = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 );
+
+                m_pcTrQuant->invTransformNxN( TUIterator, compID, pcResiCurrComp, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID), currentCoefficients, cQP DEBUG_STRING_PASS_INTO_OPTIONAL(&sSingleStringTest, (DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask)) );
+
+                if (bUseCrossCPrediction)
+                {
+#if NH_3D_VSO     
+                  assert( !m_pcRdCost->getUseVSO() );
+#endif
+                  TComTrQuant::crossComponentPrediction(TUIterator,
+                                                        compID,
+                                                        pLumaResi,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                        tuCompRect.width,
+                                                        tuCompRect.height,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y),
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID     ),
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID     ),
+                                                        true);
+                }
+
+#if NH_3D_VSO // M28     
+                if ( m_pcRdCost->getUseVSO() )
+                {
+                  if ( m_pcRdCost->getUseEstimatedVSD() )
+                  {          
+                    currCompDist  = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPartIdx, channelBitDepth, m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                      m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID),
+                      pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                      pcResi->getStride(compID),
+                      tuCompRect.width, tuCompRect.height, false);
+                  }
+                  else
+                  {        
+                    m_cYuvRecTemp.addClipPartLuma( channelBitDepth, &m_pcQTTempTComYuv[uiQTTempAccessLayer], pcPred, uiAbsPartIdx, tuCompRect.width );
+                    currCompDist = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPartIdx, channelBitDepth, 
+                                                      m_cYuvRecTemp.getAddr(compID, uiAbsPartIdx), 
+                                                      m_cYuvRecTemp.getStride( compID), 
+                                                      pcOrg->getAddr  ( compID, uiAbsPartIdx ), 
+                                                      pcOrg->getStride( compID ), 
+                                                      tuCompRect.width, tuCompRect.height, false );
+                  }
+                }
+                else
+#endif
+                currCompDist = m_pcRdCost->getDistPart( channelBitDepth, m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID),
+                                                        pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                        pcResi->getStride(compID),
+                                                        tuCompRect.width, tuCompRect.height, compID);
+
+#if NH_3D_VSO // M NEW01
+               if ( m_pcRdCost->getUseRenModel() )
+               {
+                 currCompCost = m_pcRdCost->calcRdCostVSO(currCompBits, currCompDist);
+               }
+               else
+#endif
+                currCompCost = m_pcRdCost->calcRdCost(currCompBits, currCompDist);
+                  
+                if (pcCU->isLosslessCoded(0))
+                {
+                  nonCoeffCost = MAX_DOUBLE;
+                }
+              }
+              else if ((transformSkipModeId == 1) && !bUseCrossCPrediction)
+              {
+                currCompCost = MAX_DOUBLE;
+              }
+              else
+              {
+                currCompBits = nonCoeffBits;
+                currCompDist = nonCoeffDist;
+                currCompCost = nonCoeffCost;
+              }
+
+              // evaluate
+              if ((currCompCost < minCost[compID][subTUIndex]) || ((transformSkipModeId == 1) && (currCompCost == minCost[compID][subTUIndex])))
+              {
+                bestExplicitRdpcmModeUnSplit[compID][subTUIndex] = pcCU->getExplicitRdpcmMode(compID, subTUAbsPartIdx);
+
+                if(isFirstMode) //check for forced null
+                {
+                  if((nonCoeffCost < currCompCost) || (currAbsSum == 0))
+                  {
+                    memset(currentCoefficients, 0, (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+
+                    currAbsSum   = 0;
+                    currCompBits = nonCoeffBits;
+                    currCompDist = nonCoeffDist;
+                    currCompCost = nonCoeffCost;
+                  }
+                }
+
+#if DEBUG_STRING
+                if (currAbsSum > 0)
+                {
+                  DEBUG_STRING_SWAP(sSingleStringComp[compID], sSingleStringTest)
+                }
+                else
+                {
+                  sSingleStringComp[compID].clear();
+                }
+#endif
+
+                uiAbsSum                 [compID][subTUIndex] = currAbsSum;
+                uiSingleDistComp         [compID][subTUIndex] = currCompDist;
+                minCost                  [compID][subTUIndex] = currCompCost;
+                uiBestTransformMode      [compID][subTUIndex] = transformSkipModeId;
+                bestCrossCPredictionAlpha[compID][subTUIndex] = (crossCPredictionModeId == 1) ? pcCU->getCrossComponentPredictionAlpha(subTUAbsPartIdx, compID) : 0;
+
+                if (uiAbsSum[compID][subTUIndex] == 0)
+                {
+                  if (bUseCrossCPrediction)
+                  {
+                    TComTrQuant::crossComponentPrediction(TUIterator,
+                                                          compID,
+                                                          pLumaResi,
+                                                          m_pTempPel,
+                                                          m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                          tuCompRect.width,
+                                                          tuCompRect.height,
+                                                          m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y),
+                                                          tuCompRect.width,
+                                                          m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID),
+                                                          true);
+                  }
+                  else
+                  {
+                    pcResiCurrComp = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0);
+                    const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID);
+                    for(UInt uiY = 0; uiY < tuCompRect.height; uiY++)
+                    {
+                      memset(pcResiCurrComp, 0, (sizeof(Pel) * tuCompRect.width));
+                      pcResiCurrComp += uiStride;
+                    }
+                  }
+                }
+              }
+              else
+              {
+                // reset
+                memcpy(currentCoefficients,    bestCoeffComp,    (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+#if ADAPTIVE_QP_SELECTION
+                memcpy(currentARLCoefficients, bestArlCoeffComp, (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+#endif
+                for (Int y = 0; y < tuCompRect.height; y++)
+                {
+                  memcpy((pcResiCurrComp + (y * resiStride)), &bestResiComp[y * tuCompRect.width], (sizeof(Pel) * tuCompRect.width));
+                }
+              }
             }
           }
-          else
-          {
-            uiDistU = uiNonzeroDistU;
-            if( checkTransformSkipUV )
-            {
-              minCostU = dSingleCostU;
-            }
-          }
-        }
-      }
-      else if( checkTransformSkipUV )
-      {
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-        m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrMode );
-        const UInt uiNullBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();
-        minCostU = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
-      }
-      if( !uiAbsSumU )
-      {
-        Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
-          const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
-        for( UInt uiY = 0; uiY < trHeightC; ++uiY )
-        {
-          ::memset( pcPtr, 0, sizeof(Pel) * trWidthC );
-          pcPtr += uiStride;
-        }
-      }
-      
-      uiDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCrAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-                                        , TEXT_CHROMA_V
-                                        ); // initialized with zero residual destortion
-      if ( puiZeroDist )
-      {
-        *puiZeroDist += uiDistV;
-      }
-      if( uiAbsSumV )
-      {
-        Pel *pcResiCurrV = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
-        Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
-        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
-        assert(scalingListType < SCALING_LIST_NUM);
-        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType );
-        
-        const UInt uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
-                                                            pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-                                                            , TEXT_CHROMA_V
-                                                            );
-        if (pcCU->isLosslessCoded(0)) 
-        {
-          uiDistV = uiNonzeroDistV;
-        }
-        else
-        {
-          const Double dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
-          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-          m_pcEntropyCoder->resetBits();
-          m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V,     uiTrMode );
-          const UInt uiNullBitsV    = m_pcEntropyCoder->getNumberOfWrittenBits();
-          const Double dNullCostV   = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
-          if( dNullCostV < dSingleCostV )
-          {
-            uiAbsSumV = 0;
-            ::memset( pcCoeffCurrV, 0, sizeof( TCoeff ) * uiNumSamplesChro );
-            if( checkTransformSkipUV )
-            {
-              minCostV = dNullCostV;
-            }
-          }
-          else
-          {
-            uiDistV = uiNonzeroDistV;
-            if( checkTransformSkipUV )
-            {
-              minCostV = dSingleCostV;
-            }
-          }
-        }
-      }
-      else if( checkTransformSkipUV )
-      {
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-        m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrMode );
-        const UInt uiNullBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
-        minCostV = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
-      }
-      if( !uiAbsSumV )
-      {
-        Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
-        const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
-        for( UInt uiY = 0; uiY < trHeightC; ++uiY )
-        {   
-          ::memset( pcPtr, 0, sizeof(Pel) * trWidthC );
-          pcPtr += uiStride;
-        }
-      }
-    }
-    pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
-    if( bCodeChroma )
-    {
-      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-    }
-
-    if( checkTransformSkipY )
-    {
-#if H_3D_VSO
-      Dist uiNonzeroDistY; 
-      UInt uiAbsSumTransformSkipY;
-#else
-      UInt uiNonzeroDistY, uiAbsSumTransformSkipY;
-#endif
-      Double dSingleCostY;
-
-      Pel *pcResiCurrY = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getLumaAddr( absTUPartIdx );
-      UInt resiYStride = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getStride();
-
-      TCoeff bestCoeffY[32*32];
-      memcpy( bestCoeffY, pcCoeffCurrY, sizeof(TCoeff) * uiNumSamplesLuma );
-      
-#if ADAPTIVE_QP_SELECTION
-      TCoeff bestArlCoeffY[32*32];
-      memcpy( bestArlCoeffY, pcArlCoeffCurrY, sizeof(TCoeff) * uiNumSamplesLuma );
-#endif
-
-      Pel bestResiY[32*32];
-      for ( Int i = 0; i < trHeight; ++i )
-      {
-        memcpy( &bestResiY[i*trWidth], pcResiCurrY+i*resiYStride, sizeof(Pel) * trWidth );
-      }
-
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-
-      pcCU->setTransformSkipSubParts ( 1, TEXT_LUMA, uiAbsPartIdx, uiDepth );
-
-      if (m_pcEncCfg->getUseRDOQTS())
-      {
-        m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, trWidth, trHeight, TEXT_LUMA );        
-      }
-
-      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
-
-#if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_LUMA);
-#endif
-      m_pcTrQuant->transformNxN( pcCU, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride (), pcCoeffCurrY, 
-#if ADAPTIVE_QP_SELECTION
-        pcArlCoeffCurrY, 
-#endif      
-        trWidth,   trHeight,    uiAbsSumTransformSkipY, TEXT_LUMA, uiAbsPartIdx, true );
-      pcCU->setCbfSubParts( uiAbsSumTransformSkipY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
-
-      if( uiAbsSumTransformSkipY != 0 )
-      {
-        m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrMode );
-        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
-        const UInt uiTsSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
-
-        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
-
-        Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
-        assert(scalingListType < SCALING_LIST_NUM);
-
-        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType, true );
-
-#if H_3D_VSO // M NEW       
-        if ( m_pcRdCost->getUseVSO() )
-        {
-          if ( m_pcRdCost->getUseEstimatedVSD() )
-          {          
-            uiNonzeroDistY = m_pcRdCost->getDistPartVSD( pcCU,  uiAbsPartIdx, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( uiAbsPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(), pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(),  1<< uiLog2TrSize,    1<< uiLog2TrSize, false );
-          }
-          else
-          {        
-            m_cYuvRecTemp.addClipPartLuma( &m_pcQTTempTComYuv[uiQTTempAccessLayer], pcPred, uiAbsPartIdx, 1<< uiLog2TrSize  );
-            uiNonzeroDistY = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPartIdx, m_cYuvRecTemp.getLumaAddr(uiAbsPartIdx), m_cYuvRecTemp.getStride(),
-              pcOrg->getLumaAddr( uiAbsPartIdx ), pcOrg->getStride(), 1<< uiLog2TrSize,   1<< uiLog2TrSize, false );
-          }
-        }
-        else
-#endif
-          uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
-          pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight );
-
-#if H_3D_VSO
-        if ( m_pcRdCost->getUseRenModel() )
-          dSingleCostY = m_pcRdCost->calcRdCostVSO( uiTsSingleBitsY, uiNonzeroDistY );
-        else
-#endif
-        dSingleCostY = m_pcRdCost->calcRdCost( uiTsSingleBitsY, uiNonzeroDistY );
-      }
-
-      if( !uiAbsSumTransformSkipY || minCostY < dSingleCostY )
-      {
-        pcCU->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
-        memcpy( pcCoeffCurrY, bestCoeffY, sizeof(TCoeff) * uiNumSamplesLuma );
-#if ADAPTIVE_QP_SELECTION
-        memcpy( pcArlCoeffCurrY, bestArlCoeffY, sizeof(TCoeff) * uiNumSamplesLuma );
-#endif
-        for( Int i = 0; i < trHeight; ++i )
-        {
-          memcpy( pcResiCurrY+i*resiYStride, &bestResiY[i*trWidth], sizeof(Pel) * trWidth );
-        }
-      }
-      else
-      {
-        uiDistY = uiNonzeroDistY;
-        uiAbsSumY = uiAbsSumTransformSkipY;
-        uiBestTransformMode[0] = 1;
-      }
-
-      pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
-    }
-
-    if( bCodeChroma && checkTransformSkipUV  )
-    {
-      UInt uiNonzeroDistU, uiNonzeroDistV, uiAbsSumTransformSkipU, uiAbsSumTransformSkipV;
-      Double dSingleCostU, dSingleCostV;
-
-      Pel *pcResiCurrU = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
-      Pel *pcResiCurrV = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
-      UInt resiCStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
-
-      TCoeff bestCoeffU[32*32], bestCoeffV[32*32];
-      memcpy( bestCoeffU, pcCoeffCurrU, sizeof(TCoeff) * uiNumSamplesChro );
-      memcpy( bestCoeffV, pcCoeffCurrV, sizeof(TCoeff) * uiNumSamplesChro );
-
-#if ADAPTIVE_QP_SELECTION
-      TCoeff bestArlCoeffU[32*32], bestArlCoeffV[32*32];
-      memcpy( bestArlCoeffU, pcArlCoeffCurrU, sizeof(TCoeff) * uiNumSamplesChro );
-      memcpy( bestArlCoeffV, pcArlCoeffCurrV, sizeof(TCoeff) * uiNumSamplesChro );
-#endif
-
-      Pel bestResiU[32*32], bestResiV[32*32];
-      for (Int i = 0; i < trHeightC; ++i )
-      {
-        memcpy( &bestResiU[i*trWidthC], pcResiCurrU+i*resiCStride, sizeof(Pel) * trWidthC );
-        memcpy( &bestResiV[i*trWidthC], pcResiCurrV+i*resiCStride, sizeof(Pel) * trWidthC );
-      }
-
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-
-      pcCU->setTransformSkipSubParts ( 1, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
-      pcCU->setTransformSkipSubParts ( 1, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-
-      if (m_pcEncCfg->getUseRDOQTS())
-      {
-        m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidthC, trHeightC, TEXT_CHROMA );          
-      }
-
-      Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
-      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-#if RDOQ_CHROMA_LAMBDA 
-      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
-#endif
-
-      m_pcTrQuant->transformNxN( pcCU, pcResi->getCbAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrU, 
-#if ADAPTIVE_QP_SELECTION
-        pcArlCoeffCurrU, 
-#endif        
-        trWidthC, trHeightC, uiAbsSumTransformSkipU, TEXT_CHROMA_U, uiAbsPartIdx, true );
-      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
-      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-#if RDOQ_CHROMA_LAMBDA
-      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
-#endif
-      m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
-#if ADAPTIVE_QP_SELECTION
-        pcArlCoeffCurrV, 
-#endif        
-        trWidthC, trHeightC, uiAbsSumTransformSkipV, TEXT_CHROMA_V, uiAbsPartIdx, true );
-
-      pcCU->setCbfSubParts( uiAbsSumTransformSkipU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-      pcCU->setCbfSubParts( uiAbsSumTransformSkipV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-
-      uiSingleBitsU = 0;
-      uiSingleBitsV = 0;
-
-      if( uiAbsSumTransformSkipU )
-      {
-        m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
-        uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();    
-
-        curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
-        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
-        assert(scalingListType < SCALING_LIST_NUM);
-
-        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType, true  );
-
-        uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
-                                                 pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
-                                                 , TEXT_CHROMA_U
-                                                 );
-
-        dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
-      }
-
-      if( !uiAbsSumTransformSkipU || minCostU < dSingleCostU )
-      {
-        pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
-
-        memcpy( pcCoeffCurrU, bestCoeffU, sizeof (TCoeff) * uiNumSamplesChro );
-#if ADAPTIVE_QP_SELECTION
-        memcpy( pcArlCoeffCurrU, bestArlCoeffU, sizeof (TCoeff) * uiNumSamplesChro );
-#endif
-        for( Int i = 0; i < trHeightC; ++i )
-        {
-          memcpy( pcResiCurrU+i*resiCStride, &bestResiU[i*trWidthC], sizeof(Pel) * trWidthC );
-        }
-      }
-      else
-      {
-        uiDistU = uiNonzeroDistU;
-        uiAbsSumU = uiAbsSumTransformSkipU;
-        uiBestTransformMode[1] = 1;
-      }
-
-      if( uiAbsSumTransformSkipV )
-      {
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-        m_pcEntropyCoder->resetBits();
-        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
-        uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
-
-        curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
-        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
-
-        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
-        assert(scalingListType < SCALING_LIST_NUM);
-
-        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType, true );
-
-        uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
-                                                 pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
-                                                 , TEXT_CHROMA_V
-                                                 );
-
-        dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
-      }
-
-      if( !uiAbsSumTransformSkipV || minCostV < dSingleCostV )
-      {
-        pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
-
-        memcpy( pcCoeffCurrV, bestCoeffV, sizeof(TCoeff) * uiNumSamplesChro );
-#if ADAPTIVE_QP_SELECTION
-        memcpy( pcArlCoeffCurrV, bestArlCoeffV, sizeof(TCoeff) * uiNumSamplesChro );
-#endif
-        for( Int i = 0; i < trHeightC; ++i )
-        {
-          memcpy( pcResiCurrV+i*resiCStride, &bestResiV[i*trWidthC], sizeof(Pel) * trWidthC );
-        }
-      }
-      else
-      {
-        uiDistV = uiNonzeroDistV;
-        uiAbsSumV = uiAbsSumTransformSkipV;
-        uiBestTransformMode[2] = 1;
-      }
-
-      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-    }
-
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+
+          pcCU->setExplicitRdpcmModePartRange            (   bestExplicitRdpcmModeUnSplit[compID][subTUIndex],                            compID, subTUAbsPartIdx, partIdxesPerSubTU);
+          pcCU->setTransformSkipPartRange                (   uiBestTransformMode         [compID][subTUIndex],                            compID, subTUAbsPartIdx, partIdxesPerSubTU );
+          pcCU->setCbfPartRange                          ((((uiAbsSum                    [compID][subTUIndex] > 0) ? 1 : 0) << uiTrMode), compID, subTUAbsPartIdx, partIdxesPerSubTU );
+          pcCU->setCrossComponentPredictionAlphaPartRange(   bestCrossCPredictionAlpha   [compID][subTUIndex],                            compID, subTUAbsPartIdx, partIdxesPerSubTU );
+        } while (TUIterator.nextSection(rTu)); //end of sub-TU loop
+      } // processing section
+    } // component loop
+
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      if (rTu.ProcessComponentSection(compID) && (rTu.getRect(compID).width != rTu.getRect(compID).height))
+      {
+        offsetSubTUCBFs(rTu, compID); //the CBFs up to now have been defined for two sub-TUs - shift them down a level and replace with the parent level CBF
+      }
+    }
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
     m_pcEntropyCoder->resetBits();
 
-      if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-      {
-        m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
-      }
-
-      if( bCodeChroma )
-      {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
-      }
-
-      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-
-    m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
-
-    if( bCodeChroma )
-    {
-      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
-      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
+    if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
+    }
+
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const UInt chOrderChange = ((ch + 1) == numValidComp) ? 0 : (ch + 1);
+      const ComponentID compID=ComponentID(chOrderChange);
+      if( rTu.ProcessComponentSection(compID) )
+      {
+        m_pcEntropyCoder->encodeQtCbf( rTu, compID, true );
+      }
+    }
+
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+      if (rTu.ProcessComponentSection(compID))
+      {
+        if(isChroma(compID) && (uiAbsSum[COMPONENT_Y][0] != 0))
+        {
+          m_pcEntropyCoder->encodeCrossComponentPrediction( rTu, compID );
+        }
+
+        m_pcEntropyCoder->encodeCoeffNxN( rTu, pcCoeffCurr[compID], compID );
+        for (UInt subTUIndex = 0; subTUIndex < 2; subTUIndex++)
+        {
+          uiSingleDist += uiSingleDistComp[compID][subTUIndex];
+        }
+      }
     }
 
     uiSingleBits = m_pcEntropyCoder->getNumberOfWrittenBits();
 
-    uiSingleDist = uiDistY + uiDistU + uiDistV;
-#if H_3D_VSO // M30
-    if ( m_pcRdCost->getUseLambdaScaleVSO())    
-      dSingleCost = m_pcRdCost->calcRdCostVSO( uiSingleBits, uiSingleDist );    
+#if NH_3D_VSO
+    if ( m_pcRdCost->getUseRenModel() )
+    {
+      dSingleCost = m_pcRdCost->calcRdCostVSO( uiSingleBits, uiSingleDist );
+    }
     else
 #endif
-    dSingleCost = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDist );
-  }  
-  
+      dSingleCost = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDist );
+  } // check full
+
   // code sub-blocks
   if( bCheckSplit )
@@ -6945,191 +6673,326 @@
       m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
     }
-#if H_3D_VSO
-    Dist uiSubdivDist = 0;
+#if NH_3D_VSO
+    Dist       uiSubdivDist = 0;
 #else
-    UInt uiSubdivDist = 0;
-#endif
-    UInt uiSubdivBits = 0;
-    Double dSubdivCost = 0.0;
-    
-    const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
-    for( UInt ui = 0; ui < 4; ++ui )
-    {
-      UInt nsAddr = uiAbsPartIdx + ui * uiQPartNumSubdiv;
-#if H_3D_VSO // M31
-      xEstimateResidualQT( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcOrg, pcPred, pcResi, uiDepth + 1, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist );
+    Distortion uiSubdivDist = 0;
+#endif
+    UInt       uiSubdivBits = 0;
+    Double     dSubdivCost = 0.0;
+
+    //save the non-split CBFs in case we need to restore them later
+
+    UInt bestCBF     [MAX_NUM_COMPONENT];
+    UInt bestsubTUCBF[MAX_NUM_COMPONENT][2];
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+
+      if (rTu.ProcessComponentSection(compID))
+      {
+        bestCBF[compID] = pcCU->getCbf(uiAbsPartIdx, compID, uiTrMode);
+
+        const TComRectangle &tuCompRect = rTu.getRect(compID);
+        if (tuCompRect.width != tuCompRect.height)
+        {
+          const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
+
+          for (UInt subTU = 0; subTU < 2; subTU++)
+          {
+            bestsubTUCBF[compID][subTU] = pcCU->getCbf ((uiAbsPartIdx + (subTU * partIdxesPerSubTU)), compID, subTUDepth);
+          }
+        }
+      }
+    }
+
+    TComTURecurse tuRecurseChild(rTu, false);
+    const UInt uiQPartNumSubdiv = tuRecurseChild.GetAbsPartIdxNumParts();
+
+    DEBUG_STRING_NEW(sSplitString[MAX_NUM_COMPONENT])
+
+    do
+    {
+      DEBUG_STRING_NEW(childString)
+#if NH_3D_VSO
+      xEstimateInterResidualQT( pcResi, pcOrg, pcPred, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist,  tuRecurseChild DEBUG_STRING_PASS_INTO(childString));
 #else
-      xEstimateResidualQT( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcResi, uiDepth + 1, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist );
-#endif
-    }
-    
-    UInt uiYCbf = 0;
-    UInt uiUCbf = 0;
-    UInt uiVCbf = 0;
-    for( UInt ui = 0; ui < 4; ++ui )
-    {
-      uiYCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_LUMA,     uiTrMode + 1 );
-      uiUCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_CHROMA_U, uiTrMode + 1 );
-      uiVCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_CHROMA_V, uiTrMode + 1 );
-    }
-    for( UInt ui = 0; ui < 4 * uiQPartNumSubdiv; ++ui )
-    {
-      pcCU->getCbf( TEXT_LUMA     )[uiAbsPartIdx + ui] |= uiYCbf << uiTrMode;
-      pcCU->getCbf( TEXT_CHROMA_U )[uiAbsPartIdx + ui] |= uiUCbf << uiTrMode;
-      pcCU->getCbf( TEXT_CHROMA_V )[uiAbsPartIdx + ui] |= uiVCbf << uiTrMode;
-    }
-    
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+      xEstimateInterResidualQT( pcResi, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist,  tuRecurseChild DEBUG_STRING_PASS_INTO(childString));
+#endif
+#if DEBUG_STRING
+      // split the string by component and append to the relevant output (because decoder decodes in channel order, whereas this search searches by TU-order)
+      std::size_t lastPos=0;
+      const std::size_t endStrng=childString.find(debug_reorder_data_inter_token[MAX_NUM_COMPONENT], lastPos);
+      for(UInt ch = 0; ch < numValidComp; ch++)
+      {
+        if (lastPos!=std::string::npos && childString.find(debug_reorder_data_inter_token[ch], lastPos)==lastPos)
+        {
+          lastPos+=strlen(debug_reorder_data_inter_token[ch]); // skip leading string
+        }
+        std::size_t pos=childString.find(debug_reorder_data_inter_token[ch+1], lastPos);
+        if (pos!=std::string::npos && pos>endStrng)
+        {
+          lastPos=endStrng;
+        }
+        sSplitString[ch]+=childString.substr(lastPos, (pos==std::string::npos)? std::string::npos : (pos-lastPos) );
+        lastPos=pos;
+      }
+#endif
+    } while ( tuRecurseChild.nextSection(rTu) ) ;
+
+    UInt uiCbfAny=0;
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      UInt uiYUVCbf = 0;
+      for( UInt ui = 0; ui < 4; ++ui )
+      {
+        uiYUVCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, ComponentID(ch),  uiTrMode + 1 );
+      }
+      UChar *pBase=pcCU->getCbf( ComponentID(ch) );
+      const UInt flags=uiYUVCbf << uiTrMode;
+      for( UInt ui = 0; ui < 4 * uiQPartNumSubdiv; ++ui )
+      {
+        pBase[uiAbsPartIdx + ui] |= flags;
+      }
+      uiCbfAny|=uiYUVCbf;
+    }
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
     m_pcEntropyCoder->resetBits();
-    
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, true,  TEXT_LUMA );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_LUMA );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_U );
-      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_V );
-    
+
+    // when compID isn't a channel, code Cbfs:
+
+    xEncodeInterResidualQT( MAX_NUM_COMPONENT, rTu );
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      xEncodeInterResidualQT( ComponentID(ch), rTu );
+    }
+
     uiSubdivBits = m_pcEntropyCoder->getNumberOfWrittenBits();
-#if H_3D_VSO // M32
-    if ( m_pcRdCost->getUseLambdaScaleVSO())
+#if NH_3D_VSO
+    if( m_pcRdCost->getUseLambdaScaleVSO())
+    {
       dSubdivCost  = m_pcRdCost->calcRdCostVSO( uiSubdivBits, uiSubdivDist );
+    }
     else
 #endif
-    dSubdivCost  = m_pcRdCost->calcRdCost( uiSubdivBits, uiSubdivDist );
-    
-    if( uiYCbf || uiUCbf || uiVCbf || !bCheckFull )
-    {
-      if( dSubdivCost < dSingleCost )
-      {
-        rdCost += dSubdivCost;
-        ruiBits += uiSubdivBits;
-        ruiDist += uiSubdivDist;
-        return;
-      }
-    }
-    pcCU->setTransformSkipSubParts ( uiBestTransformMode[0], TEXT_LUMA, uiAbsPartIdx, uiDepth ); 
-    if(bCodeChroma)
-    {
-      pcCU->setTransformSkipSubParts ( uiBestTransformMode[1], TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
-      pcCU->setTransformSkipSubParts ( uiBestTransformMode[2], TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
-    }
-    assert( bCheckFull );
-
-    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
-  }
-#if H_3D_VSO // M33
-  if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
-  {
-    UInt  uiWidth     = 1<< uiLog2TrSize;
-    UInt  uiHeight    = 1<< uiLog2TrSize;
-    Pel*  piSrc;
-    UInt  uiSrcStride;
-    if ( uiAbsSumY )
-    {
-      UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-      m_cYuvRecTemp.addClipPartLuma( &m_pcQTTempTComYuv[uiQTLayer], pcPred, uiAbsPartIdx, 1<< uiLog2TrSize  );
-      piSrc       = m_cYuvRecTemp.getLumaAddr( uiAbsPartIdx );
-      uiSrcStride = m_cYuvRecTemp.getStride  ();
+      dSubdivCost  = m_pcRdCost->calcRdCost( uiSubdivBits, uiSubdivDist );
+
+    if (!bCheckFull || (uiCbfAny && (dSubdivCost < dSingleCost)))
+    {
+      rdCost += dSubdivCost;
+      ruiBits += uiSubdivBits;
+      ruiDist += uiSubdivDist;
+#if DEBUG_STRING
+      for(UInt ch = 0; ch < numValidComp; ch++)
+      {
+        DEBUG_STRING_APPEND(sDebug, debug_reorder_data_inter_token[ch])
+        DEBUG_STRING_APPEND(sDebug, sSplitString[ch])
+      }
+#endif
     }
     else
     {
-      piSrc       = pcPred->getLumaAddr( uiAbsPartIdx );
-      uiSrcStride = pcPred->getStride  ();
-    }
-    m_pcRdCost->setRenModelData( pcCU, uiAbsPartIdx, piSrc, (Int) uiSrcStride, (Int) uiWidth, (Int) uiHeight );
-  }
-#endif
-  rdCost += dSingleCost;
-  ruiBits += uiSingleBits;
-  ruiDist += uiSingleDist;
-  
-  pcCU->setTrIdxSubParts( uiTrMode, uiAbsPartIdx, uiDepth );
-  
-  pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
-  if( bCodeChroma )
-  {
-    pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-    pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
-  }
+      rdCost  += dSingleCost;
+      ruiBits += uiSingleBits;
+      ruiDist += uiSingleDist;
+
+      //restore state to unsplit
+
+      pcCU->setTrIdxSubParts( uiTrMode, uiAbsPartIdx, uiDepth );
+
+      for(UInt ch = 0; ch < numValidComp; ch++)
+      {
+        const ComponentID compID=ComponentID(ch);
+
+        DEBUG_STRING_APPEND(sDebug, debug_reorder_data_inter_token[ch])
+        if (rTu.ProcessComponentSection(compID))
+        {
+          DEBUG_STRING_APPEND(sDebug, sSingleStringComp[compID])
+
+          const Bool splitIntoSubTUs   = rTu.getRect(compID).width != rTu.getRect(compID).height;
+          const UInt numberOfSections  = splitIntoSubTUs ? 2 : 1;
+          const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> (splitIntoSubTUs ? 1 : 0);
+
+          for (UInt subTUIndex = 0; subTUIndex < numberOfSections; subTUIndex++)
+          {
+            const UInt  uisubTUPartIdx = uiAbsPartIdx + (subTUIndex * partIdxesPerSubTU);
+
+            if (splitIntoSubTUs)
+            {
+              const UChar combinedCBF = (bestsubTUCBF[compID][subTUIndex] << subTUDepth) | (bestCBF[compID] << uiTrMode);
+              pcCU->setCbfPartRange(combinedCBF, compID, uisubTUPartIdx, partIdxesPerSubTU);
+            }
+            else
+            {
+              pcCU->setCbfPartRange((bestCBF[compID] << uiTrMode), compID, uisubTUPartIdx, partIdxesPerSubTU);
+            }
+
+            pcCU->setCrossComponentPredictionAlphaPartRange(bestCrossCPredictionAlpha[compID][subTUIndex], compID, uisubTUPartIdx, partIdxesPerSubTU);
+            pcCU->setTransformSkipPartRange(uiBestTransformMode[compID][subTUIndex], compID, uisubTUPartIdx, partIdxesPerSubTU);
+            pcCU->setExplicitRdpcmModePartRange(bestExplicitRdpcmModeUnSplit[compID][subTUIndex], compID, uisubTUPartIdx, partIdxesPerSubTU);
+          }
+        }
+      }
+
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+    }
+  }
+  else
+  {
+    rdCost  += dSingleCost;
+    ruiBits += uiSingleBits;
+    ruiDist += uiSingleDist;
+#if DEBUG_STRING
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+      DEBUG_STRING_APPEND(sDebug, debug_reorder_data_inter_token[compID])
+
+      if (rTu.ProcessComponentSection(compID))
+      {
+        DEBUG_STRING_APPEND(sDebug, sSingleStringComp[compID])
+      }
+    }
+#endif
+  }
+  DEBUG_STRING_APPEND(sDebug, debug_reorder_data_inter_token[MAX_NUM_COMPONENT])
 }
 
-Void TEncSearch::xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType )
+
+
+Void TEncSearch::xEncodeInterResidualQT( const ComponentID compID, TComTU &rTu )
 {
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+  const UInt uiCurrTrMode = rTu.GetTransformDepthRel();
   assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
-  const UInt uiCurrTrMode = uiDepth - pcCU->getDepth( 0 );
   const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
-  
+
   const Bool bSubdiv = uiCurrTrMode != uiTrMode;
-  
-  const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
-
-    if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
-    {
+
+  const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+
+  if (compID==MAX_NUM_COMPONENT)  // we are not processing a channel, instead we always recurse and code the CBFs
+  {
+    if( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      if((pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && (pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N))
+      {
+        assert(bSubdiv); // Inferred splitting rule - see derivation and use of interSplitFlag in the specification.
+      }
+      else
+      {
       m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
     }
-
-    assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
-    if( bSubdivAndCbf )
-    {
-      const Bool bFirstCbfOfCU = uiCurrTrMode == 0;
-      if( bFirstCbfOfCU || uiLog2TrSize > 2 )
-      {
-        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode - 1 ) )
-        {
-          m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode );
-        }
-        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode - 1 ) )
-        {
-          m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode );
-        }
-      }
-      else if( uiLog2TrSize == 2 )
-      {
-        assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode - 1 ) );
-        assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode - 1 ) );
-      }
-    }
-  
+    }
+    assert( !pcCU->isIntra(uiAbsPartIdx) );
+
+    const Bool bFirstCbfOfCU = uiCurrTrMode == 0;
+
+    for (UInt ch=COMPONENT_Cb; ch<pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compIdInner=ComponentID(ch);
+      if( bFirstCbfOfCU || rTu.ProcessingAllQuadrants(compIdInner) )
+      {
+        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, compIdInner, uiCurrTrMode - 1 ) )
+        {
+          m_pcEntropyCoder->encodeQtCbf( rTu, compIdInner, !bSubdiv );
+        }
+      }
+      else
+      {
+        assert( pcCU->getCbf( uiAbsPartIdx, compIdInner, uiCurrTrMode ) == pcCU->getCbf( uiAbsPartIdx, compIdInner, uiCurrTrMode - 1 ) );
+      }
+    }
+
+    if (!bSubdiv)
+    {
+      m_pcEntropyCoder->encodeQtCbf( rTu, COMPONENT_Y, true );
+    }
+  }
+
   if( !bSubdiv )
   {
-    const UInt uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
-    //assert( 16 == uiNumCoeffPerAbsPartIdxIncrement ); // check
-    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-    TCoeff *pcCoeffCurrY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
-    TCoeff *pcCoeffCurrU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-    TCoeff *pcCoeffCurrV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-    
-    Bool  bCodeChroma   = true;
-    UInt  uiTrModeC     = uiTrMode;
-    UInt  uiLog2TrSizeC = uiLog2TrSize-1;
-    if( uiLog2TrSize == 2 )
-    {
-      uiLog2TrSizeC++;
-      uiTrModeC    --;
-      UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
-      bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
-    }
-    
-    if( bSubdivAndCbf )
-    {
-        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
-      }
+    if (compID != MAX_NUM_COMPONENT) // we have already coded the CBFs, so now we code coefficients
+    {
+      if (rTu.ProcessComponentSection(compID))
+      {
+        if (isChroma(compID) && (pcCU->getCbf(uiAbsPartIdx, COMPONENT_Y, uiTrMode) != 0))
+        {
+          m_pcEntropyCoder->encodeCrossComponentPrediction(rTu, compID);
+        }
+
+        if (pcCU->getCbf(uiAbsPartIdx, compID, uiTrMode) != 0)
+        {
+          const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+          TCoeff *pcCoeffCurr = m_ppcQTTempCoeff[compID][uiQTTempAccessLayer] + rTu.getCoefficientOffset(compID);
+          m_pcEntropyCoder->encodeCoeffNxN( rTu, pcCoeffCurr, compID );
+        }
+      }
+    }
+  }
+  else
+  {
+    if( compID==MAX_NUM_COMPONENT || pcCU->getCbf( uiAbsPartIdx, compID, uiCurrTrMode ) )
+    {
+      TComTURecurse tuRecurseChild(rTu, false);
+      do
+      {
+        xEncodeInterResidualQT( compID, tuRecurseChild );
+      } while (tuRecurseChild.nextSection(rTu));
+    }
+  }
+}
+
+
+
+
+Void TEncSearch::xSetInterResidualQTData( TComYuv* pcResi, Bool bSpatial, TComTU &rTu ) // TODO: turn this into two functions for bSpatial=true and false.
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiCurrTrMode=rTu.GetTransformDepthRel();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
+  const TComSPS *sps=pcCU->getSlice()->getSPS();
+
+  if( uiCurrTrMode == uiTrMode )
+  {
+    const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+    const UInt uiQTTempAccessLayer = sps->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    if( bSpatial )
+    {
+      // Data to be copied is in the spatial domain, i.e., inverse-transformed.
+
+      for(UInt i=0; i<pcResi->getNumberValidComponents(); i++)
+      {
+        const ComponentID compID=ComponentID(i);
+        if (rTu.ProcessComponentSection(compID))
+        {
+          const TComRectangle &rectCompTU(rTu.getRect(compID));
+          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartComponentMxN    ( compID, pcResi, rectCompTU );
+        }
+      }
+    }
     else
     {
-      if( eType == TEXT_LUMA     && pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA,     uiTrMode ) )
-      {
-        Int trWidth  = 1 << uiLog2TrSize;
-        Int trHeight = 1 << uiLog2TrSize;
-        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
-      }
-      if( bCodeChroma )
-      {
-        Int trWidth  = 1 << uiLog2TrSizeC;
-        Int trHeight = 1 << uiLog2TrSizeC;
-        if( eType == TEXT_CHROMA_U && pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode ) )
-        {
-          m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
-        }
-        if( eType == TEXT_CHROMA_V && pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode ) )
-        {
-          m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+      for (UInt ch=0; ch < getNumberValidComponents(sps->getChromaFormatIdc()); ch++)
+      {
+        const ComponentID compID   = ComponentID(ch);
+        if (rTu.ProcessComponentSection(compID))
+        {
+          const TComRectangle &rectCompTU(rTu.getRect(compID));
+          const UInt numCoeffInBlock    = rectCompTU.width * rectCompTU.height;
+          const UInt offset             = rTu.getCoefficientOffset(compID);
+          TCoeff* dest                  = pcCU->getCoeff(compID)                        + offset;
+          const TCoeff* src             = m_ppcQTTempCoeff[compID][uiQTTempAccessLayer] + offset;
+          ::memcpy( dest, src, sizeof(TCoeff)*numCoeffInBlock );
+
+#if ADAPTIVE_QP_SELECTION
+          TCoeff* pcArlCoeffSrc            = m_ppcQTTempArlCoeff[compID][uiQTTempAccessLayer] + offset;
+          TCoeff* pcArlCoeffDst            = pcCU->getArlCoeff(compID)                        + offset;
+          ::memcpy( pcArlCoeffDst, pcArlCoeffSrc, sizeof( TCoeff ) * numCoeffInBlock );
+#endif
         }
       }
@@ -7138,106 +7001,50 @@
   else
   {
-    if( bSubdivAndCbf || pcCU->getCbf( uiAbsPartIdx, eType, uiCurrTrMode ) )
-    {
-      const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
-      for( UInt ui = 0; ui < 4; ++ui )
-      {
-        xEncodeResidualQT( pcCU, uiAbsPartIdx + ui * uiQPartNumSubdiv, uiDepth + 1, bSubdivAndCbf, eType );
-      }
-    }
+
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xSetInterResidualQTData( pcResi, bSpatial, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
   }
 }
 
-Void TEncSearch::xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial )
+
+
+
+UInt TEncSearch::xModeBitsIntra( TComDataCU* pcCU, UInt uiMode, UInt uiPartOffset, UInt uiDepth, const ChannelType chType )
 {
-  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
-  const UInt uiCurrTrMode = uiDepth - pcCU->getDepth( 0 );
-  const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
-
-  if( uiCurrTrMode == uiTrMode )
-  {
-    const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
-    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
-
-    Bool  bCodeChroma   = true;
-    UInt  uiTrModeC     = uiTrMode;
-    UInt  uiLog2TrSizeC = uiLog2TrSize-1;
-    if( uiLog2TrSize == 2 )
-    {
-      uiLog2TrSizeC++;
-      uiTrModeC    --;
-      UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
-      bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
-    }
-
-    if( bSpatial )
-    {      
-      Int trWidth  = 1 << uiLog2TrSize;
-      Int trHeight = 1 << uiLog2TrSize;
-      m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartLuma    ( pcResi, absTUPartIdx, trWidth , trHeight );
-
-      if( bCodeChroma )
-      {
-          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
-        }
-      }
-    else
-    {
-      UInt    uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
-      UInt    uiNumCoeffY = ( 1 << ( uiLog2TrSize << 1 ) );
-      TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
-      TCoeff* pcCoeffDstY = pcCU->getCoeffY() + uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
-      ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
-#if ADAPTIVE_QP_SELECTION
-      Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
-      Int* pcArlCoeffDstY = pcCU->getArlCoeffY() + uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
-      ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
-#endif
-      if( bCodeChroma )
-      {
-        UInt    uiNumCoeffC = ( 1 << ( uiLog2TrSizeC << 1 ) );
-        TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-        TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-        TCoeff* pcCoeffDstU = pcCU->getCoeffCb() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-        TCoeff* pcCoeffDstV = pcCU->getCoeffCr() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-        ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
-        ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
-#if ADAPTIVE_QP_SELECTION
-        Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-        Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-        Int* pcArlCoeffDstU = pcCU->getArlCoeffCb() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-        Int* pcArlCoeffDstV = pcCU->getArlCoeffCr() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
-        ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
-        ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
-#endif
-      }
-    }
-  }
-  else
-  {
-    const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
-    for( UInt ui = 0; ui < 4; ++ui )
-    {
-      UInt nsAddr = uiAbsPartIdx + ui * uiQPartNumSubdiv;
-      xSetResidualQTData( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcResi, uiDepth + 1, bSpatial );
-    }
-  }
-}
-
-UInt TEncSearch::xModeBitsIntra( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth )
-{
-    // Reload only contexts required for coding intra mode information
-    m_pcRDGoOnSbacCoder->loadIntraDirModeLuma( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+  // Reload only contexts required for coding intra mode information
+  m_pcRDGoOnSbacCoder->loadIntraDirMode( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST], chType );
 #if H_3D_DIM
     m_pcRDGoOnSbacCoder->loadIntraDepthMode( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
 #endif
-  
-  pcCU->setLumaIntraDirSubParts ( uiMode, uiPartOffset, uiDepth + uiInitTrDepth );
-  
+
+  // Temporarily set the intra dir being tested, and only
+  // for absPartIdx, since encodeIntraDirModeLuma/Chroma only use
+  // the entry at absPartIdx.
+
+  UChar &rIntraDirVal=pcCU->getIntraDir( chType )[uiPartOffset];
+  UChar origVal=rIntraDirVal;
+  rIntraDirVal = uiMode;
+  //pcCU->setIntraDirSubParts ( chType, uiMode, uiPartOffset, uiDepth + uiInitTrDepth );
+
   m_pcEntropyCoder->resetBits();
-  m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPartOffset);
-  
+  if (isLuma(chType))
+  {
+    m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPartOffset);
+  }
+  else
+  {
+    m_pcEntropyCoder->encodeIntraDirModeChroma ( pcCU, uiPartOffset);
+  }
+
+  rIntraDirVal = origVal; // restore
+
   return m_pcEntropyCoder->getNumberOfWrittenBits();
 }
+
+
+
 
 UInt TEncSearch::xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList )
@@ -7245,7 +7052,10 @@
   UInt i;
   UInt shift=0;
-  
-  while ( shift<uiFastCandNum && uiCost<CandCostList[ uiFastCandNum-1-shift ] ) shift++;
-  
+
+  while ( shift<uiFastCandNum && uiCost<CandCostList[ uiFastCandNum-1-shift ] )
+  {
+    shift++;
+  }
+
   if( shift!=0 )
   {
@@ -7259,7 +7069,11 @@
     return 1;
   }
-  
+
   return 0;
 }
+
+
+
+
 
 /** add inter-prediction syntax elements for a CU block
@@ -7268,10 +7082,7 @@
  * \param uiTrMode
  * \param ruiBits
- * \param rpcYuvRec
- * \param pcYuvPred
- * \param rpcYuvResi
  * \returns Void
  */
-Void  TEncSearch::xAddSymbolBitsInter( TComDataCU* pcCU, UInt uiQp, UInt uiTrMode, UInt& ruiBits, TComYuv*& rpcYuvRec, TComYuv*pcYuvPred, TComYuv*& rpcYuvResi )
+Void  TEncSearch::xAddSymbolBitsInter( TComDataCU* pcCU, UInt& ruiBits )
 {
   if(pcCU->getMergeFlag( 0 ) && pcCU->getPartitionSize( 0 ) == SIZE_2Nx2N && !pcCU->getQtRootCbf( 0 ))
@@ -7297,8 +7108,10 @@
   {
     m_pcEntropyCoder->resetBits();
+
     if(pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
     {
       m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
     }
+
     m_pcEntropyCoder->encodeSkipFlag ( pcCU, 0, true );
 #if H_3D
@@ -7307,5 +7120,5 @@
     m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
     m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
-    m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+    m_pcEntropyCoder->encodePredInfo( pcCU, 0 );
 #if H_3D_DIM_SDC
     m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
@@ -7320,14 +7133,16 @@
     m_pcEntropyCoder->encodeDBBPFlag( pcCU, 0, true );
 #endif
-    Bool bDummy = false;
-#if H_3D_DISABLE_CHROMA
-    m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0), bDummy, true );
-#else
-    m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0), bDummy );
-#endif
-    
+
+    Bool codeDeltaQp = false;
+    Bool codeChromaQpAdj = false;
+    m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), codeDeltaQp, codeChromaQpAdj );
+
     ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
   }
 }
+
+
+
+
 
 /**
@@ -7337,37 +7152,43 @@
  * \param biPred    Flag indicating whether block is for biprediction
  */
-Void TEncSearch::xExtDIFUpSamplingH( TComPattern* pattern, Bool biPred )
+Void TEncSearch::xExtDIFUpSamplingH( TComPattern* pattern )
 {
   Int width      = pattern->getROIYWidth();
   Int height     = pattern->getROIYHeight();
   Int srcStride  = pattern->getPatternLStride();
-  
-  Int intStride = m_filteredBlockTmp[0].getStride();
-  Int dstStride = m_filteredBlock[0][0].getStride();
-  Short *intPtr;
-  Short *dstPtr;
+
+  Int intStride = m_filteredBlockTmp[0].getStride(COMPONENT_Y);
+  Int dstStride = m_filteredBlock[0][0].getStride(COMPONENT_Y);
+  Pel *intPtr;
+  Pel *dstPtr;
   Int filterSize = NTAPS_LUMA;
   Int halfFilterSize = (filterSize>>1);
   Pel *srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
-  
-  m_if.filterHorLuma(srcPtr, srcStride, m_filteredBlockTmp[0].getLumaAddr(), intStride, width+1, height+filterSize, 0, false);
-  m_if.filterHorLuma(srcPtr, srcStride, m_filteredBlockTmp[2].getLumaAddr(), intStride, width+1, height+filterSize, 2, false);
-  
-  intPtr = m_filteredBlockTmp[0].getLumaAddr() + halfFilterSize * intStride + 1;  
-  dstPtr = m_filteredBlock[0][0].getLumaAddr();
-  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+0, height+0, 0, false, true);
-  
-  intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;  
-  dstPtr = m_filteredBlock[2][0].getLumaAddr();
-  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+0, height+1, 2, false, true);
-  
-  intPtr = m_filteredBlockTmp[2].getLumaAddr() + halfFilterSize * intStride;
-  dstPtr = m_filteredBlock[0][2].getLumaAddr();
-  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+1, height+0, 0, false, true);
-  
-  intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
-  dstPtr = m_filteredBlock[2][2].getLumaAddr();
-  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+1, height+1, 2, false, true);
+
+  const ChromaFormat chFmt = m_filteredBlock[0][0].getChromaFormat();
+
+  m_if.filterHor(COMPONENT_Y, srcPtr, srcStride, m_filteredBlockTmp[0].getAddr(COMPONENT_Y), intStride, width+1, height+filterSize, 0, false, chFmt, pattern->getBitDepthY());
+  m_if.filterHor(COMPONENT_Y, srcPtr, srcStride, m_filteredBlockTmp[2].getAddr(COMPONENT_Y), intStride, width+1, height+filterSize, 2, false, chFmt, pattern->getBitDepthY());
+
+  intPtr = m_filteredBlockTmp[0].getAddr(COMPONENT_Y) + halfFilterSize * intStride + 1;
+  dstPtr = m_filteredBlock[0][0].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width+0, height+0, 0, false, true, chFmt, pattern->getBitDepthY());
+
+  intPtr = m_filteredBlockTmp[0].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride + 1;
+  dstPtr = m_filteredBlock[2][0].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width+0, height+1, 2, false, true, chFmt, pattern->getBitDepthY());
+
+  intPtr = m_filteredBlockTmp[2].getAddr(COMPONENT_Y) + halfFilterSize * intStride;
+  dstPtr = m_filteredBlock[0][2].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width+1, height+0, 0, false, true, chFmt, pattern->getBitDepthY());
+
+  intPtr = m_filteredBlockTmp[2].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[2][2].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width+1, height+1, 2, false, true, chFmt, pattern->getBitDepthY());
 }
+
+
+
+
 
 /**
@@ -7378,24 +7199,26 @@
  * \param biPred     Flag indicating whether block is for biprediction
  */
-Void TEncSearch::xExtDIFUpSamplingQ( TComPattern* pattern, TComMv halfPelRef, Bool biPred )
+Void TEncSearch::xExtDIFUpSamplingQ( TComPattern* pattern, TComMv halfPelRef )
 {
   Int width      = pattern->getROIYWidth();
   Int height     = pattern->getROIYHeight();
   Int srcStride  = pattern->getPatternLStride();
-  
+
   Pel *srcPtr;
-  Int intStride = m_filteredBlockTmp[0].getStride();
-  Int dstStride = m_filteredBlock[0][0].getStride();
-  Short *intPtr;
-  Short *dstPtr;
+  Int intStride = m_filteredBlockTmp[0].getStride(COMPONENT_Y);
+  Int dstStride = m_filteredBlock[0][0].getStride(COMPONENT_Y);
+  Pel *intPtr;
+  Pel *dstPtr;
   Int filterSize = NTAPS_LUMA;
-  
+
   Int halfFilterSize = (filterSize>>1);
 
   Int extHeight = (halfPelRef.getVer() == 0) ? height + filterSize : height + filterSize-1;
-  
+
+  const ChromaFormat chFmt = m_filteredBlock[0][0].getChromaFormat();
+
   // Horizontal filter 1/4
   srcPtr = pattern->getROIY() - halfFilterSize * srcStride - 1;
-  intPtr = m_filteredBlockTmp[1].getLumaAddr();
+  intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y);
   if (halfPelRef.getVer() > 0)
   {
@@ -7406,9 +7229,9 @@
     srcPtr += 1;
   }
-  m_if.filterHorLuma(srcPtr, srcStride, intPtr, intStride, width, extHeight, 1, false);
-  
+  m_if.filterHor(COMPONENT_Y, srcPtr, srcStride, intPtr, intStride, width, extHeight, 1, false, chFmt, pattern->getBitDepthY());
+
   // Horizontal filter 3/4
   srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
-  intPtr = m_filteredBlockTmp[3].getLumaAddr();
+  intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y);
   if (halfPelRef.getVer() > 0)
   {
@@ -7419,58 +7242,58 @@
     srcPtr += 1;
   }
-  m_if.filterHorLuma(srcPtr, srcStride, intPtr, intStride, width, extHeight, 3, false);        
-  
+  m_if.filterHor(COMPONENT_Y, srcPtr, srcStride, intPtr, intStride, width, extHeight, 3, false, chFmt, pattern->getBitDepthY());
+
   // Generate @ 1,1
-  intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
-  dstPtr = m_filteredBlock[1][1].getLumaAddr();
+  intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][1].getAddr(COMPONENT_Y);
   if (halfPelRef.getVer() == 0)
   {
     intPtr += intStride;
   }
-  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
-  
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true, chFmt, pattern->getBitDepthY());
+
   // Generate @ 3,1
-  intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
-  dstPtr = m_filteredBlock[3][1].getLumaAddr();
-  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
-  
+  intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[3][1].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true, chFmt, pattern->getBitDepthY());
+
   if (halfPelRef.getVer() != 0)
   {
     // Generate @ 2,1
-    intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
-    dstPtr = m_filteredBlock[2][1].getLumaAddr();
+    intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][1].getAddr(COMPONENT_Y);
     if (halfPelRef.getVer() == 0)
     {
       intPtr += intStride;
     }
-    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true);
-    
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true, chFmt, pattern->getBitDepthY());
+
     // Generate @ 2,3
-    intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
-    dstPtr = m_filteredBlock[2][3].getLumaAddr();
+    intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][3].getAddr(COMPONENT_Y);
     if (halfPelRef.getVer() == 0)
     {
       intPtr += intStride;
     }
-    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true);
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true, chFmt, pattern->getBitDepthY());
   }
   else
   {
     // Generate @ 0,1
-    intPtr = m_filteredBlockTmp[1].getLumaAddr() + halfFilterSize * intStride;
-    dstPtr = m_filteredBlock[0][1].getLumaAddr();
-    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true);
-    
+    intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y) + halfFilterSize * intStride;
+    dstPtr = m_filteredBlock[0][1].getAddr(COMPONENT_Y);
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true, chFmt, pattern->getBitDepthY());
+
     // Generate @ 0,3
-    intPtr = m_filteredBlockTmp[3].getLumaAddr() + halfFilterSize * intStride;
-    dstPtr = m_filteredBlock[0][3].getLumaAddr();
-    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true);
-  }
-  
+    intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y) + halfFilterSize * intStride;
+    dstPtr = m_filteredBlock[0][3].getAddr(COMPONENT_Y);
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true, chFmt, pattern->getBitDepthY());
+  }
+
   if (halfPelRef.getHor() != 0)
   {
     // Generate @ 1,2
-    intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
-    dstPtr = m_filteredBlock[1][2].getLumaAddr();
+    intPtr = m_filteredBlockTmp[2].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[1][2].getAddr(COMPONENT_Y);
     if (halfPelRef.getHor() > 0)
     {
@@ -7481,9 +7304,9 @@
       intPtr += intStride;
     }
-    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
-    
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true, chFmt, pattern->getBitDepthY());
+
     // Generate @ 3,2
-    intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
-    dstPtr = m_filteredBlock[3][2].getLumaAddr();
+    intPtr = m_filteredBlockTmp[2].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[3][2].getAddr(COMPONENT_Y);
     if (halfPelRef.getHor() > 0)
     {
@@ -7494,48 +7317,44 @@
       intPtr += intStride;
     }
-    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);  
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true, chFmt, pattern->getBitDepthY());
   }
   else
   {
     // Generate @ 1,0
-    intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;
-    dstPtr = m_filteredBlock[1][0].getLumaAddr();
+    intPtr = m_filteredBlockTmp[0].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[1][0].getAddr(COMPONENT_Y);
     if (halfPelRef.getVer() >= 0)
     {
       intPtr += intStride;
     }
-    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
-    
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true, chFmt, pattern->getBitDepthY());
+
     // Generate @ 3,0
-    intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;
-    dstPtr = m_filteredBlock[3][0].getLumaAddr();
+    intPtr = m_filteredBlockTmp[0].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[3][0].getAddr(COMPONENT_Y);
     if (halfPelRef.getVer() > 0)
     {
       intPtr += intStride;
     }
-    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
-  }
-  
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true, chFmt, pattern->getBitDepthY());
+  }
+
   // Generate @ 1,3
-  intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
-  dstPtr = m_filteredBlock[1][3].getLumaAddr();
+  intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][3].getAddr(COMPONENT_Y);
   if (halfPelRef.getVer() == 0)
   {
     intPtr += intStride;
   }
-  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
-  
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true, chFmt, pattern->getBitDepthY());
+
   // Generate @ 3,3
-  intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
-  dstPtr = m_filteredBlock[3][3].getLumaAddr();
-  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
+  intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[3][3].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true, chFmt, pattern->getBitDepthY());
 }
 
-/** set wp tables
- * \param TComDataCU* pcCU
- * \param iRefIdx
- * \param eRefPicListCur
- * \returns Void
- */
+
+//! set wp tables
 Void  TEncSearch::setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur )
 {
@@ -7547,8 +7366,12 @@
 
   TComSlice       *pcSlice  = pcCU->getSlice();
-  TComPPS         *pps      = pcCU->getSlice()->getPPS();
-  wpScalingParam  *wp0 , *wp1;
-  m_cDistParam.bApplyWeight = ( pcSlice->getSliceType()==P_SLICE && pps->getUseWP() ) || ( pcSlice->getSliceType()==B_SLICE && pps->getWPBiPred() ) ;
-  if ( !m_cDistParam.bApplyWeight ) return;
+  WPScalingParam  *wp0 , *wp1;
+
+  m_cDistParam.bApplyWeight = ( pcSlice->getSliceType()==P_SLICE && pcSlice->testWeightPred() ) || ( pcSlice->getSliceType()==B_SLICE && pcSlice->testWeightBiPred() ) ;
+
+  if ( !m_cDistParam.bApplyWeight )
+  {
+    return;
+  }
 
   Int iRefIdx0 = ( eRefPicListCur == REF_PIC_LIST_0 ) ? iRefIdx : (-1);
@@ -7557,6 +7380,12 @@
   getWpScaling( pcCU, iRefIdx0, iRefIdx1, wp0 , wp1 );
 
-  if ( iRefIdx0 < 0 ) wp0 = NULL;
-  if ( iRefIdx1 < 0 ) wp1 = NULL;
+  if ( iRefIdx0 < 0 )
+  {
+    wp0 = NULL;
+  }
+  if ( iRefIdx1 < 0 )
+  {
+    wp1 = NULL;
+  }
 
   m_cDistParam.wpCur  = NULL;
@@ -7851,7 +7680,6 @@
 }
 
-
-#endif
-
-#endif
+#endif
+#endif
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSearch.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSearch.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -35,5 +35,4 @@
     \brief    encoder search class (header)
 */
-
 #ifndef __TENCSEARCH__
 #define __TENCSEARCH__
@@ -46,4 +45,5 @@
 #include "TLibCommon/TComTrQuant.h"
 #include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComRectangle.h"
 #include "TEncEntropy.h"
 #include "TEncSbac.h"
@@ -58,4 +58,8 @@
 // Class definition
 // ====================================================================================================================
+
+static const UInt MAX_NUM_REF_LIST_ADAPT_SR=2;
+static const UInt MAX_IDX_ADAPT_SR=33;
+static const UInt NUM_MV_PREDICTORS=3;
 
 /// encoder search class
@@ -63,63 +67,56 @@
 {
 private:
-  TCoeff**        m_ppcQTTempCoeffY;
-  TCoeff**        m_ppcQTTempCoeffCb;
-  TCoeff**        m_ppcQTTempCoeffCr;
-  TCoeff*         m_pcQTTempCoeffY;
-  TCoeff*         m_pcQTTempCoeffCb;
-  TCoeff*         m_pcQTTempCoeffCr;
+  TCoeff**        m_ppcQTTempCoeff[MAX_NUM_COMPONENT /* 0->Y, 1->Cb, 2->Cr*/];
+  TCoeff*         m_pcQTTempCoeff[MAX_NUM_COMPONENT];
 #if ADAPTIVE_QP_SELECTION
-  Int**           m_ppcQTTempArlCoeffY;
-  Int**           m_ppcQTTempArlCoeffCb;
-  Int**           m_ppcQTTempArlCoeffCr;
-  Int*            m_pcQTTempArlCoeffY;
-  Int*            m_pcQTTempArlCoeffCb;
-  Int*            m_pcQTTempArlCoeffCr;
+  TCoeff**        m_ppcQTTempArlCoeff[MAX_NUM_COMPONENT];
+  TCoeff*         m_pcQTTempArlCoeff[MAX_NUM_COMPONENT];
 #endif
   UChar*          m_puhQTTempTrIdx;
-  UChar*          m_puhQTTempCbf[3];
-  
+  UChar*          m_puhQTTempCbf[MAX_NUM_COMPONENT];
+
   TComYuv*        m_pcQTTempTComYuv;
   TComYuv         m_tmpYuvPred; // To be used in xGetInterPredictionError() to avoid constant memory allocation/deallocation
-  Pel*            m_pSharedPredTransformSkip[3];
-  TCoeff*         m_pcQTTempTUCoeffY;
-  TCoeff*         m_pcQTTempTUCoeffCb;
-  TCoeff*         m_pcQTTempTUCoeffCr;
-  UChar*          m_puhQTTempTransformSkipFlag[3];
+
+  Char*           m_phQTTempCrossComponentPredictionAlpha[MAX_NUM_COMPONENT];
+  Pel*            m_pSharedPredTransformSkip[MAX_NUM_COMPONENT];
+  TCoeff*         m_pcQTTempTUCoeff[MAX_NUM_COMPONENT];
+  UChar*          m_puhQTTempTransformSkipFlag[MAX_NUM_COMPONENT];
   TComYuv         m_pcQTTempTransformSkipTComYuv;
 #if ADAPTIVE_QP_SELECTION
-  Int*            m_ppcQTTempTUArlCoeffY;
-  Int*            m_ppcQTTempTUArlCoeffCb;
-  Int*            m_ppcQTTempTUArlCoeffCr;
-#endif
+  TCoeff*         m_ppcQTTempTUArlCoeff[MAX_NUM_COMPONENT];
+#endif
+
 protected:
   // interface to option
   TEncCfg*        m_pcEncCfg;
-  
+
   // interface to classes
   TComTrQuant*    m_pcTrQuant;
   TComRdCost*     m_pcRdCost;
   TEncEntropy*    m_pcEntropyCoder;
-  
+
   // ME parameters
   Int             m_iSearchRange;
   Int             m_bipredSearchRange; // Search range for bi-prediction
   Int             m_iFastSearch;
-  Int             m_aaiAdaptSR[2][33];
+#if NH_MV
+  Bool            m_vertRestriction; 
+#endif 
+  Int             m_aaiAdaptSR[MAX_NUM_REF_LIST_ADAPT_SR][MAX_IDX_ADAPT_SR];
   TComMv          m_cSrchRngLT;
   TComMv          m_cSrchRngRB;
-  TComMv          m_acMvPredictors[3];
-  
+  TComMv          m_acMvPredictors[NUM_MV_PREDICTORS]; // Left, Above, AboveRight. enum MVP_DIR first NUM_MV_PREDICTORS entries are suitable for accessing.
+
   // RD computation
   TEncSbac***     m_pppcRDSbacCoder;
   TEncSbac*       m_pcRDGoOnSbacCoder;
   DistParam       m_cDistParam;
-  
+
   // Misc.
   Pel*            m_pTempPel;
   const UInt*     m_puiDFilter;
-  Int             m_iMaxDeltaQP;
-
-#if H_3D_VSO // M17
+
+#if NH_3D_VSO // M17
   TComYuv         m_cYuvRecTemp; 
 #endif
@@ -127,9 +124,11 @@
   // UInt            m_auiMVPIdxCost[AMVP_MAX_NUM_CANDS+1][AMVP_MAX_NUM_CANDS];
   UInt            m_auiMVPIdxCost[AMVP_MAX_NUM_CANDS+1][AMVP_MAX_NUM_CANDS+1]; //th array bounds
-  
+
+  TComMv          m_integerMv2Nx2N[NUM_REF_PIC_LIST_01][MAX_NUM_REF];
+
 public:
   TEncSearch();
   virtual ~TEncSearch();
-  
+
   Void init(  TEncCfg*      pcEncCfg,
             TComTrQuant*  pcTrQuant,
@@ -137,29 +136,32 @@
             Int           bipredSearchRange,
             Int           iFastSearch,
-            Int           iMaxDeltaQP,
+            const UInt    maxCUWidth,
+            const UInt    maxCUHeight,
+            const UInt    maxTotalCUDepth,
             TEncEntropy*  pcEntropyCoder,
             TComRdCost*   pcRdCost,
             TEncSbac***   pppcRDSbacCoder,
             TEncSbac*     pcRDGoOnSbacCoder );
-  
+
 protected:
-  
+
   /// sub-function for motion vector refinement used in fractional-pel accuracy
-  UInt  xPatternRefinement( TComPattern* pcPatternKey,
-                           TComMv baseRefMv,
-                           Int iFrac, TComMv& rcMvFrac );
-  
+  Distortion  xPatternRefinement( TComPattern* pcPatternKey,
+                                  TComMv baseRefMv,
+                                  Int iFrac, TComMv& rcMvFrac, Bool bAllowUseOfHadamard
+                                 );
+
   typedef struct
   {
-    Pel*  piRefY;
-    Int   iYStride;
-    Int   iBestX;
-    Int   iBestY;
-    UInt  uiBestRound;
-    UInt  uiBestDistance;
-    UInt  uiBestSad;
-    UChar ucPointNr;
+    Pel*        piRefY;
+    Int         iYStride;
+    Int         iBestX;
+    Int         iBestY;
+    UInt        uiBestRound;
+    UInt        uiBestDistance;
+    Distortion  uiBestSad;
+    UChar       ucPointNr;
   } IntTZSearchStruct;
-  
+
   // sub-functions for ME
   __inline Void xTZSearchHelp         ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance );
@@ -167,28 +169,26 @@
   __inline Void xTZ8PointSquareSearch ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist );
   __inline Void xTZ8PointDiamondSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist );
-  
-  Void xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, UInt& ruiSAD, Bool Hadamard );
+
+  Void xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, Distortion& ruiSAD, Bool Hadamard );
 
 public:
-  Void  preestChromaPredMode    ( TComDataCU* pcCU, 
-                                  TComYuv*    pcOrgYuv, 
-                                  TComYuv*    pcPredYuv );
-  Void  estIntraPredQT          ( TComDataCU* pcCU, 
-                                  TComYuv*    pcOrgYuv, 
-                                  TComYuv*    pcPredYuv, 
-                                  TComYuv*    pcResiYuv, 
+  Void  estIntraPredLumaQT      ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*    pcPredYuv,
+                                  TComYuv*    pcResiYuv,
                                   TComYuv*    pcRecoYuv,
-                                  UInt&       ruiDistC,
-                                  Bool        bLumaOnly
+                                  Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE]
 #if H_3D_DIM
                                 , Bool        bOnlyIVP
 #endif
-                                );
-  Void  estIntraPredChromaQT    ( TComDataCU* pcCU, 
-                                  TComYuv*    pcOrgYuv, 
-                                  TComYuv*    pcPredYuv, 
-                                  TComYuv*    pcResiYuv, 
+                                  DEBUG_STRING_FN_DECLARE(sDebug));
+
+  Void  estIntraPredChromaQT    ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*    pcPredYuv,
+                                  TComYuv*    pcResiYuv,
                                   TComYuv*    pcRecoYuv,
-                                  UInt        uiPreCalcDistC );
+                                  Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE]
+                                  DEBUG_STRING_FN_DECLARE(sDebug));
 #if H_3D
   Void  estIntraPredDIS        ( TComDataCU* pcCU, 
@@ -200,13 +200,15 @@
                                  Bool        bLumaOnly );
 #endif  
+
   /// encoder estimation - inter prediction (non-skip)
   Void predInterSearch          ( TComDataCU* pcCU,
                                   TComYuv*    pcOrgYuv,
-                                  TComYuv*&   rpcPredYuv,
-                                  TComYuv*&   rpcResiYuv,
-                                  TComYuv*&   rpcRecoYuv,
+                                  TComYuv*    pcPredYuv,
+                                  TComYuv*    pcResiYuv,
+                                  TComYuv*    pcRecoYuv
 #if H_3D_FAST_TEXTURE_ENCODING
                                   Bool        bFMD,
 #endif
+                                  DEBUG_STRING_FN_DECLARE(sDebug),
                                   Bool        bUseRes = false
 #if AMP_MRG
@@ -214,13 +216,14 @@
 #endif
                                 );
-  
+
   /// encode residual and compute rd-cost for inter mode
   Void encodeResAndCalcRdInterCU( TComDataCU* pcCU,
                                   TComYuv*    pcYuvOrg,
                                   TComYuv*    pcYuvPred,
-                                  TComYuv*&   rpcYuvResi,
-                                  TComYuv*&   rpcYuvResiBest,
-                                  TComYuv*&   rpcYuvRec,
-                                  Bool        bSkipRes );
+                                  TComYuv*    pcYuvResi,
+                                  TComYuv*    pcYuvResiBest,
+                                  TComYuv*    pcYuvRec,
+                                  Bool        bSkipResidual
+                                  DEBUG_STRING_FN_DECLARE(sDebug) );
 #if H_3D_INTER_SDC
   Void encodeResAndCalcRdInterSDCCU( TComDataCU* pcCU,
@@ -232,25 +235,22 @@
     const UInt uiDepth );
 #endif
+
   /// set ME search range
-  Void setAdaptiveSearchRange   ( Int iDir, Int iRefIdx, Int iSearchRange) { m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange; }
-  
-  Void xEncPCM    (TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piOrg, Pel* piPCM, Pel* piPred, Pel* piResi, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType eText);
-  Void IPCMSearch (TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv );
+  Void setAdaptiveSearchRange   ( Int iDir, Int iRefIdx, Int iSearchRange) { assert(iDir < MAX_NUM_REF_LIST_ADAPT_SR && iRefIdx<Int(MAX_IDX_ADAPT_SR)); m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange; }
+
+  Void xEncPCM    (TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piOrg, Pel* piPCM, Pel* piPred, Pel* piResi, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, const ComponentID compID );
+  Void IPCMSearch (TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* rpcPredYuv, TComYuv* rpcResiYuv, TComYuv* rpcRecoYuv );
 protected:
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // Intra search
   // -------------------------------------------------------------------------------------------------------------------
-  
-  Void  xEncSubdivCbfQT           ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
+
+  Void  xEncSubdivCbfQT           ( TComTU      &rTu,
                                     Bool         bLuma,
                                     Bool         bChroma );
 
-  Void  xEncCoeffQT               ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    TextType     eTextType,
+  Void  xEncCoeffQT               ( TComTU &rTu,
+                                    ComponentID  component,
                                     Bool         bRealCoeff );
   Void  xEncIntraHeader           ( TComDataCU*  pcCU,
@@ -259,99 +259,87 @@
                                     Bool         bLuma,
                                     Bool         bChroma );
-  UInt  xGetIntraBitsQT           ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
+  UInt  xGetIntraBitsQT           ( TComTU &rTu,
                                     Bool         bLuma,
                                     Bool         bChroma,
                                     Bool         bRealCoeff );
-  UInt  xGetIntraBitsQTChroma    ( TComDataCU*   pcCU,
-                                   UInt          uiTrDepth,
-                                   UInt          uiAbsPartIdx,
-                                   UInt          uiChromaId,
+
+  UInt  xGetIntraBitsQTChroma    ( TComTU &rTu,
+                                   ComponentID compID,
                                    Bool          bRealCoeff );
-  
-  Void  xIntraCodingLumaBlk       ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    TComYuv*     pcOrgYuv, 
-                                    TComYuv*     pcPredYuv, 
-                                    TComYuv*     pcResiYuv, 
-#if H_3D_VSO
+
+  Void  xIntraCodingTUBlock       (       TComYuv*      pcOrgYuv,
+                                          TComYuv*      pcPredYuv,
+                                          TComYuv*      pcResiYuv,
+                                          Pel           resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                    const Bool          checkCrossCPrediction,
+#if NH_3D_VSO
                                     Dist&        ruiDist,
 #else
-                                    UInt&        ruiDist,
-#endif
-                                    Int         default0Save1Load2 = 0
+                                    Distortion&   ruiDist,
+#endif
+const ComponentID   compID,
+                                          TComTU        &rTu
+                                    DEBUG_STRING_FN_DECLARE(sTest)
+                                         ,Int           default0Save1Load2 = 0
 #if H_3D_DIM_ENC
                                   , Bool          zeroResi = false
 #endif
-                                    );
-  Void  xIntraCodingChromaBlk     ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    TComYuv*     pcOrgYuv, 
-                                    TComYuv*     pcPredYuv, 
-                                    TComYuv*     pcResiYuv, 
-                                    UInt&        ruiDist,
-                                    UInt         uiChromaId,
-                                    Int          default0Save1Load2 = 0 );
-
-  Void  xRecurIntraCodingQT       ( TComDataCU*  pcCU, 
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx, 
-                                    Bool         bLumaOnly,
-                                    TComYuv*     pcOrgYuv, 
-                                    TComYuv*     pcPredYuv, 
-                                    TComYuv*     pcResiYuv, 
-#if H_3D_VSO
+                                   );
+
+  Void  xRecurIntraCodingLumaQT   ( TComYuv*    pcOrgYuv,
+                                    TComYuv*    pcPredYuv,
+                                    TComYuv*    pcResiYuv,
+                                    Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+#if NH_3D_VSO
                                     Dist&        ruiDistY,
 #else
-                                    UInt&        ruiDistY,
-#endif
-                                    UInt&        ruiDistC,
+                                    Distortion& ruiDistY,
+#endif
 #if HHI_RQT_INTRA_SPEEDUP
-                                   Bool         bCheckFirst,
-#endif
-                                   Double&      dRDCost
+                                    Bool         bCheckFirst,
+#endif
+                                    Double&      dRDCost,
 #if H_3D_DIM_ENC
                                    , Bool          zeroResi = false
 #endif
-                                   );
-  
-  Void  xSetIntraResultQT         ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    Bool         bLumaOnly,
-                                    TComYuv*     pcRecoYuv );
-  
-  Void  xRecurIntraChromaCodingQT ( TComDataCU*  pcCU, 
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx, 
-                                    TComYuv*     pcOrgYuv, 
-                                    TComYuv*     pcPredYuv, 
-                                    TComYuv*     pcResiYuv, 
-                                    UInt&        ruiDist );
-  Void  xSetIntraResultChromaQT   ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    TComYuv*     pcRecoYuv );
-  
-  Void  xStoreIntraResultQT       ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    Bool         bLumaOnly );
-  Void  xLoadIntraResultQT        ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    Bool         bLumaOnly );
-  Void xStoreIntraResultChromaQT  ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    UInt         stateU0V1Both2 );
-  Void xLoadIntraResultChromaQT   ( TComDataCU*  pcCU,
-                                    UInt         uiTrDepth,
-                                    UInt         uiAbsPartIdx,
-                                    UInt         stateU0V1Both2 );
-
+                                    TComTU      &rTu
+                                    DEBUG_STRING_FN_DECLARE(sDebug));
+
+  Void  xSetIntraResultLumaQT     ( TComYuv*     pcRecoYuv,
+                                    TComTU &rTu);
+
+  Void xStoreCrossComponentPredictionResult  (       Pel    *pResiLuma,
+                                               const Pel    *pBestLuma,
+                                                     TComTU &rTu,
+                                               const Int     xOffset,
+                                               const Int     yOffset,
+                                               const Int     strideResi,
+                                               const Int     strideBest );
+
+  Char xCalcCrossComponentPredictionAlpha    (       TComTU &rTu,
+                                               const ComponentID compID,
+                                               const Pel*        piResiL,
+                                               const Pel*        piResiC,
+                                               const Int         width,
+                                               const Int         height,
+                                               const Int         strideL,
+                                               const Int         strideC );
+
+  Void  xRecurIntraChromaCodingQT ( TComYuv*    pcOrgYuv,
+                                    TComYuv*    pcPredYuv,
+                                    TComYuv*    pcResiYuv,
+                                    Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+#if NH_3D_VSO
+                                    Dist&       ruiDist,
+#else
+                                    Distortion& ruiDist,
+#endif
+                                    TComTU      &rTu
+                                    DEBUG_STRING_FN_DECLARE(sDebug));
+
+  Void  xSetIntraResultChromaQT   ( TComYuv*    pcRecoYuv, TComTU &rTu);
+
+  Void  xStoreIntraResultQT       ( const ComponentID compID, TComTU &rTu);
+  Void  xLoadIntraResultQT        ( const ComponentID compID, TComTU &rTu);
 #if H_3D
   Void xIntraCodingDIS           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, UInt uiPredMode );
@@ -371,8 +359,9 @@
 #endif
 
+
   // -------------------------------------------------------------------------------------------------------------------
   // Inter search (AMP)
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   Void xEstimateMvPredAMVP        ( TComDataCU* pcCU,
                                     TComYuv*    pcOrgYuv,
@@ -382,10 +371,7 @@
                                     TComMv&     rcMvPred,
                                     Bool        bFilled = false
-                                  , UInt*       puiDistBiP = NULL
-                                  #if ZERO_MVD_EST
-                                  , UInt*       puiDist = NULL
-                                  #endif
+                                  , Distortion* puiDistBiP = NULL
                                      );
-  
+
   Void xCheckBestMVP              ( TComDataCU* pcCU,
                                     RefPicList  eRefPicList,
@@ -394,8 +380,7 @@
                                     Int&        riMVPIdx,
                                     UInt&       ruiBits,
-                                    UInt&       ruiCost );
-  
-  UInt xGetTemplateCost           ( TComDataCU* pcCU,
-                                    UInt        uiPartIdx,
+                                    Distortion& ruiCost );
+
+  Distortion xGetTemplateCost    ( TComDataCU*  pcCU,
                                     UInt        uiPartAddr,
                                     TComYuv*    pcOrgYuv,
@@ -408,23 +393,20 @@
                                     Int         iSizeX,
                                     Int         iSizeY
-                                  #if ZERO_MVD_EST
-                                  , UInt&       ruiDist
-                                  #endif
                                    );
-  
-  
+
+
   Void xCopyAMVPInfo              ( AMVPInfo*   pSrc, AMVPInfo* pDst );
   UInt xGetMvpIdxBits             ( Int iIdx, Int iNum );
   Void xGetBlkBits                ( PartSize  eCUMode, Bool bPSlice, Int iPartIdx,  UInt uiLastMode, UInt uiBlkBit[3]);
-  
-  Void xMergeEstimation           ( TComDataCU*     pcCU,
-                                    TComYuv*        pcYuvOrg,
-                                    Int             iPartIdx,
-                                    UInt&           uiInterDir,
-                                    TComMvField*    pacMvField,
-                                    UInt&           uiMergeIndex,
-                                    UInt&           ruiCost
-                                  , TComMvField* cMvFieldNeighbours,  
-                                    UChar* uhInterDirNeighbours
+
+  Void xMergeEstimation           ( TComDataCU*  pcCU,
+                                    TComYuv*     pcYuvOrg,
+                                    Int          iPartIdx,
+                                    UInt&        uiInterDir,
+                                    TComMvField* pacMvField,
+                                    UInt&        uiMergeIndex,
+                                    Distortion&  ruiCost,
+                                    TComMvField* cMvFieldNeighbours,
+                                    UChar*       uhInterDirNeighbours,
 #if H_3D_VSP
                                   , Int* vspFlag
@@ -433,114 +415,115 @@
                                   , Bool* pbSPIVMPFlag, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
 #endif
-                                  , Int& numValidMergeCand
+                                    Int&         numValidMergeCand
                                    );
 
   Void xRestrictBipredMergeCand   ( TComDataCU*     pcCU,
                                     UInt            puIdx,
-                                    TComMvField*    mvFieldNeighbours, 
-                                    UChar*          interDirNeighbours, 
+                                    TComMvField*    mvFieldNeighbours,
+                                    UChar*          interDirNeighbours,
                                     Int             numValidMergeCand );
 
+
   // -------------------------------------------------------------------------------------------------------------------
   // motion estimation
   // -------------------------------------------------------------------------------------------------------------------
-  
-  Void xMotionEstimation          ( TComDataCU*   pcCU,
-                                    TComYuv*      pcYuvOrg,
-                                    Int           iPartIdx,
-                                    RefPicList    eRefPicList,
-                                    TComMv*       pcMvPred,
-                                    Int           iRefIdxPred,
-                                    TComMv&       rcMv,
-                                    UInt&         ruiBits,
-                                    UInt&         ruiCost,
-                                    Bool          bBi = false  );
-  
-  Void xTZSearch                  ( TComDataCU*   pcCU,
-                                    TComPattern*  pcPatternKey,
-                                    Pel*          piRefY,
-                                    Int           iRefStride,
-                                    TComMv*       pcMvSrchRngLT,
-                                    TComMv*       pcMvSrchRngRB,
-                                    TComMv&       rcMv,
-                                    UInt&         ruiSAD );
-  
-#if H_MV
-  Void xSetSearchRange           (  TComDataCU* pcCU, 
-                                    TComMv& cMvPred, 
-                                    Int iSrchRng, 
-                                    TComMv& rcMvSrchRngLT, 
-                                    TComMv& rcMvSrchRngRB, 
-                                    Bool bMv_VRng_Restricted, 
-                                    Int iVerDispSrchRng );
+
+  Void xMotionEstimation          ( TComDataCU*  pcCU,
+                                    TComYuv*     pcYuvOrg,
+                                    Int          iPartIdx,
+                                    RefPicList   eRefPicList,
+                                    TComMv*      pcMvPred,
+                                    Int          iRefIdxPred,
+                                    TComMv&      rcMv,
+                                    UInt&        ruiBits,
+                                    Distortion&  ruiCost,
+                                    Bool         bBi = false  );
+
+  Void xTZSearch                  ( TComDataCU*  pcCU,
+                                    TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvSrchRngLT,
+                                    TComMv*      pcMvSrchRngRB,
+                                    TComMv&      rcMv,
+                                    Distortion&  ruiSAD,
+                                    const TComMv *pIntegerMv2Nx2NPred
+                                    );
+
+  Void xTZSearchSelective         ( TComDataCU*  pcCU,
+                                    TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvSrchRngLT,
+                                    TComMv*      pcMvSrchRngRB,
+                                    TComMv&      rcMv,
+                                    Distortion&  ruiSAD,
+                                    const TComMv *pIntegerMv2Nx2NPred
+                                    );
+
+  Void xSetSearchRange            ( TComDataCU*  pcCU,
+                                    TComMv&      cMvPred,
+                                    Int          iSrchRng,
+                                    TComMv&      rcMvSrchRngLT,
+                                    TComMv&      rcMvSrchRngRB );
+
+  Void xPatternSearchFast         ( TComDataCU*  pcCU,
+                                    TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvSrchRngLT,
+                                    TComMv*      pcMvSrchRngRB,
+                                    TComMv&      rcMv,
+                                    Distortion&  ruiSAD,
+                                    const TComMv* pIntegerMv2Nx2NPred
+                                  );
+
+  Void xPatternSearch             ( TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvSrchRngLT,
+                                    TComMv*      pcMvSrchRngRB,
+                                    TComMv&      rcMv,
+                                    Distortion&  ruiSAD );
+
+  Void xPatternSearchFracDIF      (
+                                    Bool         bIsLosslessCoded,
+                                    TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvInt,
+                                    TComMv&      rcMvHalf,
+                                    TComMv&      rcMvQter,
+                                    Distortion&  ruiCost
+                                   );
+
+  Void xExtDIFUpSamplingH( TComPattern* pcPattern );
+  Void xExtDIFUpSamplingQ( TComPattern* pcPatternKey, TComMv halfPelRef );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // T & Q & Q-1 & T-1
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Void xEncodeInterResidualQT( const ComponentID compID, TComTU &rTu );
+#if NH_3D_VSO // M26
+  Void xEstimateInterResidualQT( TComYuv* pcResi, TComYuv* pcOrg, TComYuv* pcPred,  Double &rdCost, UInt &ruiBits, Dist       &ruiDist, Dist       *puiZeroDist, TComTU &rTu DEBUG_STRING_FN_DECLARE(sDebug) );
 #else
-  Void xSetSearchRange            ( TComDataCU*   pcCU,
-                                    TComMv&       cMvPred,
-                                    Int           iSrchRng,
-                                    TComMv&       rcMvSrchRngLT,
-                                    TComMv&       rcMvSrchRngRB );
-#endif
-  
-  Void xPatternSearchFast         ( TComDataCU*   pcCU,
-                                    TComPattern*  pcPatternKey,
-                                    Pel*          piRefY,
-                                    Int           iRefStride,
-                                    TComMv*       pcMvSrchRngLT,
-                                    TComMv*       pcMvSrchRngRB,
-                                    TComMv&       rcMv,
-                                    UInt&         ruiSAD );
-  
-  Void xPatternSearch             ( TComPattern*  pcPatternKey,
-                                    Pel*          piRefY,
-                                    Int           iRefStride,
-                                    TComMv*       pcMvSrchRngLT,
-                                    TComMv*       pcMvSrchRngRB,
-                                    TComMv&       rcMv,
-                                    UInt&         ruiSAD );
-  
-  Void xPatternSearchFracDIF      ( TComDataCU*   pcCU,
-                                    TComPattern*  pcPatternKey,
-                                    Pel*          piRefY,
-                                    Int           iRefStride,
-                                    TComMv*       pcMvInt,
-                                    TComMv&       rcMvHalf,
-                                    TComMv&       rcMvQter,
-                                    UInt&         ruiCost 
-                                   ,Bool biPred
-                                   );
-  
-  Void xExtDIFUpSamplingH( TComPattern* pcPattern, Bool biPred  );
-  Void xExtDIFUpSamplingQ( TComPattern* pcPatternKey, TComMv halfPelRef, Bool biPred );
-  
-  // -------------------------------------------------------------------------------------------------------------------
-  // T & Q & Q-1 & T-1
-  // -------------------------------------------------------------------------------------------------------------------
-  
-  Void xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType );
-#if H_3D_VSO // M26
-  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx,TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, Dist &ruiDist, Dist *puiZeroDist );
-#else
-  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx,TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist );
-#endif
-  Void xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx,UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial );
-  
-  UInt  xModeBitsIntra ( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth );
+  Void xEstimateInterResidualQT( TComYuv* pcResi                                  , Double &rdCost, UInt &ruiBits, Distortion &ruiDist, Distortion *puiZeroDist, TComTU &rTu DEBUG_STRING_FN_DECLARE(sDebug) );
+#endif
+  Void xSetInterResidualQTData( TComYuv* pcResi, Bool bSpatial, TComTU &rTu  );
+
+  UInt  xModeBitsIntra ( TComDataCU* pcCU, UInt uiMode, UInt uiPartOffset, UInt uiDepth, const ChannelType compID );
   UInt  xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList );
-  
+
   // -------------------------------------------------------------------------------------------------------------------
   // compute symbol bits
   // -------------------------------------------------------------------------------------------------------------------
-  
-  Void xAddSymbolBitsInter        ( TComDataCU*   pcCU,
-                                   UInt          uiQp,
-                                   UInt          uiTrMode,
-                                   UInt&         ruiBits,
-                                   TComYuv*&     rpcYuvRec,
-                                   TComYuv*      pcYuvPred,
-                                   TComYuv*&     rpcYuvResi );
-  
+
+  Void xAddSymbolBitsInter       ( TComDataCU*   pcCU,
+                                   UInt&         ruiBits);
+
   Void  setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur );
-  inline  Void  setDistParamComp( UInt uiComp )  { m_cDistParam.uiComp = uiComp; }
-  
+  inline  Void  setDistParamComp( ComponentID compIdx )  { m_cDistParam.compIdx = compIdx; }
+
 };// END CLASS DEFINITION TEncSearch
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,38 +46,20 @@
 // Constructor / destructor / create / destroy
 // ====================================================================================================================
-
 TEncSlice::TEncSlice()
+ : m_encCABACTableIdx(I_SLICE)
 {
   m_apcPicYuvPred = NULL;
   m_apcPicYuvResi = NULL;
-  
+
   m_pdRdPicLambda = NULL;
   m_pdRdPicQp     = NULL;
   m_piRdPicQp     = NULL;
-  m_pcBufferSbacCoders    = NULL;
-  m_pcBufferBinCoderCABACs  = NULL;
-  m_pcBufferLowLatSbacCoders    = NULL;
-  m_pcBufferLowLatBinCoderCABACs  = NULL;
 }
 
 TEncSlice::~TEncSlice()
 {
-  for (std::vector<TEncSbac*>::iterator i = CTXMem.begin(); i != CTXMem.end(); i++)
-  {
-    delete (*i);
-  }
-}
-
-Void TEncSlice::initCtxMem(  UInt i )                
-{   
-  for (std::vector<TEncSbac*>::iterator j = CTXMem.begin(); j != CTXMem.end(); j++)
-  {
-    delete (*j);
-  }
-  CTXMem.clear(); 
-  CTXMem.resize(i); 
-}
-
-Void TEncSlice::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth )
+}
+
+Void TEncSlice::create( Int iWidth, Int iHeight, ChromaFormat chromaFormat, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth )
 {
   // create prediction picture
@@ -85,12 +67,12 @@
   {
     m_apcPicYuvPred  = new TComPicYuv;
-    m_apcPicYuvPred->create( iWidth, iHeight, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
-  }
-  
+    m_apcPicYuvPred->create( iWidth, iHeight, chromaFormat, iMaxCUWidth, iMaxCUHeight, uhTotalDepth, true );
+  }
+
   // create residual picture
   if( m_apcPicYuvResi == NULL )
   {
     m_apcPicYuvResi  = new TComPicYuv;
-    m_apcPicYuvResi->create( iWidth, iHeight, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
+    m_apcPicYuvResi->create( iWidth, iHeight, chromaFormat, iMaxCUWidth, iMaxCUHeight, uhTotalDepth, true );
   }
 }
@@ -105,5 +87,5 @@
     m_apcPicYuvPred  = NULL;
   }
-  
+
   // destroy residual picture
   if ( m_apcPicYuvResi )
@@ -113,22 +95,21 @@
     m_apcPicYuvResi  = NULL;
   }
-  
+
   // free lambda and QP arrays
-  if ( m_pdRdPicLambda ) { xFree( m_pdRdPicLambda ); m_pdRdPicLambda = NULL; }
-  if ( m_pdRdPicQp     ) { xFree( m_pdRdPicQp     ); m_pdRdPicQp     = NULL; }
-  if ( m_piRdPicQp     ) { xFree( m_piRdPicQp     ); m_piRdPicQp     = NULL; }
-
-  if ( m_pcBufferSbacCoders )
-  {
-    delete[] m_pcBufferSbacCoders;
-  }
-  if ( m_pcBufferBinCoderCABACs )
-  {
-    delete[] m_pcBufferBinCoderCABACs;
-  }
-  if ( m_pcBufferLowLatSbacCoders )
-    delete[] m_pcBufferLowLatSbacCoders;
-  if ( m_pcBufferLowLatBinCoderCABACs )
-    delete[] m_pcBufferLowLatBinCoderCABACs;
+  if ( m_pdRdPicLambda )
+  {
+    xFree( m_pdRdPicLambda );
+    m_pdRdPicLambda = NULL;
+  }
+  if ( m_pdRdPicQp )
+  {
+    xFree( m_pdRdPicQp );
+    m_pdRdPicQp = NULL;
+  }
+  if ( m_piRdPicQp )
+  {
+    xFree( m_piRdPicQp );
+    m_piRdPicQp = NULL;
+  }
 }
 
@@ -137,20 +118,18 @@
   m_pcCfg             = pcEncTop;
   m_pcListPic         = pcEncTop->getListPic();
-  
+
   m_pcGOPEncoder      = pcEncTop->getGOPEncoder();
   m_pcCuEncoder       = pcEncTop->getCuEncoder();
   m_pcPredSearch      = pcEncTop->getPredSearch();
-  
+
   m_pcEntropyCoder    = pcEncTop->getEntropyCoder();
-  m_pcCavlcCoder      = pcEncTop->getCavlcCoder();
   m_pcSbacCoder       = pcEncTop->getSbacCoder();
   m_pcBinCABAC        = pcEncTop->getBinCABAC();
   m_pcTrQuant         = pcEncTop->getTrQuant();
-  
-  m_pcBitCounter      = pcEncTop->getBitCounter();
+
   m_pcRdCost          = pcEncTop->getRdCost();
   m_pppcRDSbacCoder   = pcEncTop->getRDSbacCoder();
   m_pcRDGoOnSbacCoder = pcEncTop->getRDGoOnSbacCoder();
-  
+
   // create lambda and QP arrays
   m_pdRdPicLambda     = (Double*)xMalloc( Double, m_pcCfg->getDeltaQpRD() * 2 + 1 );
@@ -169,5 +148,40 @@
   m_pcRateCtrl        = pcEncTop->getRateCtrl();
 #endif
-}
+
+}
+
+
+
+Void
+TEncSlice::setUpLambda(TComSlice* slice, const Double dLambda, Int iQP)
+{
+  // store lambda
+  m_pcRdCost ->setLambda( dLambda, slice->getSPS()->getBitDepths() );
+
+  // for RDO
+  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+  Double dLambdas[MAX_NUM_COMPONENT] = { dLambda };
+  for(UInt compIdx=1; compIdx<MAX_NUM_COMPONENT; compIdx++)
+  {
+    const ComponentID compID=ComponentID(compIdx);
+    Int chromaQPOffset = slice->getPPS()->getQpOffset(compID) + slice->getSliceChromaQpDelta(compID);
+    Int qpc=(iQP + chromaQPOffset < 0) ? iQP : getScaledChromaQP(iQP + chromaQPOffset, m_pcCfg->getChromaFormatIdc());
+    Double tmpWeight = pow( 2.0, (iQP-qpc)/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setDistortionWeight(compID, tmpWeight);
+    dLambdas[compIdx]=dLambda/tmpWeight;
+  }
+
+#if RDOQ_CHROMA_LAMBDA
+// for RDOQ
+  m_pcTrQuant->setLambdas( dLambdas );
+#else
+  m_pcTrQuant->setLambda( dLambda );
+#endif
+
+// For SAO
+  slice   ->setLambdas( dLambdas );
+}
+
+
 
 /**
@@ -181,22 +195,21 @@
  \param pocCurr       current POC
  \param iNumPicRcvd   number of received pictures
- \param iTimeOffset   POC offset for hierarchical structure
- \param iDepth        temporal layer depth
+ \param iGOPid        POC offset for hierarchical structure
  \param rpcSlice      slice header class
- \param pSPS          SPS associated with the slice
- \param pPPS          PPS associated with the slice
+ \param isField       true for field coding
  */
-#if H_MV
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId, bool isField )
-#else
-Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField )
+
+#if NH_MV
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, Int layerId, bool isField )
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iGOPid, TComSlice*& rpcSlice, Bool isField )
 #endif
 {
   Double dQP;
   Double dLambda;
-  
+
   rpcSlice = pcPic->getSlice(0);
 
-#if H_MV
+#if NH_MV
   rpcSlice->setVPS( pVPS ); 
 
@@ -204,10 +217,8 @@
   rpcSlice->setViewId      ( pVPS->getViewId      ( layerId ) );    
   rpcSlice->setViewIndex   ( pVPS->getViewIndex   ( layerId ) );
-#if H_3D
+#if NH_3D
   rpcSlice->setIsDepth     ( pVPS->getDepthId     ( layerId ) != 0 );    
 #endif
 #endif
-  rpcSlice->setSPS( pSPS );
-  rpcSlice->setPPS( pPPS );
   rpcSlice->setSliceBits(0);
   rpcSlice->setPic( pcPic );
@@ -221,17 +232,14 @@
   Int depth;
   {
-#if FIX_FIELD_DEPTH    
+
     Int poc = rpcSlice->getPOC();
     if(isField)
     {
-      poc = (poc/2)%(m_pcCfg->getGOPSize()/2);
+      poc = (poc/2) % (m_pcCfg->getGOPSize()/2);
     }
     else
     {
-      poc = poc%m_pcCfg->getGOPSize();   
-    }
-#else
-    Int poc = rpcSlice->getPOC()%m_pcCfg->getGOPSize();
-#endif
+      poc = poc % m_pcCfg->getGOPSize();   
+    }
     if ( poc == 0 )
     {
@@ -256,21 +264,16 @@
       }
     }
-#if FIX_FIELD_DEPTH  
-#if HARMONIZE_GOP_FIRST_FIELD_COUPLE
-    if(poc != 0)
-    {
-#endif
-    if(isField && rpcSlice->getPOC()%2 == 1)
-    {
-      depth ++;
-    }
-#if HARMONIZE_GOP_FIRST_FIELD_COUPLE
-  }
-#endif
-#endif
-  }
-  
+
+    if(m_pcCfg->getHarmonizeGopFirstFieldCoupleEnabled() && poc != 0)
+    {
+      if (isField && ((rpcSlice->getPOC() % 2) == 1))
+      {
+        depth ++;
+      }
+    }
+  }
+
   // slice type
-#if H_MV
+#if NH_MV
   SliceType eSliceTypeBaseView;
   if( pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0 )
@@ -289,27 +292,18 @@
 #else
   SliceType eSliceType;
-  
+
   eSliceType=B_SLICE;
-#if EFFICIENT_FIELD_IRAP
-  if(!(isField && pocLast == 1))
-  {
-#endif // EFFICIENT_FIELD_IRAP
-#if ALLOW_RECOVERY_POINT_AS_RAP
-  if(m_pcCfg->getDecodingRefreshType() == 3)
-  {
-    eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0             || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
-  }
-  else
-  {
-    eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
-  }
-#else
-  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
-#endif
-#if EFFICIENT_FIELD_IRAP
-  }
-#endif
-#endif
-  
+  if(!(isField && pocLast == 1) || !m_pcCfg->getEfficientFieldIRAPEnabled())
+  {
+    if(m_pcCfg->getDecodingRefreshType() == 3)
+    {
+      eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0             || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+    }
+    else
+    {
+      eSliceType = (pocLast == 0 || (pocCurr - (isField ? 1 : 0)) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+    }
+  }
+#endif
   rpcSlice->setSliceType    ( eSliceType );
 
@@ -317,5 +311,5 @@
   // Non-referenced frame marking
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   if(pocLast == 0)
   {
@@ -324,5 +318,5 @@
   else
   {
-#if 0 // Check this! H_MV
+#if 0 // Check this! NH_MV
     rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_refPic);
 #else
@@ -331,15 +325,15 @@
   }
   rpcSlice->setReferenced(true);
-  
+
   // ------------------------------------------------------------------------------------------------------------------
   // QP setting
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   dQP = m_pcCfg->getQP();
   if(eSliceType!=I_SLICE)
   {
-    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffsetY() ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
-    {
-#if H_MV
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA) ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
+    {
+#if NH_MV
       dQP += m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_QPOffset;
 #else
@@ -348,5 +342,5 @@
     }
   }
-  
+
   // modify QP
   Int* pdQPs = m_pcCfg->getdQPs();
@@ -355,8 +349,15 @@
     dQP += pdQPs[ rpcSlice->getPOC() ];
   }
+
+  if (m_pcCfg->getCostMode()==COST_LOSSLESS_CODING)
+  {
+    dQP=LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP;
+    m_pcCfg->setDeltaQpRD(0);
+  }
+
   // ------------------------------------------------------------------------------------------------------------------
   // Lambda computation
   // ------------------------------------------------------------------------------------------------------------------
-  
+
   Int iQP;
   Double dOrigQP = dQP;
@@ -367,11 +368,13 @@
     // compute QP value
     dQP = dOrigQP + ((iDQpIdx+1)>>1)*(iDQpIdx%2 ? -1 : 1);
-    
+
     // compute lambda value
     Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
     Int    SHIFT_QP = 12;
+
     Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
+
 #if FULL_NBIT
-    Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth - 8);
+    Int    bitdepth_luma_qp_scale = 6 * (rpcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8);
 #else
     Int    bitdepth_luma_qp_scale = 0;
@@ -382,5 +385,5 @@
 #endif
     // Case #1: I or P-slices (key-frame)
-#if H_MV
+#if NH_MV
     Double dQPFactor;
     if( eSliceType != I_SLICE ) 
@@ -406,5 +409,5 @@
 #endif
     }
-    
+
     // if hadamard is used in ME process
     if ( !m_pcCfg->getUseHADME() && rpcSlice->getSliceType( ) != I_SLICE )
@@ -412,6 +415,6 @@
       dLambda *= 0.95;
     }
-    
-    iQP = max( -pSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+
+    iQP = max( -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
 
     m_pdRdPicLambda[iDQpIdx] = dLambda;
@@ -419,13 +422,13 @@
     m_piRdPicQp    [iDQpIdx] = iQP;
   }
-  
+
   // obtain dQP = 0 case
   dLambda = m_pdRdPicLambda[0];
   dQP     = m_pdRdPicQp    [0];
   iQP     = m_piRdPicQp    [0];
-  
+
   if( rpcSlice->getSliceType( ) != I_SLICE )
   {
-#if H_MV
+#if NH_MV
     dLambda *= m_pcCfg->getLambdaModifier( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_temporalId );
 #else
@@ -434,8 +437,7 @@
   }
 
-  // store lambda
-  m_pcRdCost ->setLambda( dLambda );
-
-#if H_3D_VSO
+  setUpLambda(rpcSlice, dLambda, iQP);
+
+#if NH_3D_VSO
   m_pcRdCost->setUseLambdaScaleVSO  ( (m_pcCfg->getUseVSO() ||  m_pcCfg->getForceLambdaScaleVSO()) && m_pcCfg->getIsDepth() );
   m_pcRdCost->setLambdaVSO          ( dLambda * m_pcCfg->getLambdaScaleVSO() );
@@ -456,35 +458,8 @@
 #endif
 
-// for RDO
-  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight[2] = { 1.0, 1.0 };
-  Int qpc;
-  Int chromaQPOffset;
-
-  chromaQPOffset = rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb();
-  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight[0]);
-
-  chromaQPOffset = rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr();
-  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight[1]);
-
-  const Double lambdaArray[3] = {dLambda, (dLambda / weight[0]), (dLambda / weight[1])};
-
-#if RDOQ_CHROMA_LAMBDA 
-// for RDOQ
-  m_pcTrQuant->setLambdas( lambdaArray );
-#else
-  m_pcTrQuant->setLambda( dLambda );
-#endif
-
-// For SAO
-  rpcSlice->setLambdas( lambdaArray );
-  
-#if HB_LAMBDA_FOR_LDC
+  if (m_pcCfg->getFastMEForGenBLowDelayEnabled())
+  {
   // restore original slice type
-#if H_MV
+#if NH_MV
   eSliceType = eSliceTypeBaseView;
   if( eSliceTypeBaseView == I_SLICE && m_pcCfg->getGOPEntry(MAX_GOP).m_POC == 0 && m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType != 'I' )
@@ -493,43 +468,36 @@
   }
 #else
-#if EFFICIENT_FIELD_IRAP
-  if(!(isField && pocLast == 1))
-  {
-#endif // EFFICIENT_FIELD_IRAP
-#if ALLOW_RECOVERY_POINT_AS_RAP
-  if(m_pcCfg->getDecodingRefreshType() == 3)
-  {
-    eSliceType = (pocLast == 0 || (pocCurr)           % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
-
-  }
-  else
-  {
-  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
-  }
-#else
-  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
-#endif
-#if EFFICIENT_FIELD_IRAP
-  }
-#endif // EFFICIENT_FIELD_IRAP
+    if(!(isField && pocLast == 1) || !m_pcCfg->getEfficientFieldIRAPEnabled())
+  {
+    if(m_pcCfg->getDecodingRefreshType() == 3)
+    {
+      eSliceType = (pocLast == 0 || (pocCurr)                     % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+    }
+    else
+    {
+      eSliceType = (pocLast == 0 || (pocCurr - (isField ? 1 : 0)) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+
+    }
+  }
 #endif
 
   rpcSlice->setSliceType        ( eSliceType );
-#endif
-  
+}
+
   if (m_pcCfg->getUseRecalculateQPAccordingToLambda())
   {
     dQP = xGetQPValueAccordingToLambda( dLambda );
-    iQP = max( -pSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );    
-  }
-
-  rpcSlice->setSliceQp          ( iQP );
+    iQP = max( -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+  }
+
+  rpcSlice->setSliceQp           ( iQP );
 #if ADAPTIVE_QP_SELECTION
-  rpcSlice->setSliceQpBase      ( iQP );
-#endif
-  rpcSlice->setSliceQpDelta     ( 0 );
-  rpcSlice->setSliceQpDeltaCb   ( 0 );
-  rpcSlice->setSliceQpDeltaCr   ( 0 );
-#if H_MV
+  rpcSlice->setSliceQpBase       ( iQP );
+#endif
+  rpcSlice->setSliceQpDelta      ( 0 );
+  rpcSlice->setSliceChromaQpDelta( COMPONENT_Cb, 0 );
+  rpcSlice->setSliceChromaQpDelta( COMPONENT_Cr, 0 );
+  rpcSlice->setUseChromaQpAdj( rpcSlice->getPPS()->getPpsRangeExtension().getChromaQpOffsetListEnabledFlag() );
+#if NH_MV
   rpcSlice->setNumRefIdx(REF_PIC_LIST_0,m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_numRefPicsActive);
   rpcSlice->setNumRefIdx(REF_PIC_LIST_1,m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_numRefPicsActive);
@@ -545,23 +513,17 @@
     rpcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
     rpcSlice->setDeblockingFilterTcOffsetDiv2( 0 );
-  } else
-  if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
-  {
-    rpcSlice->getPPS()->setDeblockingFilterOverrideEnabledFlag( !m_pcCfg->getLoopFilterOffsetInPPS() );
-    rpcSlice->setDeblockingFilterOverrideFlag( !m_pcCfg->getLoopFilterOffsetInPPS() );
-    rpcSlice->getPPS()->setPicDisableDeblockingFilterFlag( m_pcCfg->getLoopFilterDisable() );
-    rpcSlice->setDeblockingFilterDisable( m_pcCfg->getLoopFilterDisable() );
+  }
+  else if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
+  {
+    rpcSlice->setDeblockingFilterOverrideFlag( rpcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() );
+    rpcSlice->setDeblockingFilterDisable( rpcSlice->getPPS()->getPicDisableDeblockingFilterFlag() );
     if ( !rpcSlice->getDeblockingFilterDisable())
     {
-      if ( !m_pcCfg->getLoopFilterOffsetInPPS() && eSliceType!=I_SLICE)
-      {
-#if H_MV
-        rpcSlice->getPPS()->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset() );
-        rpcSlice->getPPS()->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
+      if ( rpcSlice->getDeblockingFilterOverrideFlag() && eSliceType!=I_SLICE)
+      {
+#if NH_MV
         rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset()  );
         rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
 #else
-        rpcSlice->getPPS()->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset() );
-        rpcSlice->getPPS()->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
         rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset()  );
         rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
@@ -570,8 +532,6 @@
       else
       {
-      rpcSlice->getPPS()->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getLoopFilterBetaOffset() );
-      rpcSlice->getPPS()->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getLoopFilterTcOffset() );
-      rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getLoopFilterBetaOffset() );
-      rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getLoopFilterTcOffset() );
+        rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getLoopFilterBetaOffset() );
+        rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getLoopFilterTcOffset() );
       }
     }
@@ -586,6 +546,6 @@
 
   rpcSlice->setDepth            ( depth );
-  
-#if H_MV
+
+#if NH_MV
   pcPic->setTLayer( m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_temporalId );
 #else
@@ -600,5 +560,5 @@
   assert( m_apcPicYuvPred );
   assert( m_apcPicYuvResi );
-  
+
   pcPic->setPicYuvPred( m_apcPicYuvPred );
   pcPic->setPicYuvResi( m_apcPicYuvResi );
@@ -607,8 +567,8 @@
   rpcSlice->setSliceSegmentMode     ( m_pcCfg->getSliceSegmentMode()     );
   rpcSlice->setSliceSegmentArgument ( m_pcCfg->getSliceSegmentArgument() );
-#if !H_3D
+#if H_3D_IV_MERGE
+#else
   rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
 #endif
-  xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPred() );
 }
 
@@ -622,33 +582,7 @@
   slice->setSliceQpBase ( sliceQP );
 #endif
-  m_pcRdCost ->setLambda( lambda );
-  // for RDO
-  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Double weight[2] = { 1.0, 1.0 };
-  Int qpc;
-  Int chromaQPOffset;
-
-  chromaQPOffset = slice->getPPS()->getChromaCbQpOffset() + slice->getSliceQpDeltaCb();
-  qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
-  weight[0] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight[0]);
-
-  chromaQPOffset = slice->getPPS()->getChromaCrQpOffset() + slice->getSliceQpDeltaCr();
-  qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
-  weight[1] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight[1]);
-
-  const Double lambdaArray[3] = {lambda, (lambda / weight[0]), (lambda / weight[1])};
-
-#if RDOQ_CHROMA_LAMBDA 
-  // for RDOQ
-  m_pcTrQuant->setLambdas( lambdaArray );
-#else
-  m_pcTrQuant->setLambda( lambda );
-#endif
-
-  // For SAO
-  slice->setLambdas( lambdaArray );
-}
+  setUpLambda(slice, lambda, sliceQP);
+}
+
 // ====================================================================================================================
 // Public member functions
@@ -663,5 +597,5 @@
   Int iMaxSR = m_pcCfg->getSearchRange();
   Int iNumPredDir = pcSlice->isInterP() ? 1 : 2;
- 
+
   for (Int iDir = 0; iDir <= iNumPredDir; iDir++)
   {
@@ -678,9 +612,9 @@
 
 /**
- - multi-loop slice encoding for different slice QP
- .
- \param rpcPic    picture class
+ Multi-loop slice encoding for different slice QP
+
+ \param pcPic    picture class
  */
-Void TEncSlice::precompressSlice( TComPic*& rpcPic )
+Void TEncSlice::precompressSlice( TComPic* pcPic )
 {
   // if deltaQP RD is not used, simply return
@@ -694,17 +628,35 @@
     printf( "\nMultiple QP optimization is not allowed when rate control is enabled." );
     assert(0);
-  }
-  
-  TComSlice* pcSlice        = rpcPic->getSlice(getSliceIdx());
+    return;
+  }
+
+  TComSlice* pcSlice        = pcPic->getSlice(getSliceIdx());
+
+  if (pcSlice->getDependentSliceSegmentFlag())
+  {
+    // if this is a dependent slice segment, then it was optimised
+    // when analysing the entire slice.
+    return;
+  }
+
+  if (pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES)
+  {
+    // TODO: investigate use of average cost per CTU so that this Slice Mode can be used.
+    printf( "\nUnable to optimise Slice-level QP if Slice Mode is set to FIXED_NUMBER_OF_BYTES\n" );
+    assert(0);
+    return;
+  }
+
+
   Double     dPicRdCostBest = MAX_DOUBLE;
   UInt       uiQpIdxBest = 0;
-  
+
   Double dFrameLambda;
 #if FULL_NBIT
-  Int    SHIFT_QP = 12 + 6 * (g_bitDepth - 8);
+  Int    SHIFT_QP = 12 + 6 * (pcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8);
 #else
   Int    SHIFT_QP = 12;
 #endif
-  
+
   // set frame lambda
   if (m_pcCfg->getGOPSize() > 1)
@@ -717,5 +669,5 @@
   }
   m_pcRdCost      ->setFrameLambda(dFrameLambda);
-  
+
   // for each QP candidate
   for ( UInt uiQpIdx = 0; uiQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; uiQpIdx++ )
@@ -725,51 +677,28 @@
     pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdx] );
 #endif
-    m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
-    // for RDO
-    // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-    Int iQP = m_piRdPicQp    [uiQpIdx];
-    Double weight[2] = { 1.0, 1.0 };
-    Int qpc;
-    Int chromaQPOffset;
-
-    chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
-    qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-    weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-    m_pcRdCost->setCbDistortionWeight(weight[0]);
-
-    chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
-    qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-    weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-    m_pcRdCost->setCrDistortionWeight(weight[1]);
-
-    const Double lambdaArray[3] = {m_pdRdPicLambda[uiQpIdx], (m_pdRdPicLambda[uiQpIdx] / weight[0]), (m_pdRdPicLambda[uiQpIdx] / weight[1])};
-#if RDOQ_CHROMA_LAMBDA 
-    // for RDOQ
-    m_pcTrQuant->setLambdas( lambdaArray );
-#else
-    m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
-#endif
-    // For SAO
-    pcSlice->setLambdas( lambdaArray );
-    
+    setUpLambda(pcSlice, m_pdRdPicLambda[uiQpIdx], m_piRdPicQp    [uiQpIdx]);
+
     // try compress
-    compressSlice   ( rpcPic );
-    
-    Double dPicRdCost;
-#if H_3D_VSO
+    compressSlice   ( pcPic, true );
+
+#if NH_3D_VSO
     Dist64 uiPicDist        = m_uiPicDist;
 #else
-    UInt64 uiPicDist        = m_uiPicDist;
-#endif
-    UInt64 uiALFBits        = 0;
-    
-    m_pcGOPEncoder->preLoopFilterPicAll( rpcPic, uiPicDist, uiALFBits );
-    
+    UInt64 uiPicDist        = m_uiPicDist; // Distortion, as calculated by compressSlice.
+    // NOTE: This distortion is the chroma-weighted SSE distortion for the slice.
+    //       Previously a standard SSE distortion was calculated (for the entire frame).
+    //       Which is correct?
+
+    // TODO: Update loop filter, SAO and distortion calculation to work on one slice only.
+    // m_pcGOPEncoder->preLoopFilterPicAll( pcPic, uiPicDist );
+
+#endif
+
     // compute RD cost and choose the best
-    dPicRdCost = m_pcRdCost->calcRdCost64( m_uiPicTotalBits + uiALFBits, uiPicDist, true, DF_SSE_FRAME);
+    Double dPicRdCost = m_pcRdCost->calcRdCost64( m_uiPicTotalBits, uiPicDist, true, DF_SSE_FRAME); // NOTE: Is the 'true' parameter really necessary?
 #if H_3D
     // Above calculation need to be fixed for VSO, including frameLambda value. 
 #endif
-    
+
     if ( dPicRdCost < dPicRdCostBest )
     {
@@ -778,5 +707,5 @@
     }
   }
-  
+
   // set best values
   pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdxBest] );
@@ -784,92 +713,73 @@
   pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdxBest] );
 #endif
-  m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
-  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
-  Int iQP = m_piRdPicQp    [uiQpIdxBest];
-  Double weight[2] = { 1.0, 1.0 };
-  Int qpc;
-  Int chromaQPOffset;
-
-  chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
-  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCbDistortionWeight(weight[0]);
-
-  chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
-  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
-  weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
-  m_pcRdCost->setCrDistortionWeight(weight[1]);
-
-  const Double lambdaArray[3] = {m_pdRdPicLambda[uiQpIdxBest], (m_pdRdPicLambda[uiQpIdxBest] / weight[0]), (m_pdRdPicLambda[uiQpIdxBest] / weight[1])};
-#if RDOQ_CHROMA_LAMBDA 
-  // for RDOQ 
-  m_pcTrQuant->setLambdas( lambdaArray );
-#else
-  m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
-#endif
-  // For SAO
-  pcSlice->setLambdas( lambdaArray );
-}
-
-/** \param rpcPic   picture class
+  setUpLambda(pcSlice, m_pdRdPicLambda[uiQpIdxBest], m_piRdPicQp    [uiQpIdxBest]);
+}
+
+Void TEncSlice::calCostSliceI(TComPic* pcPic) // TODO: this only analyses the first slice segment. What about the others?
+{
+  Double            iSumHadSlice      = 0;
+  TComSlice * const pcSlice           = pcPic->getSlice(getSliceIdx());
+  const TComSPS    &sps               = *(pcSlice->getSPS());
+  const Int         shift             = sps.getBitDepth(CHANNEL_TYPE_LUMA)-8;
+  const Int         offset            = (shift>0)?(1<<(shift-1)):0;
+
+  pcSlice->setSliceSegmentBits(0);
+
+  UInt startCtuTsAddr, boundingCtuTsAddr;
+  xDetermineStartAndBoundingCtuTsAddr ( startCtuTsAddr, boundingCtuTsAddr, pcPic );
+
+  for( UInt ctuTsAddr = startCtuTsAddr, ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap( startCtuTsAddr);
+       ctuTsAddr < boundingCtuTsAddr;
+       ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap(++ctuTsAddr) )
+  {
+    // initialize CU encoder
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+    pCtu->initCtu( pcPic, ctuRsAddr );
+
+    Int height  = min( sps.getMaxCUHeight(),sps.getPicHeightInLumaSamples() - ctuRsAddr / pcPic->getFrameWidthInCtus() * sps.getMaxCUHeight() );
+    Int width   = min( sps.getMaxCUWidth(), sps.getPicWidthInLumaSamples()  - ctuRsAddr % pcPic->getFrameWidthInCtus() * sps.getMaxCUWidth() );
+
+    Int iSumHad = m_pcCuEncoder->updateCtuDataISlice(pCtu, width, height);
+
+    (m_pcRateCtrl->getRCPic()->getLCU(ctuRsAddr)).m_costIntra=(iSumHad+offset)>>shift;
+    iSumHadSlice += (m_pcRateCtrl->getRCPic()->getLCU(ctuRsAddr)).m_costIntra;
+
+  }
+  m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
+}
+
+/** \param pcPic   picture class
  */
-Void TEncSlice::calCostSliceI(TComPic*& rpcPic)
-{
-  UInt    uiCUAddr;
-  UInt    uiStartCUAddr;
-  UInt    uiBoundingCUAddr;
-  Int     iSumHad, shift = g_bitDepthY-8, offset = (shift>0)?(1<<(shift-1)):0;;
-  Double  iSumHadSlice = 0;
-
-  rpcPic->getSlice(getSliceIdx())->setSliceSegmentBits(0);
-  TComSlice* pcSlice            = rpcPic->getSlice(getSliceIdx());
-  xDetermineStartAndBoundingCUAddr ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, false );
-
-  UInt uiEncCUOrder;
-  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU()); 
-  for( uiEncCUOrder = uiStartCUAddr/rpcPic->getNumPartInCU();
-       uiEncCUOrder < (uiBoundingCUAddr+(rpcPic->getNumPartInCU()-1))/rpcPic->getNumPartInCU();
-       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
-  {
-    // initialize CU encoder
-    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
-    pcCU->initCU( rpcPic, uiCUAddr );
-
-    Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
-    Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
-
-    iSumHad = m_pcCuEncoder->updateLCUDataISlice(pcCU, uiCUAddr, width, height);
-
-    (m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr)).m_costIntra=(iSumHad+offset)>>shift;
-    iSumHadSlice += (m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr)).m_costIntra;
-
-  }
-  m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
-}
-
-Void TEncSlice::compressSlice( TComPic*& rpcPic )
-{
-  UInt  uiCUAddr;
-  UInt   uiStartCUAddr;
-  UInt   uiBoundingCUAddr;
-  rpcPic->getSlice(getSliceIdx())->setSliceSegmentBits(0);
-  TEncBinCABAC* pppcRDSbacCoder = NULL;
-  TComSlice* pcSlice            = rpcPic->getSlice(getSliceIdx());
-  xDetermineStartAndBoundingCUAddr ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, false );
-  
-  // initialize cost values
+Void TEncSlice::compressSlice( TComPic* pcPic, const Bool bCompressEntireSlice )
+{
+  // if bCompressEntireSlice is true, then the entire slice (not slice segment) is compressed,
+  //   effectively disabling the slice-segment-mode.
+
+  UInt   startCtuTsAddr;
+  UInt   boundingCtuTsAddr;
+  TComSlice* const pcSlice            = pcPic->getSlice(getSliceIdx());
+  pcSlice->setSliceSegmentBits(0);
+  xDetermineStartAndBoundingCtuTsAddr ( startCtuTsAddr, boundingCtuTsAddr, pcPic );
+  if (bCompressEntireSlice)
+  {
+    boundingCtuTsAddr = pcSlice->getSliceCurEndCtuTsAddr();
+    pcSlice->setSliceSegmentCurEndCtuTsAddr(boundingCtuTsAddr);
+  }
+
+  // initialize cost values - these are used by precompressSlice (they should be parameters).
   m_uiPicTotalBits  = 0;
-  m_dPicRdCost      = 0;
+  m_dPicRdCost      = 0; // NOTE: This is a write-only variable!
   m_uiPicDist       = 0;
-  
-  // set entropy coder
-    m_pcSbacCoder->init( m_pcBinCABAC );
-    m_pcEntropyCoder->setEntropyCoder   ( m_pcSbacCoder, pcSlice );
-    m_pcEntropyCoder->resetEntropy      ();
-    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load(m_pcSbacCoder);
-    pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
-    pppcRDSbacCoder->setBinCountingEnableFlag( false );
-    pppcRDSbacCoder->setBinsCoded( 0 );
-  
+
+  m_pcEntropyCoder->setEntropyCoder   ( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
+  m_pcEntropyCoder->resetEntropy      ( pcSlice );
+
+  TEncBinCABAC* pRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+  pRDSbacCoder->setBinCountingEnableFlag( false );
+  pRDSbacCoder->setBinsCoded( 0 );
+
+  TComBitCounter  tempBitCounter;
+  const UInt      frameWidthInCtus = pcPic->getPicSym()->getFrameWidthInCtus();
+
   //------------------------------------------------------------------------------
   //  Weighted Prediction parameters estimation.
@@ -881,5 +791,5 @@
   }
 
-  Bool bWp_explicit = (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred());
+  const Bool bWp_explicit = (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred());
 
   if ( bWp_explicit )
@@ -888,5 +798,5 @@
     //  Weighted Prediction implemented at Slice level. SliceMode=2 is not supported yet.
     //------------------------------------------------------------------------------
-    if ( pcSlice->getSliceMode()==2 || pcSlice->getSliceSegmentMode()==2 )
+    if ( pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES || pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES )
     {
       printf("Weighted Prediction is not supported with slice mode determined by max number of bins.\n"); exit(0);
@@ -894,5 +804,5 @@
 
     xEstimateWPParamSlice( pcSlice );
-    pcSlice->initWpScaling();
+    pcSlice->initWpScaling(pcSlice->getSPS());
 
     // check WP on/off
@@ -901,7 +811,8 @@
 
 #if ADAPTIVE_QP_SELECTION
-  if( m_pcCfg->getUseAdaptQpSelect() )
-  {
-    m_pcTrQuant->clearSliceARLCnt();
+  if( m_pcCfg->getUseAdaptQpSelect() && !(pcSlice->getDependentSliceSegmentFlag()))
+  {
+    // TODO: this won't work with dependent slices: they do not have their own QP. Check fix to mask clause execution with && !(pcSlice->getDependentSliceSegmentFlag())
+    m_pcTrQuant->clearSliceARLCnt(); // TODO: this looks wrong for multiple slices - the results of all but the last slice will be cleared before they are used (all slices compressed, and then all slices encoded)
     if(pcSlice->getSliceType()!=I_SLICE)
     {
@@ -911,9 +822,5 @@
   }
 #endif
-  TEncTop* pcEncTop = (TEncTop*) m_pcCfg;
-  TEncSbac**** ppppcRDSbacCoders    = pcEncTop->getRDSbacCoders();
-  TComBitCounter* pcBitCounters     = pcEncTop->getBitCounters();
-  Int  iNumSubstreams = 1;
-  UInt uiTilesAcross  = 0;
+
 #if H_3D_IC
   if ( pcEncTop->getViewIndex() && pcEncTop->getUseIC() &&
@@ -928,92 +835,35 @@
   }
 #endif
-    iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
-    uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
-    delete[] m_pcBufferSbacCoders;
-    delete[] m_pcBufferBinCoderCABACs;
-    m_pcBufferSbacCoders     = new TEncSbac    [uiTilesAcross];
-    m_pcBufferBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
-    for (Int ui = 0; ui < uiTilesAcross; ui++)
-    {
-      m_pcBufferSbacCoders[ui].init( &m_pcBufferBinCoderCABACs[ui] );
-    }
-    for (UInt ui = 0; ui < uiTilesAcross; ui++)
-    {
-      m_pcBufferSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
-    }
-
-    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ ) //init all sbac coders for RD optimization
-    {
-      ppppcRDSbacCoders[ui][0][CI_CURR_BEST]->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-    }
-    delete[] m_pcBufferLowLatSbacCoders;
-    delete[] m_pcBufferLowLatBinCoderCABACs;
-    m_pcBufferLowLatSbacCoders     = new TEncSbac    [uiTilesAcross];
-    m_pcBufferLowLatBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
-    for (Int ui = 0; ui < uiTilesAcross; ui++)
-    {
-      m_pcBufferLowLatSbacCoders[ui].init( &m_pcBufferLowLatBinCoderCABACs[ui] );
-    }
-    for (UInt ui = 0; ui < uiTilesAcross; ui++)
-      m_pcBufferLowLatSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
-
-  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
-  //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU();
-  UInt uiCol=0, uiLin=0, uiSubStrm=0;
-  UInt uiTileCol      = 0;
-  UInt uiTileStartLCU = 0;
-  UInt uiTileLCUX     = 0;
-  Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
-  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());
-  uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
-  if( depSliceSegmentsEnabled )
-  {
-    if((pcSlice->getSliceSegmentCurStartCUAddr()!= pcSlice->getSliceCurStartCUAddr())&&(uiCUAddr != uiTileStartLCU))
-    {
-      if( m_pcCfg->getWaveFrontsynchro() )
-      {
-        uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1);
-        m_pcBufferSbacCoders[uiTileCol].loadContexts( CTXMem[1] );
-        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
-        uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU()); 
-        uiLin     = uiCUAddr / uiWidthInLCUs;
-        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(rpcPic->getPicSym()->getCUOrderMap(uiCUAddr))*iNumSubstreamsPerTile
-          + uiLin%iNumSubstreamsPerTile;
-        if ( (uiCUAddr%uiWidthInLCUs+1) >= uiWidthInLCUs  )
-        {
-          uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
-          uiCol     = uiCUAddr % uiWidthInLCUs;
-          if(uiCol==uiTileStartLCU)
-          {
-            CTXMem[0]->loadContexts(m_pcSbacCoder);
-          }
-        }
-      }
-      m_pppcRDSbacCoder[0][CI_CURR_BEST]->loadContexts( CTXMem[0] );
-      ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( CTXMem[0] );
-    }
-    else
-    {
-      if(m_pcCfg->getWaveFrontsynchro())
-      {
-        CTXMem[1]->loadContexts(m_pcSbacCoder);
-      }
-      CTXMem[0]->loadContexts(m_pcSbacCoder);
-    }
-  }
-
-  // for every CU in slice
-#if H_3D
+
+
+
+  // Adjust initial state if this is the start of a dependent slice.
+  {
+    const UInt      ctuRsAddr               = pcPic->getPicSym()->getCtuTsToRsAddrMap( startCtuTsAddr);
+    const UInt      currentTileIdx          = pcPic->getPicSym()->getTileIdxMap(ctuRsAddr);
+    const TComTile *pCurrentTile            = pcPic->getPicSym()->getTComTile(currentTileIdx);
+    const UInt      firstCtuRsAddrOfTile    = pCurrentTile->getFirstCtuRsAddr();
+    if( pcSlice->getDependentSliceSegmentFlag() && ctuRsAddr != firstCtuRsAddrOfTile )
+    {
+      // This will only occur if dependent slice-segments (m_entropyCodingSyncContextState=true) are being used.
+      if( pCurrentTile->getTileWidthInCtus() >= 2 || !m_pcCfg->getWaveFrontsynchro() )
+      {
+        m_pppcRDSbacCoder[0][CI_CURR_BEST]->loadContexts( &m_lastSliceSegmentEndContextState );
+      }
+    }
+  }
+
+  // for every CTU in the slice segment (may terminate sooner if there is a byte limit on the slice-segment)
+#if NH_3D_VSO
   Int iLastPosY = -1;
 #endif
-  UInt uiEncCUOrder;
-  for( uiEncCUOrder = uiStartCUAddr/rpcPic->getNumPartInCU();
-       uiEncCUOrder < (uiBoundingCUAddr+(rpcPic->getNumPartInCU()-1))/rpcPic->getNumPartInCU();
-       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
-  {
-    // initialize CU encoder
-    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
-    pcCU->initCU( rpcPic, uiCUAddr );
-#if H_3D_VSO
+
+  for( UInt ctuTsAddr = startCtuTsAddr; ctuTsAddr < boundingCtuTsAddr; ++ctuTsAddr )
+  {
+    const UInt ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddr);
+    // initialize CTU encoder
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+    pCtu->initCtu( pcPic, ctuRsAddr );
+#if NH_3D_VSO
     if ( m_pcRdCost->getUseRenModel() )
     {
@@ -1021,94 +871,62 @@
       Int iCurPosX;
       Int iCurPosY; 
-      pcCU->getPosInPic(0, iCurPosX, iCurPosY );
+      pCtu->getPosInPic(0, iCurPosX, iCurPosY );
       if ( iCurPosY != iLastPosY )
       {
         iLastPosY = iCurPosY;         
-        pcEncTop->setupRenModel( pcSlice->getPOC() , pcSlice->getViewIndex(), pcSlice->getIsDepth() ? 1 : 0, iCurPosY );
-      }
-    }
-#endif
-    // inherit from TR if necessary, select substream to use.
-      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
-      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
-      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
-      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
-      uiCol     = uiCUAddr % uiWidthInLCUs;
-      uiLin     = uiCUAddr / uiWidthInLCUs;
-      if (pcSlice->getPPS()->getNumSubstreams() > 1)
-      {
-        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
-        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
-        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
-                      + uiLin%iNumSubstreamsPerTile;
+        TEncTop* pcEncTop = (TEncTop*) m_pcCfg; // Fix this later.
+        pcEncTop->setupRenModel( pcSlice->getPOC() , pcSlice->getViewIndex(), pcSlice->getIsDepth() ? 1 : 0, iCurPosY, pcSlice->getSPS()->getMaxCUHeight() );
+      }
+    }
+#endif
+
+    // update CABAC state
+    const UInt firstCtuRsAddrOfTile = pcPic->getPicSym()->getTComTile(pcPic->getPicSym()->getTileIdxMap(ctuRsAddr))->getFirstCtuRsAddr();
+    const UInt tileXPosInCtus = firstCtuRsAddrOfTile % frameWidthInCtus;
+    const UInt ctuXPosInCtus  = ctuRsAddr % frameWidthInCtus;
+    
+    if (ctuRsAddr == firstCtuRsAddrOfTile)
+    {
+      m_pppcRDSbacCoder[0][CI_CURR_BEST]->resetEntropy(pcSlice);
+    }
+    else if ( ctuXPosInCtus == tileXPosInCtus && m_pcCfg->getWaveFrontsynchro())
+    {
+      // reset and then update contexts to the state at the end of the top-right CTU (if within current slice and tile).
+      m_pppcRDSbacCoder[0][CI_CURR_BEST]->resetEntropy(pcSlice);
+      // Sync if the Top-Right is available.
+      TComDataCU *pCtuUp = pCtu->getCtuAbove();
+      if ( pCtuUp && ((ctuRsAddr%frameWidthInCtus+1) < frameWidthInCtus)  )
+      {
+        TComDataCU *pCtuTR = pcPic->getCtu( ctuRsAddr - frameWidthInCtus + 1 );
+        if ( pCtu->CUIsFromSameSliceAndTile(pCtuTR) )
+        {
+          // Top-Right is available, we use it.
+          m_pppcRDSbacCoder[0][CI_CURR_BEST]->loadContexts( &m_entropyCodingSyncContextState );
+        }
+      }
+    }
+
+    // set go-on entropy coder (used for all trial encodings - the cu encoder and encoder search also have a copy of the same pointer)
+    m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder );
+    m_pcEntropyCoder->setBitstream( &tempBitCounter );
+    tempBitCounter.resetBits();
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] ); // this copy is not strictly necessary here, but indicates that the GoOnSbacCoder
+                                                                     // is reset to a known state before every decision process.
+
+    ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
+
+    Double oldLambda = m_pcRdCost->getLambda();
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+      Int estQP        = pcSlice->getSliceQp();
+      Double estLambda = -1.0;
+      Double bpp       = -1.0;
+
+      if ( ( pcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
+      {
+        estQP = pcSlice->getSliceQp();
       }
       else
       {
-        // dependent tiles => substreams are "per frame".
-        uiSubStrm = uiLin % iNumSubstreams;
-      }
-      if ( ((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled ) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
-      {
-        // We'll sync if the TR is available.
-        TComDataCU *pcCUUp = pcCU->getCUAbove();
-        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
-        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
-        TComDataCU *pcCUTR = NULL;
-        if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
-        {
-          pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
-        }
-        if ( ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
-             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
-             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
-             )
-           )
-        {
-          // TR not available.
-        }
-        else
-        {
-          // TR is available, we use it.
-          ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
-        }
-      }
-      m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST] ); //this load is used to simplify the code
-
-    // reset the entropy coder
-    if( uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr() &&                                   // must be first CU of tile
-        uiCUAddr!=0 &&                                                                                                                                    // cannot be first CU of picture
-        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr())/rpcPic->getNumPartInCU() &&
-        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())     // cannot be first CU of slice
-    {
-      SliceType sliceType = pcSlice->getSliceType();
-      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag() && pcSlice->getPPS()->getEncCABACTableIdx()!=I_SLICE)
-      {
-        sliceType = (SliceType) pcSlice->getPPS()->getEncCABACTableIdx();
-      }
-      m_pcEntropyCoder->updateContextTables ( sliceType, pcSlice->getSliceQp(), false );
-      m_pcEntropyCoder->setEntropyCoder     ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
-      m_pcEntropyCoder->updateContextTables ( sliceType, pcSlice->getSliceQp() );
-      m_pcEntropyCoder->setEntropyCoder     ( m_pcSbacCoder, pcSlice );
-    }
-
-      // set go-on entropy coder
-      m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
-      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
-      
-      ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
-
-      Double oldLambda = m_pcRdCost->getLambda();
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
-        Int estQP        = pcSlice->getSliceQp();
-        Double estLambda = -1.0;
-        Double bpp       = -1.0;
-
-        if ( ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
-        {
-          estQP = pcSlice->getSliceQp();
-        }
-        else
-        {
 #if KWU_RC_MADPRED_E0227
           if(pcSlice->getLayerId() != 0 && m_pcCfg->getUseDepthMADPred() && !pcSlice->getIsDepth())
@@ -1129,70 +947,94 @@
           {
 #endif
-          bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
-          if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
-          {
-            estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambdaAndQP(bpp, pcSlice->getSliceQp(), &estQP);
-          }
-          else
-          {
-            estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
-            estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
-          }
+        bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
+        if ( pcPic->getSlice( 0 )->getSliceType() == I_SLICE)
+        {
+          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambdaAndQP(bpp, pcSlice->getSliceQp(), &estQP);
+        }
+        else
+        {
+          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
+          estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
+        }
 #if KWU_RC_MADPRED_E0227
           estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
           estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
 #endif
-          estQP     = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, estQP );
-
-          m_pcRdCost->setLambda(estLambda);
+
+        estQP     = Clip3( -pcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, estQP );
+
+        m_pcRdCost->setLambda(estLambda, pcSlice->getSPS()->getBitDepths());
+
 #if RDOQ_CHROMA_LAMBDA
-          // set lambda for RDOQ
-          Double weight=m_pcRdCost->getChromaWeight();
-        const Double lambdaArray[3] = { estLambda, (estLambda / weight), (estLambda / weight) };
+        // set lambda for RDOQ
+        const Double chromaLambda = estLambda / m_pcRdCost->getChromaWeight();
+        const Double lambdaArray[MAX_NUM_COMPONENT] = { estLambda, chromaLambda, chromaLambda };
         m_pcTrQuant->setLambdas( lambdaArray );
 #else
-          m_pcTrQuant->setLambda( estLambda );
-#endif
-        }
-
-        m_pcRateCtrl->setRCQP( estQP );
+        m_pcTrQuant->setLambda( estLambda );
+#endif
+      }
+
+      m_pcRateCtrl->setRCQP( estQP );
 #if ADAPTIVE_QP_SELECTION
-        pcCU->getSlice()->setSliceQpBase( estQP );
-#endif
-      }
-      // run CU encoder
-      m_pcCuEncoder->compressCU( pcCU );
-
-      // restore entropy coder to an initial stage
-      m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
-      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
-      m_pcCuEncoder->setBitCounter( &pcBitCounters[uiSubStrm] );
-      m_pcBitCounter = &pcBitCounters[uiSubStrm];
-      pppcRDSbacCoder->setBinCountingEnableFlag( true );
-      m_pcBitCounter->resetBits();
-      pppcRDSbacCoder->setBinsCoded( 0 );
-      m_pcCuEncoder->encodeCU( pcCU );
-
-      pppcRDSbacCoder->setBinCountingEnableFlag( false );
-      if (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES && ( ( pcSlice->getSliceBits() + m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
-      {
-        pcSlice->setNextSlice( true );
-        break;
-      }
-      if (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+m_pcEntropyCoder->getNumberOfWrittenBits() > (m_pcCfg->getSliceSegmentArgument() << 3) &&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getSliceSegmentCurEndCUAddr())
-      {
-        pcSlice->setNextSliceSegment( true );
-        break;
-      }
-       
-    ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
-         //Store probabilties of second LCU in line into buffer
-         if ( ( uiCol == uiTileLCUX+1) && (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && m_pcCfg->getWaveFrontsynchro())
-        {
-          m_pcBufferSbacCoders[uiTileCol].loadContexts(ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]);
-        }
-
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
+      pCtu->getSlice()->setSliceQpBase( estQP );
+#endif
+    }
+
+    // run CTU trial encoder
+    m_pcCuEncoder->compressCtu( pCtu );
+
+
+    // All CTU decisions have now been made. Restore entropy coder to an initial stage, ready to make a true encode,
+    // which will result in the state of the contexts being correct. It will also count up the number of bits coded,
+    // which is used if there is a limit of the number of bytes per slice-segment.
+
+    m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
+    m_pcEntropyCoder->setBitstream( &tempBitCounter );
+    pRDSbacCoder->setBinCountingEnableFlag( true );
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->resetBits();
+    pRDSbacCoder->setBinsCoded( 0 );
+
+    // encode CTU and calculate the true bit counters.
+    m_pcCuEncoder->encodeCtu( pCtu );
+
+
+    pRDSbacCoder->setBinCountingEnableFlag( false );
+
+    const Int numberOfWrittenBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+    // Calculate if this CTU puts us over slice bit size.
+    // cannot terminate if current slice/slice-segment would be 0 Ctu in size,
+    const UInt validEndOfSliceCtuTsAddr = ctuTsAddr + (ctuTsAddr == startCtuTsAddr ? 1 : 0);
+    // Set slice end parameter
+    if(pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceBits()+numberOfWrittenBits > (pcSlice->getSliceArgument()<<3))
+    {
+      pcSlice->setSliceSegmentCurEndCtuTsAddr(validEndOfSliceCtuTsAddr);
+      pcSlice->setSliceCurEndCtuTsAddr(validEndOfSliceCtuTsAddr);
+      boundingCtuTsAddr=validEndOfSliceCtuTsAddr;
+    }
+    else if((!bCompressEntireSlice) && pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+numberOfWrittenBits > (pcSlice->getSliceSegmentArgument()<<3))
+    {
+      pcSlice->setSliceSegmentCurEndCtuTsAddr(validEndOfSliceCtuTsAddr);
+      boundingCtuTsAddr=validEndOfSliceCtuTsAddr;
+    }
+
+    if (boundingCtuTsAddr <= ctuTsAddr)
+    {
+      break;
+    }
+
+    pcSlice->setSliceBits( (UInt)(pcSlice->getSliceBits() + numberOfWrittenBits) );
+    pcSlice->setSliceSegmentBits(pcSlice->getSliceSegmentBits()+numberOfWrittenBits);
+
+    // Store probabilities of second CTU in line into buffer - used only if wavefront-parallel-processing is enabled.
+    if ( ctuXPosInCtus == tileXPosInCtus+1 && m_pcCfg->getWaveFrontsynchro())
+    {
+      m_entropyCodingSyncContextState.loadContexts(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+    }
+
+
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
 #if KWU_RC_MADPRED_E0227
         UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
@@ -1204,84 +1046,76 @@
 #endif
 
-        Int actualQP        = g_RCInvalidQPValue;
-        Double actualLambda = m_pcRdCost->getLambda();
-        Int actualBits      = pcCU->getTotalBits();
-        Int numberOfEffectivePixels    = 0;
-        for ( Int idx = 0; idx < rpcPic->getNumPartInCU(); idx++ )
+      Int actualQP        = g_RCInvalidQPValue;
+      Double actualLambda = m_pcRdCost->getLambda();
+      Int actualBits      = pCtu->getTotalBits();
+      Int numberOfEffectivePixels    = 0;
+      for ( Int idx = 0; idx < pcPic->getNumPartitionsInCtu(); idx++ )
+      {
+        if ( pCtu->getPredictionMode( idx ) != NUMBER_OF_PREDICTION_MODES && ( !pCtu->isSkipped( idx ) ) )
         {
-          if ( pcCU->getPredictionMode( idx ) != MODE_NONE && ( !pcCU->isSkipped( idx ) ) )
-          {
-            numberOfEffectivePixels = numberOfEffectivePixels + 16;
-            break;
-          }
+          numberOfEffectivePixels = numberOfEffectivePixels + 16;
+          break;
         }
-
-        if ( numberOfEffectivePixels == 0 )
-        {
-          actualQP = g_RCInvalidQPValue;
-        }
-        else
-        {
-          actualQP = pcCU->getQP( 0 );
-        }
-        m_pcRdCost->setLambda(oldLambda);
-
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, 
-          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
-    }
-    
-    m_uiPicTotalBits += pcCU->getTotalBits();
-    m_dPicRdCost     += pcCU->getTotalCost();
-    m_uiPicDist      += pcCU->getTotalDistortion();
-  }
-  if ((pcSlice->getPPS()->getNumSubstreams() > 1) && !depSliceSegmentsEnabled)
-  {
-    pcSlice->setNextSlice( true );
-  }
-  if(m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES || m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES)
-  {
-    if(pcSlice->getSliceCurEndCUAddr()<=pcSlice->getSliceSegmentCurEndCUAddr())
-    {
-       pcSlice->setNextSlice( true );
-    }
-    else
-    {
-       pcSlice->setNextSliceSegment( true );
-    }
-  }
-  if( depSliceSegmentsEnabled )
-  {
-    if (m_pcCfg->getWaveFrontsynchro())
-    {
-      CTXMem[1]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );//ctx 2.LCU
-    }
-     CTXMem[0]->loadContexts( m_pppcRDSbacCoder[0][CI_CURR_BEST] );//ctx end of dep.slice
-  }
-  xRestoreWPparam( pcSlice );
-}
-
-/**
- \param  rpcPic        picture class
- \retval rpcBitstream  bitstream class
- */
-Void TEncSlice::encodeSlice   ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams )
-{
-  UInt       uiCUAddr;
-  UInt       uiStartCUAddr;
-  UInt       uiBoundingCUAddr;
-  TComSlice* pcSlice = rpcPic->getSlice(getSliceIdx());
-
-  uiStartCUAddr=pcSlice->getSliceSegmentCurStartCUAddr();
-  uiBoundingCUAddr=pcSlice->getSliceSegmentCurEndCUAddr();
-  // choose entropy coder
-  {
-    m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
-    m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
-  }
-  
-  m_pcCuEncoder->setBitCounter( NULL );
-  m_pcBitCounter = NULL;
-  // Appropriate substream bitstream is switched later.
-  // for every CU
+      }
+
+      if ( numberOfEffectivePixels == 0 )
+      {
+        actualQP = g_RCInvalidQPValue;
+      }
+      else
+      {
+        actualQP = pCtu->getQP( 0 );
+      }
+      m_pcRdCost->setLambda(oldLambda, pcSlice->getSPS()->getBitDepths());
+      m_pcRateCtrl->getRCPic()->updateAfterCTU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
+                                                pCtu->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
+    }
+
+    m_uiPicTotalBits += pCtu->getTotalBits();
+    m_dPicRdCost     += pCtu->getTotalCost();
+    m_uiPicDist      += pCtu->getTotalDistortion();
+  }
+
+  // store context state at the end of this slice-segment, in case the next slice is a dependent slice and continues using the CABAC contexts.
+  if( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() )
+  {
+    m_lastSliceSegmentEndContextState.loadContexts( m_pppcRDSbacCoder[0][CI_CURR_BEST] );//ctx end of dep.slice
+  }
+
+  // stop use of temporary bit counter object.
+  m_pppcRDSbacCoder[0][CI_CURR_BEST]->setBitstream(NULL);
+  m_pcRDGoOnSbacCoder->setBitstream(NULL); // stop use of tempBitCounter.
+
+  // TODO: optimise cabac_init during compress slice to improve multi-slice operation
+  //if (pcSlice->getPPS()->getCabacInitPresentFlag() && !pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag())
+  //{
+  //  m_encCABACTableIdx = m_pcEntropyCoder->determineCabacInitIdx();
+  //}
+  //else
+  //{
+  //  m_encCABACTableIdx = pcSlice->getSliceType();
+  //}
+}
+
+Void TEncSlice::encodeSlice   ( TComPic* pcPic, TComOutputBitstream* pcSubstreams, UInt &numBinsCoded )
+{
+  TComSlice *const pcSlice           = pcPic->getSlice(getSliceIdx());
+
+  const UInt startCtuTsAddr          = pcSlice->getSliceSegmentCurStartCtuTsAddr();
+  const UInt boundingCtuTsAddr       = pcSlice->getSliceSegmentCurEndCtuTsAddr();
+
+  const UInt frameWidthInCtus        = pcPic->getPicSym()->getFrameWidthInCtus();
+  const Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
+  const Bool wavefrontsEnabled       = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag();
+
+  // initialise entropy coder for the slice
+  m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+  m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder );
+  m_pcEntropyCoder->resetEntropy    ( pcSlice );
+
+  numBinsCoded = 0;
+  m_pcBinCABAC->setBinCountingEnableFlag( true );
+  m_pcBinCABAC->setBinsCoded(0);
+
 #if ENC_DEC_TRACE
   g_bJustDoIt = g_bEncDecTraceEnable;
@@ -1289,8 +1123,8 @@
   DTRACE_CABAC_VL( g_nSymbolCounter++ );
   DTRACE_CABAC_T( "\tPOC: " );
-  DTRACE_CABAC_V( rpcPic->getPOC() );
+  DTRACE_CABAC_V( pcPic->getPOC() );
 #if H_MV_ENC_DEC_TRAC
   DTRACE_CABAC_T( " Layer: " );
-  DTRACE_CABAC_V( rpcPic->getLayerId() );
+  DTRACE_CABAC_V( pcPic->getLayerId() );
 #endif
   DTRACE_CABAC_T( "\n" );
@@ -1299,161 +1133,62 @@
 #endif
 
-  TEncTop* pcEncTop = (TEncTop*) m_pcCfg;
-  TEncSbac* pcSbacCoders = pcEncTop->getSbacCoders(); //coder for each substream
-  Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
-  UInt uiBitsOriginallyInSubstreams = 0;
-  {
-    UInt uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
-    for (UInt ui = 0; ui < uiTilesAcross; ui++)
-    {
-      m_pcBufferSbacCoders[ui].load(m_pcSbacCoder); //init. state
-    }
-    
-    for (Int iSubstrmIdx=0; iSubstrmIdx < iNumSubstreams; iSubstrmIdx++)
-    {
-      uiBitsOriginallyInSubstreams += pcSubstreams[iSubstrmIdx].getNumberOfWrittenBits();
-    }
-
-    for (UInt ui = 0; ui < uiTilesAcross; ui++)
-    {
-      m_pcBufferLowLatSbacCoders[ui].load(m_pcSbacCoder);  //init. state
-    }
-  }
-
-  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
-  UInt uiCol=0, uiLin=0, uiSubStrm=0;
-  UInt uiTileCol      = 0;
-  UInt uiTileStartLCU = 0;
-  UInt uiTileLCUX     = 0;
-  Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
-  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());  /* for tiles, uiStartCUAddr is NOT the real raster scan address, it is actually
-                                                                                               an encoding order index, so we need to convert the index (uiStartCUAddr)
-                                                                                               into the real raster scan address (uiCUAddr) via the CUOrderMap */
-  uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
-  if( depSliceSegmentsEnabled )
-  {
-    if( pcSlice->isNextSlice()||
-        uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr())
-    {
-      if(m_pcCfg->getWaveFrontsynchro())
-      {
-        CTXMem[1]->loadContexts(m_pcSbacCoder);
-      }
-      CTXMem[0]->loadContexts(m_pcSbacCoder);
-    }
-    else
-    {
-      if(m_pcCfg->getWaveFrontsynchro())
-      {
-        uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1);
-        m_pcBufferSbacCoders[uiTileCol].loadContexts( CTXMem[1] );
-        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
-        uiLin     = uiCUAddr / uiWidthInLCUs;
-        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(rpcPic->getPicSym()->getCUOrderMap( uiCUAddr))*iNumSubstreamsPerTile
-          + uiLin%iNumSubstreamsPerTile;
-        if ( (uiCUAddr%uiWidthInLCUs+1) >= uiWidthInLCUs  )
+
+  if (depSliceSegmentsEnabled)
+  {
+    // modify initial contexts with previous slice segment if this is a dependent slice.
+    const UInt ctuRsAddr        = pcPic->getPicSym()->getCtuTsToRsAddrMap( startCtuTsAddr );
+    const UInt currentTileIdx=pcPic->getPicSym()->getTileIdxMap(ctuRsAddr);
+    const TComTile *pCurrentTile=pcPic->getPicSym()->getTComTile(currentTileIdx);
+    const UInt firstCtuRsAddrOfTile = pCurrentTile->getFirstCtuRsAddr();
+
+    if( pcSlice->getDependentSliceSegmentFlag() && ctuRsAddr != firstCtuRsAddrOfTile )
+    {
+      if( pCurrentTile->getTileWidthInCtus() >= 2 || !wavefrontsEnabled )
+      {
+        m_pcSbacCoder->loadContexts(&m_lastSliceSegmentEndContextState);
+      }
+    }
+  }
+
+  // for every CTU in the slice segment...
+
+  for( UInt ctuTsAddr = startCtuTsAddr; ctuTsAddr < boundingCtuTsAddr; ++ctuTsAddr )
+  {
+    const UInt ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddr);
+    const TComTile &currentTile = *(pcPic->getPicSym()->getTComTile(pcPic->getPicSym()->getTileIdxMap(ctuRsAddr)));
+    const UInt firstCtuRsAddrOfTile = currentTile.getFirstCtuRsAddr();
+    const UInt tileXPosInCtus       = firstCtuRsAddrOfTile % frameWidthInCtus;
+    const UInt tileYPosInCtus       = firstCtuRsAddrOfTile / frameWidthInCtus;
+    const UInt ctuXPosInCtus        = ctuRsAddr % frameWidthInCtus;
+    const UInt ctuYPosInCtus        = ctuRsAddr / frameWidthInCtus;
+    const UInt uiSubStrm=pcPic->getSubstreamForCtuAddr(ctuRsAddr, true, pcSlice);
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+
+    m_pcEntropyCoder->setBitstream( &pcSubstreams[uiSubStrm] );
+
+    // set up CABAC contexts' state for this CTU
+    if (ctuRsAddr == firstCtuRsAddrOfTile)
+    {
+      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
+      {
+        m_pcEntropyCoder->resetEntropy(pcSlice);
+      }
+    }
+    else if (ctuXPosInCtus == tileXPosInCtus && wavefrontsEnabled)
+    {
+      // Synchronize cabac probabilities with upper-right CTU if it's available and at the start of a line.
+      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
+      {
+        m_pcEntropyCoder->resetEntropy(pcSlice);
+      }
+      TComDataCU *pCtuUp = pCtu->getCtuAbove();
+      if ( pCtuUp && ((ctuRsAddr%frameWidthInCtus+1) < frameWidthInCtus)  )
+      {
+        TComDataCU *pCtuTR = pcPic->getCtu( ctuRsAddr - frameWidthInCtus + 1 );
+        if ( pCtu->CUIsFromSameSliceAndTile(pCtuTR) )
         {
-          uiCol     = uiCUAddr % uiWidthInLCUs;
-          uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
-          if(uiCol==uiTileLCUX)
-          {
-            CTXMem[0]->loadContexts(m_pcSbacCoder);
-          }
+          // Top-right is available, so use it.
+          m_pcSbacCoder->loadContexts( &m_entropyCodingSyncContextState );
         }
-      }
-      pcSbacCoders[uiSubStrm].loadContexts( CTXMem[0] );
-    }
-  }
-
-  UInt uiEncCUOrder;
-  for( uiEncCUOrder = uiStartCUAddr /rpcPic->getNumPartInCU();
-       uiEncCUOrder < (uiBoundingCUAddr+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
-       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
-  {
-      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
-      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
-      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
-      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
-      uiCol     = uiCUAddr % uiWidthInLCUs;
-      uiLin     = uiCUAddr / uiWidthInLCUs;
-      if (pcSlice->getPPS()->getNumSubstreams() > 1)
-      {
-        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
-        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
-        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
-                      + uiLin%iNumSubstreamsPerTile;
-      }
-      else
-      {
-        // dependent tiles => substreams are "per frame".
-        uiSubStrm = uiLin % iNumSubstreams;
-      }
-
-      m_pcEntropyCoder->setBitstream( &pcSubstreams[uiSubStrm] );
-      // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line.
-      if (((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
-      {
-        // We'll sync if the TR is available.
-        TComDataCU *pcCUUp = rpcPic->getCU( uiCUAddr )->getCUAbove();
-        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
-        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
-        TComDataCU *pcCUTR = NULL;
-        if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
-        {
-          pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
-        }
-        if ( (true/*bEnforceSliceRestriction*/ &&
-             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
-             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
-             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
-             ))
-           )
-        {
-          // TR not available.
-        }
-        else
-        {
-          // TR is available, we use it.
-          pcSbacCoders[uiSubStrm].loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
-        }
-      }
-      m_pcSbacCoder->load(&pcSbacCoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to m_pcSbacCoder)
-
-    // reset the entropy coder
-    if( uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr() &&                                   // must be first CU of tile
-        uiCUAddr!=0 &&                                                                                                                                    // cannot be first CU of picture
-        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr())/rpcPic->getNumPartInCU() &&
-        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())     // cannot be first CU of slice
-    {
-      {
-        // We're crossing into another tile, tiles are independent.
-        // When tiles are independent, we have "substreams per tile".  Each substream has already been terminated, and we no longer
-        // have to perform it here.
-        if (pcSlice->getPPS()->getNumSubstreams() > 1)
-        {
-          ; // do nothing.
-        }
-        else
-        {
-          SliceType sliceType  = pcSlice->getSliceType();
-          if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag() && pcSlice->getPPS()->getEncCABACTableIdx()!=I_SLICE)
-          {
-            sliceType = (SliceType) pcSlice->getPPS()->getEncCABACTableIdx();
-          }
-          m_pcEntropyCoder->updateContextTables( sliceType, pcSlice->getSliceQp() );
-          // Byte-alignment in slice_data() when new tile
-          pcSubstreams[uiSubStrm].writeByteAlignment();
-        }
-      }
-      {
-        UInt numStartCodeEmulations = pcSubstreams[uiSubStrm].countStartCodeEmulations();
-        UInt uiAccumulatedSubstreamLength = 0;
-        for (Int iSubstrmIdx=0; iSubstrmIdx < iNumSubstreams; iSubstrmIdx++)
-        {
-          uiAccumulatedSubstreamLength += pcSubstreams[iSubstrmIdx].getNumberOfWrittenBits();
-        }
-        // add bits coded in previous dependent slices + bits coded so far
-        // add number of emulation prevention byte count in the tile
-        pcSlice->addTileLocation( ((pcSlice->getTileOffstForMultES() + uiAccumulatedSubstreamLength - uiBitsOriginallyInSubstreams) >> 3) + numStartCodeEmulations );
       }
     }
@@ -1462,412 +1197,224 @@
     rpcPic->setReduceBitsFlag(true);
 #endif
-    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );    
     if ( pcSlice->getSPS()->getUseSAO() )
     {
-      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
-      {
-        SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[uiCUAddr];
-        Bool sliceEnabled[NUM_SAO_COMPONENTS];
-        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
-        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
+      Bool bIsSAOSliceEnabled = false;
+      Bool sliceEnabled[MAX_NUM_COMPONENT];
+      for(Int comp=0; comp < MAX_NUM_COMPONENT; comp++)
+      {
+        ComponentID compId=ComponentID(comp);
+        sliceEnabled[compId] = pcSlice->getSaoEnabledFlag(toChannelType(compId)) && (comp < pcPic->getNumberValidComponents());
+        if (sliceEnabled[compId])
+        {
+          bIsSAOSliceEnabled=true;
+        }
+      }
+      if (bIsSAOSliceEnabled)
+      {
+        SAOBlkParam& saoblkParam = (pcPic->getPicSym()->getSAOBlkParam())[ctuRsAddr];
 
         Bool leftMergeAvail = false;
         Bool aboveMergeAvail= false;
         //merge left condition
-        Int rx = (uiCUAddr % uiWidthInLCUs);
+        Int rx = (ctuRsAddr % frameWidthInCtus);
         if(rx > 0)
         {
-          leftMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-1);
+          leftMergeAvail = pcPic->getSAOMergeAvailability(ctuRsAddr, ctuRsAddr-1);
         }
 
         //merge up condition
-        Int ry = (uiCUAddr / uiWidthInLCUs);
+        Int ry = (ctuRsAddr / frameWidthInCtus);
         if(ry > 0)
-      {
-          aboveMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-uiWidthInLCUs);
+        {
+          aboveMergeAvail = pcPic->getSAOMergeAvailability(ctuRsAddr, ctuRsAddr-frameWidthInCtus);
         }
 
-        m_pcEntropyCoder->encodeSAOBlkParam(saoblkParam,sliceEnabled, leftMergeAvail, aboveMergeAvail);
-      }
-    }
+        m_pcEntropyCoder->encodeSAOBlkParam(saoblkParam, pcPic->getPicSym()->getSPS().getBitDepths(), sliceEnabled, leftMergeAvail, aboveMergeAvail);
+      }
+    }
+
 #if ENC_DEC_TRACE
     g_bJustDoIt = g_bEncDecTraceEnable;
 #endif
-    if ( (m_pcCfg->getSliceMode()!=0 || m_pcCfg->getSliceSegmentMode()!=0) &&
-      uiCUAddr == rpcPic->getPicSym()->getCUOrderMap((uiBoundingCUAddr+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU()-1) )
-    {
-      m_pcCuEncoder->encodeCU( pcCU );
-    }
-    else
-    {
-      m_pcCuEncoder->encodeCU( pcCU );
-    }
+      m_pcCuEncoder->encodeCtu( pCtu );
 #if ENC_DEC_TRACE
     g_bJustDoIt = g_bEncDecTraceDisable;
-#endif    
-       pcSbacCoders[uiSubStrm].load(m_pcSbacCoder);   //load back status of the entropy coder after encoding the LCU into relevant bitstream entropy coder
-       
-
-       //Store probabilties of second LCU in line into buffer
-       if ( (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (uiCol == uiTileLCUX+1) && m_pcCfg->getWaveFrontsynchro())
-      {
-        m_pcBufferSbacCoders[uiTileCol].loadContexts( &pcSbacCoders[uiSubStrm] );
-      }
+#endif
+
+    //Store probabilities of second CTU in line into buffer
+    if ( ctuXPosInCtus == tileXPosInCtus+1 && wavefrontsEnabled)
+    {
+      m_entropyCodingSyncContextState.loadContexts( m_pcSbacCoder );
+    }
+
+    // terminate the sub-stream, if required (end of slice-segment, end of tile, end of wavefront-CTU-row):
+    if (ctuTsAddr+1 == boundingCtuTsAddr ||
+         (  ctuXPosInCtus + 1 == tileXPosInCtus + currentTile.getTileWidthInCtus() &&
+          ( ctuYPosInCtus + 1 == tileYPosInCtus + currentTile.getTileHeightInCtus() || wavefrontsEnabled)
+         )
+       )
+    {
+      m_pcEntropyCoder->encodeTerminatingBit(1);
+      m_pcEntropyCoder->encodeSliceFinish();
+      // Byte-alignment in slice_data() when new tile
+      pcSubstreams[uiSubStrm].writeByteAlignment();
+
+      // write sub-stream size
+      if (ctuTsAddr+1 != boundingCtuTsAddr)
+      {
+        pcSlice->addSubstreamSize( (pcSubstreams[uiSubStrm].getNumberOfWrittenBits() >> 3) + pcSubstreams[uiSubStrm].countStartCodeEmulations() );
+      }
+    }
 #if H_3D_QTLPC
     rpcPic->setReduceBitsFlag(false);
 #endif
-  }
+  } // CTU-loop
+
   if( depSliceSegmentsEnabled )
   {
-    if (m_pcCfg->getWaveFrontsynchro())
-    {
-      CTXMem[1]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );//ctx 2.LCU
-    }
-    CTXMem[0]->loadContexts( m_pcSbacCoder );//ctx end of dep.slice
-  }
+    m_lastSliceSegmentEndContextState.loadContexts( m_pcSbacCoder );//ctx end of dep.slice
+  }
+
 #if ADAPTIVE_QP_SELECTION
   if( m_pcCfg->getUseAdaptQpSelect() )
   {
-    m_pcTrQuant->storeSliceQpNext(pcSlice);
-  }
-#endif
-  if (pcSlice->getPPS()->getCabacInitPresentFlag())
-  {
-    if  (pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag())
-    {
-      pcSlice->getPPS()->setEncCABACTableIdx( pcSlice->getSliceType() );
-    }
-    else
-    {
-      m_pcEntropyCoder->determineCabacInitIdx();
-    }
-  }
-}
-
-/** Determines the starting and bounding LCU address of current slice / dependent slice
- * \param bEncodeSlice Identifies if the calling function is compressSlice() [false] or encodeSlice() [true]
- * \returns Updates uiStartCUAddr, uiBoundingCUAddr with appropriate LCU address
- */
-Void TEncSlice::xDetermineStartAndBoundingCUAddr  ( UInt& startCUAddr, UInt& boundingCUAddr, TComPic*& rpcPic, Bool bEncodeSlice )
-{
-  TComSlice* pcSlice = rpcPic->getSlice(getSliceIdx());
-  UInt uiStartCUAddrSlice, uiBoundingCUAddrSlice;
-  UInt tileIdxIncrement;
-  UInt tileIdx;
-  UInt tileWidthInLcu;
-  UInt tileHeightInLcu;
-  UInt tileTotalCount;
-
-  uiStartCUAddrSlice        = pcSlice->getSliceCurStartCUAddr();
-  UInt uiNumberOfCUsInFrame = rpcPic->getNumCUsInFrame();
-  uiBoundingCUAddrSlice     = uiNumberOfCUsInFrame;
-  if (bEncodeSlice) 
-  {
-    UInt uiCUAddrIncrement;
-    switch (m_pcCfg->getSliceMode())
-    {
-    case FIXED_NUMBER_OF_LCU:
-      uiCUAddrIncrement        = m_pcCfg->getSliceArgument();
-      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+    m_pcTrQuant->storeSliceQpNext(pcSlice); // TODO: this will only be storing the adaptive QP state of the very last slice-segment that is not dependent in the frame... Perhaps this should be moved to the compress slice loop.
+  }
+#endif
+
+  if (pcSlice->getPPS()->getCabacInitPresentFlag() && !pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag())
+  {
+    m_encCABACTableIdx = m_pcEntropyCoder->determineCabacInitIdx(pcSlice);
+  }
+  else
+  {
+    m_encCABACTableIdx = pcSlice->getSliceType();
+  }
+  
+  numBinsCoded = m_pcBinCABAC->getBinsCoded();
+}
+
+Void TEncSlice::calculateBoundingCtuTsAddrForSlice(UInt &startCtuTSAddrSlice, UInt &boundingCtuTSAddrSlice, Bool &haveReachedTileBoundary,
+                                                   TComPic* pcPic, const Int sliceMode, const Int sliceArgument)
+{
+  TComSlice* pcSlice = pcPic->getSlice(getSliceIdx());
+  const UInt numberOfCtusInFrame = pcPic->getNumberOfCtusInFrame();
+  const TComPPS &pps=*(pcSlice->getPPS());
+  boundingCtuTSAddrSlice=0;
+  haveReachedTileBoundary=false;
+
+  switch (sliceMode)
+  {
+    case FIXED_NUMBER_OF_CTU:
+      {
+        UInt ctuAddrIncrement    = sliceArgument;
+        boundingCtuTSAddrSlice  = ((startCtuTSAddrSlice + ctuAddrIncrement) < numberOfCtusInFrame) ? (startCtuTSAddrSlice + ctuAddrIncrement) : numberOfCtusInFrame;
+      }
       break;
     case FIXED_NUMBER_OF_BYTES:
-      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
-      uiBoundingCUAddrSlice    = pcSlice->getSliceCurEndCUAddr();
+      boundingCtuTSAddrSlice  = numberOfCtusInFrame; // This will be adjusted later if required.
       break;
     case FIXED_NUMBER_OF_TILES:
-      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
-        rpcPic->getPicSym()->getCUOrderMap(uiStartCUAddrSlice/rpcPic->getNumPartInCU())
-        );
-      uiCUAddrIncrement        = 0;
-      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
-
-      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceArgument(); tileIdxIncrement++)
-      {
-        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+      {
+        const UInt tileIdx        = pcPic->getPicSym()->getTileIdxMap( pcPic->getPicSym()->getCtuTsToRsAddrMap(startCtuTSAddrSlice) );
+        const UInt tileTotalCount = (pcPic->getPicSym()->getNumTileColumnsMinus1()+1) * (pcPic->getPicSym()->getNumTileRowsMinus1()+1);
+        UInt ctuAddrIncrement   = 0;
+
+        for(UInt tileIdxIncrement = 0; tileIdxIncrement < sliceArgument; tileIdxIncrement++)
         {
-          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
-          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
-          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+          if((tileIdx + tileIdxIncrement) < tileTotalCount)
+          {
+            UInt tileWidthInCtus   = pcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidthInCtus();
+            UInt tileHeightInCtus  = pcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeightInCtus();
+            ctuAddrIncrement    += (tileWidthInCtus * tileHeightInCtus);
+          }
         }
-      }
-
-      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+
+        boundingCtuTSAddrSlice  = ((startCtuTSAddrSlice + ctuAddrIncrement) < numberOfCtusInFrame) ? (startCtuTSAddrSlice + ctuAddrIncrement) : numberOfCtusInFrame;
+      }
       break;
     default:
-      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
-      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      boundingCtuTSAddrSlice    = numberOfCtusInFrame;
       break;
-    } 
+  }
+
+  // Adjust for tiles and wavefronts.
+  const Bool wavefrontsAreEnabled = pps.getEntropyCodingSyncEnabledFlag();
+
+  if ((sliceMode == FIXED_NUMBER_OF_CTU || sliceMode == FIXED_NUMBER_OF_BYTES) &&
+      (pps.getNumTileRowsMinus1() > 0 || pps.getNumTileColumnsMinus1() > 0))
+  {
+    const UInt ctuRSAddr                  = pcPic->getPicSym()->getCtuTsToRsAddrMap(startCtuTSAddrSlice);
+    const UInt startTileIdx               = pcPic->getPicSym()->getTileIdxMap(ctuRSAddr);
+
+    const TComTile *pStartingTile         = pcPic->getPicSym()->getTComTile(startTileIdx);
+    const UInt tileStartTsAddr            = pcPic->getPicSym()->getCtuRsToTsAddrMap(pStartingTile->getFirstCtuRsAddr());
+    const UInt tileStartWidth             = pStartingTile->getTileWidthInCtus();
+    const UInt tileStartHeight            = pStartingTile->getTileHeightInCtus();
+    const UInt tileLastTsAddr_excl        = tileStartTsAddr + tileStartWidth*tileStartHeight;
+    const UInt tileBoundingCtuTsAddrSlice = tileLastTsAddr_excl;
+
+    const UInt ctuColumnOfStartingTile    = ((startCtuTSAddrSlice-tileStartTsAddr)%tileStartWidth);
+    if (wavefrontsAreEnabled && ctuColumnOfStartingTile!=0)
+    {
+      // WPP: if a slice does not start at the beginning of a CTB row, it must end within the same CTB row
+      const UInt numberOfCTUsToEndOfRow            = tileStartWidth - ctuColumnOfStartingTile;
+      const UInt wavefrontTileBoundingCtuAddrSlice = startCtuTSAddrSlice + numberOfCTUsToEndOfRow;
+      if (wavefrontTileBoundingCtuAddrSlice < boundingCtuTSAddrSlice)
+      {
+        boundingCtuTSAddrSlice = wavefrontTileBoundingCtuAddrSlice;
+      }
+    }
+
+    if (tileBoundingCtuTsAddrSlice < boundingCtuTSAddrSlice)
+    {
+      boundingCtuTSAddrSlice = tileBoundingCtuTsAddrSlice;
+      haveReachedTileBoundary = true;
+    }
+  }
+  else if ((sliceMode == FIXED_NUMBER_OF_CTU || sliceMode == FIXED_NUMBER_OF_BYTES) && wavefrontsAreEnabled && ((startCtuTSAddrSlice % pcPic->getFrameWidthInCtus()) != 0))
+  {
+    // Adjust for wavefronts (no tiles).
     // WPP: if a slice does not start at the beginning of a CTB row, it must end within the same CTB row
-    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
-    {
-      uiBoundingCUAddrSlice = min(uiBoundingCUAddrSlice, uiStartCUAddrSlice - (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()));
-    }
-    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
-  }
-  else
-  {
-    UInt uiCUAddrIncrement     ;
-    switch (m_pcCfg->getSliceMode())
-    {
-    case FIXED_NUMBER_OF_LCU:
-      uiCUAddrIncrement        = m_pcCfg->getSliceArgument();
-      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    case FIXED_NUMBER_OF_TILES:
-      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
-        rpcPic->getPicSym()->getCUOrderMap(uiStartCUAddrSlice/rpcPic->getNumPartInCU())
-        );
-      uiCUAddrIncrement        = 0;
-      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
-
-      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceArgument(); tileIdxIncrement++)
-      {
-        if((tileIdx + tileIdxIncrement) < tileTotalCount)
-        {
-          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
-          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
-          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
-        }
-      }
-
-      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    default:
-      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
-      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    } 
-    // WPP: if a slice does not start at the beginning of a CTB row, it must end within the same CTB row
-    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
-    {
-      uiBoundingCUAddrSlice = min(uiBoundingCUAddrSlice, uiStartCUAddrSlice - (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()));
-    }
-    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
-  }
-
-  Bool tileBoundary = false;
-  if ((m_pcCfg->getSliceMode() == FIXED_NUMBER_OF_LCU || m_pcCfg->getSliceMode() == FIXED_NUMBER_OF_BYTES) && 
-      (m_pcCfg->getNumRowsMinus1() > 0 || m_pcCfg->getNumColumnsMinus1() > 0))
-  {
-    UInt lcuEncAddr = (uiStartCUAddrSlice+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
-    UInt lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
-    UInt startTileIdx = rpcPic->getPicSym()->getTileIdxMap(lcuAddr);
-    UInt tileBoundingCUAddrSlice = 0;
-    while (lcuEncAddr < uiNumberOfCUsInFrame && rpcPic->getPicSym()->getTileIdxMap(lcuAddr) == startTileIdx)
-    {
-      lcuEncAddr++;
-      lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
-    }
-    tileBoundingCUAddrSlice = lcuEncAddr*rpcPic->getNumPartInCU();
-    
-    if (tileBoundingCUAddrSlice < uiBoundingCUAddrSlice)
-    {
-      uiBoundingCUAddrSlice = tileBoundingCUAddrSlice;
-      pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
-      tileBoundary = true;
-    }
-  }
+    boundingCtuTSAddrSlice = min(boundingCtuTSAddrSlice, startCtuTSAddrSlice - (startCtuTSAddrSlice % pcPic->getFrameWidthInCtus()) + (pcPic->getFrameWidthInCtus()));
+  }
+}
+
+/** Determines the starting and bounding CTU address of current slice / dependent slice
+ * \param [out] startCtuTsAddr
+ * \param [out] boundingCtuTsAddr
+ * \param [in]  pcPic
+
+ * Updates startCtuTsAddr, boundingCtuTsAddr with appropriate CTU address
+ */
+Void TEncSlice::xDetermineStartAndBoundingCtuTsAddr  ( UInt& startCtuTsAddr, UInt& boundingCtuTsAddr, TComPic* pcPic )
+{
+  TComSlice* pcSlice                 = pcPic->getSlice(getSliceIdx());
+
+  // Non-dependent slice
+  UInt startCtuTsAddrSlice           = pcSlice->getSliceCurStartCtuTsAddr();
+  Bool haveReachedTileBoundarySlice  = false;
+  UInt boundingCtuTsAddrSlice;
+  calculateBoundingCtuTsAddrForSlice(startCtuTsAddrSlice, boundingCtuTsAddrSlice, haveReachedTileBoundarySlice, pcPic,
+                                     m_pcCfg->getSliceMode(), m_pcCfg->getSliceArgument());
+  pcSlice->setSliceCurEndCtuTsAddr(   boundingCtuTsAddrSlice );
+  pcSlice->setSliceCurStartCtuTsAddr( startCtuTsAddrSlice    );
 
   // Dependent slice
-  UInt startCUAddrSliceSegment, boundingCUAddrSliceSegment;
-  startCUAddrSliceSegment    = pcSlice->getSliceSegmentCurStartCUAddr();
-  boundingCUAddrSliceSegment = uiNumberOfCUsInFrame;
-  if (bEncodeSlice) 
-  {
-    UInt uiCUAddrIncrement;
-    switch (m_pcCfg->getSliceSegmentMode())
-    {
-    case FIXED_NUMBER_OF_LCU:
-      uiCUAddrIncrement               = m_pcCfg->getSliceSegmentArgument();
-      boundingCUAddrSliceSegment    = ((startCUAddrSliceSegment + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (startCUAddrSliceSegment + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    case FIXED_NUMBER_OF_BYTES:
-      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
-      boundingCUAddrSliceSegment    = pcSlice->getSliceSegmentCurEndCUAddr();
-      break;
-    case FIXED_NUMBER_OF_TILES:
-      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
-        rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceSegmentCurStartCUAddr()/rpcPic->getNumPartInCU())
-        );
-      uiCUAddrIncrement        = 0;
-      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
-
-      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceSegmentArgument(); tileIdxIncrement++)
-      {
-        if((tileIdx + tileIdxIncrement) < tileTotalCount)
-        {
-          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
-          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
-          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
-        }
-      }
-      boundingCUAddrSliceSegment    = ((startCUAddrSliceSegment + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (startCUAddrSliceSegment + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    default:
-      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
-      boundingCUAddrSliceSegment    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    } 
-    // WPP: if a slice segment does not start at the beginning of a CTB row, it must end within the same CTB row
-    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (startCUAddrSliceSegment % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
-    {
-      boundingCUAddrSliceSegment = min(boundingCUAddrSliceSegment, startCUAddrSliceSegment - (startCUAddrSliceSegment % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()));
-    }
-    pcSlice->setSliceSegmentCurEndCUAddr( boundingCUAddrSliceSegment );
-  }
-  else
-  {
-    UInt uiCUAddrIncrement;
-    switch (m_pcCfg->getSliceSegmentMode())
-    {
-    case FIXED_NUMBER_OF_LCU:
-      uiCUAddrIncrement               = m_pcCfg->getSliceSegmentArgument();
-      boundingCUAddrSliceSegment    = ((startCUAddrSliceSegment + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (startCUAddrSliceSegment + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    case FIXED_NUMBER_OF_TILES:
-      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
-        rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceSegmentCurStartCUAddr()/rpcPic->getNumPartInCU())
-        );
-      uiCUAddrIncrement        = 0;
-      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
-
-      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceSegmentArgument(); tileIdxIncrement++)
-      {
-        if((tileIdx + tileIdxIncrement) < tileTotalCount)
-        {
-          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
-          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
-          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
-        }
-      }
-      boundingCUAddrSliceSegment    = ((startCUAddrSliceSegment + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (startCUAddrSliceSegment + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    default:
-      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
-      boundingCUAddrSliceSegment    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
-      break;
-    } 
-    // WPP: if a slice segment does not start at the beginning of a CTB row, it must end within the same CTB row
-    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (startCUAddrSliceSegment % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
-    {
-      boundingCUAddrSliceSegment = min(boundingCUAddrSliceSegment, startCUAddrSliceSegment - (startCUAddrSliceSegment % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()));
-    }
-    pcSlice->setSliceSegmentCurEndCUAddr( boundingCUAddrSliceSegment );
-  }
-  if ((m_pcCfg->getSliceSegmentMode() == FIXED_NUMBER_OF_LCU || m_pcCfg->getSliceSegmentMode() == FIXED_NUMBER_OF_BYTES) && 
-    (m_pcCfg->getNumRowsMinus1() > 0 || m_pcCfg->getNumColumnsMinus1() > 0))
-  {
-    UInt lcuEncAddr = (startCUAddrSliceSegment+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
-    UInt lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
-    UInt startTileIdx = rpcPic->getPicSym()->getTileIdxMap(lcuAddr);
-    UInt tileBoundingCUAddrSlice = 0;
-    while (lcuEncAddr < uiNumberOfCUsInFrame && rpcPic->getPicSym()->getTileIdxMap(lcuAddr) == startTileIdx)
-    {
-      lcuEncAddr++;
-      lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
-    }
-    tileBoundingCUAddrSlice = lcuEncAddr*rpcPic->getNumPartInCU();
-
-    if (tileBoundingCUAddrSlice < boundingCUAddrSliceSegment)
-    {
-      boundingCUAddrSliceSegment = tileBoundingCUAddrSlice;
-      pcSlice->setSliceSegmentCurEndCUAddr( boundingCUAddrSliceSegment );
-      tileBoundary = true;
-    }
-  }
-
-  if(boundingCUAddrSliceSegment>uiBoundingCUAddrSlice)
-  {
-    boundingCUAddrSliceSegment = uiBoundingCUAddrSlice;
-    pcSlice->setSliceSegmentCurEndCUAddr(uiBoundingCUAddrSlice);
-  }
-
-  //calculate real dependent slice start address
-  UInt uiInternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurStartCUAddr()) % rpcPic->getNumPartInCU();
-  UInt uiExternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurStartCUAddr()) / rpcPic->getNumPartInCU();
-  UInt uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-  UInt uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
-  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
-  while((uiPosX>=uiWidth||uiPosY>=uiHeight)&&!(uiPosX>=uiWidth&&uiPosY>=uiHeight))
-  {
-    uiInternalAddress++;
-    if(uiInternalAddress>=rpcPic->getNumPartInCU())
-    {
-      uiInternalAddress=0;
-      uiExternalAddress = rpcPic->getPicSym()->getCUOrderMap(rpcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
-    }
-    uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-    uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-  }
-  UInt uiRealStartAddress = rpcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*rpcPic->getNumPartInCU()+uiInternalAddress);
-  
-  pcSlice->setSliceSegmentCurStartCUAddr(uiRealStartAddress);
-  startCUAddrSliceSegment=uiRealStartAddress;
-  
-  //calculate real slice start address
-  uiInternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceCurStartCUAddr()) % rpcPic->getNumPartInCU();
-  uiExternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceCurStartCUAddr()) / rpcPic->getNumPartInCU();
-  uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-  uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-  uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
-  uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
-  while((uiPosX>=uiWidth||uiPosY>=uiHeight)&&!(uiPosX>=uiWidth&&uiPosY>=uiHeight))
-  {
-    uiInternalAddress++;
-    if(uiInternalAddress>=rpcPic->getNumPartInCU())
-    {
-      uiInternalAddress=0;
-      uiExternalAddress = rpcPic->getPicSym()->getCUOrderMap(rpcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
-    }
-    uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
-    uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
-  }
-  uiRealStartAddress = rpcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*rpcPic->getNumPartInCU()+uiInternalAddress);
-  
-  pcSlice->setSliceCurStartCUAddr(uiRealStartAddress);
-  uiStartCUAddrSlice=uiRealStartAddress;
-  
+  UInt startCtuTsAddrSliceSegment          = pcSlice->getSliceSegmentCurStartCtuTsAddr();
+  Bool haveReachedTileBoundarySliceSegment = false;
+  UInt boundingCtuTsAddrSliceSegment;
+  calculateBoundingCtuTsAddrForSlice(startCtuTsAddrSliceSegment, boundingCtuTsAddrSliceSegment, haveReachedTileBoundarySliceSegment, pcPic,
+                                     m_pcCfg->getSliceSegmentMode(), m_pcCfg->getSliceSegmentArgument());
+  if (boundingCtuTsAddrSliceSegment>boundingCtuTsAddrSlice)
+  {
+    boundingCtuTsAddrSliceSegment = boundingCtuTsAddrSlice;
+  }
+  pcSlice->setSliceSegmentCurEndCtuTsAddr( boundingCtuTsAddrSliceSegment );
+  pcSlice->setSliceSegmentCurStartCtuTsAddr(startCtuTsAddrSliceSegment);
+
   // Make a joint decision based on reconstruction and dependent slice bounds
-  startCUAddr    = max(uiStartCUAddrSlice   , startCUAddrSliceSegment   );
-  boundingCUAddr = min(uiBoundingCUAddrSlice, boundingCUAddrSliceSegment);
-
-
-  if (!bEncodeSlice)
-  {
-    // For fixed number of LCU within an entropy and reconstruction slice we already know whether we will encounter end of entropy and/or reconstruction slice
-    // first. Set the flags accordingly.
-    if ( (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU)
-      || (m_pcCfg->getSliceMode()==0 && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU)
-      || (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU && m_pcCfg->getSliceSegmentMode()==0) 
-      || (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_TILES && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU)
-      || (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_TILES && m_pcCfg->getSliceSegmentMode()==0) 
-      || (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_TILES && m_pcCfg->getSliceMode()==0)
-      || tileBoundary
-)
-    {
-      if (uiBoundingCUAddrSlice < boundingCUAddrSliceSegment)
-      {
-        pcSlice->setNextSlice       ( true );
-        pcSlice->setNextSliceSegment( false );
-      }
-      else if (uiBoundingCUAddrSlice > boundingCUAddrSliceSegment)
-      {
-        pcSlice->setNextSlice       ( false );
-        pcSlice->setNextSliceSegment( true );
-      }
-      else
-      {
-        pcSlice->setNextSlice       ( true );
-        pcSlice->setNextSliceSegment( true );
-      }
-    }
-    else
-    {
-      pcSlice->setNextSlice       ( false );
-      pcSlice->setNextSliceSegment( false );
-    }
-  }
+  startCtuTsAddr    = max(startCtuTsAddrSlice   , startCtuTsAddrSliceSegment   );
+  boundingCtuTsAddr = boundingCtuTsAddrSliceSegment;
 }
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSlice.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncSlice.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -65,31 +65,29 @@
   // encoder configuration
   TEncCfg*                m_pcCfg;                              ///< encoder configuration class
-  
+
   // pictures
   TComList<TComPic*>*     m_pcListPic;                          ///< list of pictures
   TComPicYuv*             m_apcPicYuvPred;                      ///< prediction picture buffer
   TComPicYuv*             m_apcPicYuvResi;                      ///< residual picture buffer
-  
+
   // processing units
   TEncGOP*                m_pcGOPEncoder;                       ///< GOP encoder
   TEncCu*                 m_pcCuEncoder;                        ///< CU encoder
-  
+
   // encoder search
   TEncSearch*             m_pcPredSearch;                       ///< encoder search class
-  
+
   // coding tools
   TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
-  TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder
   TEncSbac*               m_pcSbacCoder;                        ///< SBAC encoder
   TEncBinCABAC*           m_pcBinCABAC;                         ///< Bin encoder CABAC
   TComTrQuant*            m_pcTrQuant;                          ///< transform & quantization
-  
+
   // RD optimization
-  TComBitCounter*         m_pcBitCounter;                       ///< bit counter
   TComRdCost*             m_pcRdCost;                           ///< RD cost computation
   TEncSbac***             m_pppcRDSbacCoder;                    ///< storage for SBAC-based RD optimization
   TEncSbac*               m_pcRDGoOnSbacCoder;                  ///< go-on SBAC encoder
   UInt64                  m_uiPicTotalBits;                     ///< total bits for the picture
-#if H_3D_VSO
+#if NH_3D_VSO
   Dist64                  m_uiPicDist;                          ///< total distortion for the picture
 #else
@@ -100,44 +98,45 @@
   Double*                 m_pdRdPicQp;                          ///< array of picture QP candidates (double-type for lambda)
   Int*                    m_piRdPicQp;                          ///< array of picture QP candidates (Int-type)
-  TEncBinCABAC*           m_pcBufferBinCoderCABACs;       ///< line of bin coder CABAC
-  TEncSbac*               m_pcBufferSbacCoders;                 ///< line to store temporary contexts
-  TEncBinCABAC*           m_pcBufferLowLatBinCoderCABACs;       ///< dependent tiles: line of bin coder CABAC
-  TEncSbac*               m_pcBufferLowLatSbacCoders;           ///< dependent tiles: line to store temporary contexts
   TEncRateCtrl*           m_pcRateCtrl;                         ///< Rate control manager
   UInt                    m_uiSliceIdx;
-  std::vector<TEncSbac*> CTXMem;
+  TEncSbac                m_lastSliceSegmentEndContextState;    ///< context storage for state at the end of the previous slice-segment (used for dependent slices only).
+  TEncSbac                m_entropyCodingSyncContextState;      ///< context storate for state of contexts at the wavefront/WPP/entropy-coding-sync second CTU of tile-row
+  SliceType               m_encCABACTableIdx;
+
+  Void     setUpLambda(TComSlice* slice, const Double dLambda, Int iQP);
+  Void     calculateBoundingCtuTsAddrForSlice(UInt &startCtuTSAddrSlice, UInt &boundingCtuTSAddrSlice, Bool &haveReachedTileBoundary, TComPic* pcPic, const Int sliceMode, const Int sliceArgument);
+
 public:
   TEncSlice();
   virtual ~TEncSlice();
-  
-  Void    create              ( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth );
+
+  Void    create              ( Int iWidth, Int iHeight, ChromaFormat chromaFormat, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth );
   Void    destroy             ();
   Void    init                ( TEncTop* pcEncTop );
-  
+
   /// preparation of slice encoding (reference marking, QP and lambda)
-#if H_MV
-  Void    initEncSlice        ( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, 
-                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId, bool isField  ); 
+#if NH_MV
+  Void    initEncSlice        ( TComPic* pcPic, Int pocLast, Int pocCurr, 
+                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, Int layerId, bool isField  ); 
 #else
-  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
-                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField  );
+  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, 
+                                Int iGOPid,   TComSlice*& rpcSlice, Bool isField );
 #endif
   Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
   // compress and encode slice
-  Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
-  Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
-  Void    calCostSliceI       ( TComPic*& rpcPic );
-  Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams  );
-  
+  Void    precompressSlice    ( TComPic* pcPic                                     );      ///< precompress slice for multi-loop slice-level QP opt.
+  Void    compressSlice       ( TComPic* pcPic, const Bool bCompressEntireSlice    );      ///< analysis stage of slice
+  Void    calCostSliceI       ( TComPic* pcPic );
+  Void    encodeSlice         ( TComPic* pcPic, TComOutputBitstream* pcSubstreams, UInt &numBinsCoded );
+
   // misc. functions
   Void    setSearchRange      ( TComSlice* pcSlice  );                                  ///< set ME range adaptively
-  UInt64  getTotalBits        ()  { return m_uiPicTotalBits; }
-  
+
   TEncCu*        getCUEncoder() { return m_pcCuEncoder; }                        ///< CU encoder
-  Void    xDetermineStartAndBoundingCUAddr  ( UInt& uiStartCUAddr, UInt& uiBoundingCUAddr, TComPic*& rpcPic, Bool bEncodeSlice );
+  Void    xDetermineStartAndBoundingCtuTsAddr  ( UInt& startCtuTsAddr, UInt& boundingCtuTsAddr, TComPic* pcPic );
   UInt    getSliceIdx()         { return m_uiSliceIdx;                    }
   Void    setSliceIdx(UInt i)   { m_uiSliceIdx = i;                       }
-  Void      initCtxMem( UInt i );
-  Void      setCtxMem( TEncSbac* sb, Int b )   { CTXMem[b] = sb; }
+
+  SliceType getEncCABACTableIdx() const           { return m_encCABACTableIdx;        }
 
 private:
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,8 +39,9 @@
 #include "TEncTop.h"
 #include "TEncPic.h"
+#include "TLibCommon/TComChromaFormat.h"
 #if FAST_BIT_EST
 #include "TLibCommon/ContextModel.h"
 #endif
-#if H_MV
+#if NH_MV
 #include "../../App/TAppEncoder/TAppEncTop.h"
 #endif
@@ -62,5 +63,8 @@
   m_cRDGoOnSbacCoder.init( &m_cRDGoOnBinCoderCABAC );
 #if ENC_DEC_TRACE
-  g_hTrace = fopen( "TraceEnc.txt", "wb" );
+  if (g_hTrace == NULL)
+  {
+    g_hTrace = fopen( "TraceEnc.txt", "wb" );
+  }
   g_bJustDoIt = g_bEncDecTraceDisable;
   g_nSymbolCounter = 0;
@@ -72,17 +76,5 @@
   ContextModel::buildNextStateTable();
 #endif
-#if H_MV
-  m_iNumSubstreams         = 0; 
-#endif
-
-  m_pcSbacCoders           = NULL;
-  m_pcBinCoderCABACs       = NULL;
-  m_ppppcRDSbacCoders      = NULL;
-  m_ppppcBinCodersCABAC    = NULL;
-  m_pcRDGoOnSbacCoders     = NULL;
-  m_pcRDGoOnBinCodersCABAC = NULL;
-  m_pcBitCounters          = NULL;
-  m_pcRdCosts              = NULL;
-#if H_MV
+#if NH_MV
   m_ivPicLists = NULL;
 #endif
@@ -91,7 +83,8 @@
   m_aICEnableNum = NULL;
 #endif
-#if H_3D
+#if NH_3D
   m_cCavlcCoder.setEncTop(this); 
 #endif
+
 }
 
@@ -99,5 +92,8 @@
 {
 #if ENC_DEC_TRACE
-  fclose( g_hTrace );
+  if (g_hTrace != stdout)
+  {
+    fclose( g_hTrace );
+  }
 #endif
 }
@@ -105,21 +101,17 @@
 Void TEncTop::create ()
 {
-#if !H_MV
+#if !NH_MV
   // initialize global variables
   initROM();
 #endif
-  
+
   // create processing unit classes
-  m_cGOPEncoder.        create();
-  m_cSliceEncoder.      create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
-  m_cCuEncoder.         create( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight );
+  m_cGOPEncoder.        create( );
+  m_cSliceEncoder.      create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth );
+  m_cCuEncoder.         create( m_maxTotalCUDepth, m_maxCUWidth, m_maxCUHeight, m_chromaFormatIDC );
   if (m_bUseSAO)
   {
-    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
-#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
-    m_cEncSAO.createEncData(getSaoLcuBoundary());
-#else
-    m_cEncSAO.createEncData();
-#endif
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth, m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA], m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA] );
+    m_cEncSAO.createEncData(getSaoCtuBoundary());
   }
 #if ADAPTIVE_QP_SELECTION
@@ -129,5 +121,6 @@
   }
 #endif
-  m_cLoopFilter.        create( g_uiMaxCUDepth );
+
+  m_cLoopFilter.create( m_maxTotalCUDepth );
 
   if ( m_RCEnableRateControl )
@@ -138,83 +131,36 @@
 #else
     m_cRateCtrl.init( m_framesToBeEncoded, m_RCTargetBitrate, m_iFrameRate, m_iGOPSize, m_iSourceWidth, m_iSourceHeight,
-                      g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
-#endif
-  }
-    m_pppcRDSbacCoder = new TEncSbac** [g_uiMaxCUDepth+1];
+        m_maxCUWidth, m_maxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
+#endif
+  }
+
+  m_pppcRDSbacCoder = new TEncSbac** [m_maxTotalCUDepth+1];
 #if FAST_BIT_EST
-    m_pppcBinCoderCABAC = new TEncBinCABACCounter** [g_uiMaxCUDepth+1];
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter** [m_maxTotalCUDepth+1];
 #else
-    m_pppcBinCoderCABAC = new TEncBinCABAC** [g_uiMaxCUDepth+1];
-#endif
-    
-    for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-    {
-      m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
+  m_pppcBinCoderCABAC = new TEncBinCABAC** [m_maxTotalCUDepth+1];
+#endif
+
+  for ( Int iDepth = 0; iDepth < m_maxTotalCUDepth+1; iDepth++ )
+  {
+    m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
 #if FAST_BIT_EST
-      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
+    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
 #else
-      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
-#endif
-      
-      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-      {
-        m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
+    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
+#endif
+
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
 #if FAST_BIT_EST
-        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
 #else
-        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
-#endif
-        m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
-      }
-    }
-  }
-
-/**
- - Allocate coders required for wavefront for the nominated number of substreams.
- .
- \param iNumSubstreams Determines how much information to allocate.
- */
-Void TEncTop::createWPPCoders(Int iNumSubstreams)
-{
-  if (m_pcSbacCoders != NULL)
-  {
-    return; // already generated.
-  }
-
-  m_iNumSubstreams         = iNumSubstreams;
-  m_pcSbacCoders           = new TEncSbac       [iNumSubstreams];
-  m_pcBinCoderCABACs       = new TEncBinCABAC   [iNumSubstreams];
-  m_pcRDGoOnSbacCoders     = new TEncSbac       [iNumSubstreams];
-  m_pcRDGoOnBinCodersCABAC = new TEncBinCABAC   [iNumSubstreams];
-  m_pcBitCounters          = new TComBitCounter [iNumSubstreams];
-  m_pcRdCosts              = new TComRdCost     [iNumSubstreams];
-
-  for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
-  {
-    m_pcRDGoOnSbacCoders[ui].init( &m_pcRDGoOnBinCodersCABAC[ui] );
-    m_pcSbacCoders[ui].init( &m_pcBinCoderCABACs[ui] );
-  }
-
-    m_ppppcRDSbacCoders      = new TEncSbac***    [iNumSubstreams];
-    m_ppppcBinCodersCABAC    = new TEncBinCABAC***[iNumSubstreams];
-    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ )
-    {
-      m_ppppcRDSbacCoders[ui]  = new TEncSbac** [g_uiMaxCUDepth+1];
-      m_ppppcBinCodersCABAC[ui]= new TEncBinCABAC** [g_uiMaxCUDepth+1];
-      
-      for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-      {
-        m_ppppcRDSbacCoders[ui][iDepth]  = new TEncSbac*     [CI_NUM];
-        m_ppppcBinCodersCABAC[ui][iDepth]= new TEncBinCABAC* [CI_NUM];
-
-        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-        {
-          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx] = new TEncSbac;
-          m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] = new TEncBinCABAC;
-          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx]->init( m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] );
-        }
-      }
-    }
-  }
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+#endif
+      m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
+    }
+  }
+}
 
 Void TEncTop::destroy ()
@@ -224,103 +170,29 @@
   m_cSliceEncoder.      destroy();
   m_cCuEncoder.         destroy();
-  if (m_cSPS.getUseSAO())
-  {
-    m_cEncSAO.destroyEncData();
-    m_cEncSAO.destroy();
-  }
+  m_cEncSAO.            destroyEncData();
+  m_cEncSAO.            destroy();
   m_cLoopFilter.        destroy();
   m_cRateCtrl.          destroy();
-
-    Int iDepth;
-    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-    {
-      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-      {
-#if H_MV
-        xDelete( false, m_pppcRDSbacCoder, iDepth, iCIIdx);
-        xDelete( false, m_pppcBinCoderCABAC, iDepth, iCIIdx);
-#else
-        delete m_pppcRDSbacCoder[iDepth][iCIIdx];
-        delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
-#endif
-      }
-    }
-    
-    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-    {
-#if H_MV
-      xDelete( true, m_pppcRDSbacCoder  , iDepth);
-      xDelete( true, m_pppcBinCoderCABAC, iDepth);
-#else
-      delete [] m_pppcRDSbacCoder[iDepth];
-      delete [] m_pppcBinCoderCABAC[iDepth];
-#endif
-    }
-
-#if H_MV
-     xDelete( true, m_pppcRDSbacCoder  );
-     xDelete( true, m_pppcBinCoderCABAC);
-#else
-    delete [] m_pppcRDSbacCoder;
-    delete [] m_pppcBinCoderCABAC;
-#endif
-    for ( UInt ui = 0; ui < m_iNumSubstreams; ui++ )
-    {
-      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-      {
-        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-        {
-#if H_MV
-          xDelete(false, m_ppppcRDSbacCoders  ,ui, iDepth, iCIIdx);
-          xDelete(false, m_ppppcBinCodersCABAC,ui, iDepth, iCIIdx);
-#else
-          delete m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx];
-          delete m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx];
-#endif
-        }
-      }
-
-      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-      {
-#if H_MV
-        xDelete(true, m_ppppcRDSbacCoders  ,ui, iDepth);
-        xDelete(true, m_ppppcBinCodersCABAC,ui, iDepth);        
-#else
-        delete [] m_ppppcRDSbacCoders  [ui][iDepth];
-        delete [] m_ppppcBinCodersCABAC[ui][iDepth];
-#endif
-      }
-
-
-#if H_MV
-      xDelete(true, m_ppppcRDSbacCoders,   ui);
-      xDelete(true, m_ppppcBinCodersCABAC, ui);      
-#else
-      delete[] m_ppppcRDSbacCoders  [ui];
-      delete[] m_ppppcBinCodersCABAC[ui];
-#endif
-    }
-#if H_MV
-    xDelete(true, m_ppppcRDSbacCoders    ) ;
-    xDelete(true, m_ppppcBinCodersCABAC);
-    xDelete(true, m_pcSbacCoders);
-    xDelete(true, m_pcBinCoderCABACs);
-    xDelete(true, m_pcRDGoOnSbacCoders);  
-    xDelete(true, m_pcRDGoOnBinCodersCABAC);
-    xDelete(true, m_pcBitCounters);
-    xDelete(true, m_pcRdCosts);
-#else
-    delete[] m_ppppcRDSbacCoders;
-    delete[] m_ppppcBinCodersCABAC;
-  delete[] m_pcSbacCoders;
-  delete[] m_pcBinCoderCABACs;
-  delete[] m_pcRDGoOnSbacCoders;  
-  delete[] m_pcRDGoOnBinCodersCABAC;
-  delete[] m_pcBitCounters;
-  delete[] m_pcRdCosts;
-#endif
-
-#if !H_MV
-    // destroy ROM
+  Int iDepth;
+  for ( iDepth = 0; iDepth < m_maxTotalCUDepth+1; iDepth++ )
+  {
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+      delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+    }
+  }
+
+  for ( iDepth = 0; iDepth < m_maxTotalCUDepth+1; iDepth++ )
+  {
+    delete [] m_pppcRDSbacCoder[iDepth];
+    delete [] m_pppcBinCoderCABAC[iDepth];
+  }
+
+  delete [] m_pppcRDSbacCoder;
+  delete [] m_pppcBinCoderCABAC;
+
+#if !NH_MV
+  // destroy ROM
   destroyROM();
 #endif
@@ -341,16 +213,14 @@
 #endif
   xInitSPS();
-  
-  /* set the VPS profile information */
-#if H_MV
+  xInitVPS();
+
+  m_cRdCost.setCostMode(m_costMode);
+
+#if NH_MV
   // This seems to be incorrect, but irrelevant for the MV-HEVC
   *(m_cVPS->getPTL()) = *m_cSPS.getPTL();
   m_cVPS->getTimingInfo()->setTimingInfoPresentFlag       ( false );
-#else
-  *m_cVPS.getPTL() = *m_cSPS.getPTL();
-  m_cVPS.getTimingInfo()->setTimingInfoPresentFlag       ( false );
 #endif
   // initialize PPS
-  m_cPPS.setSPS(&m_cSPS);
   xInitPPS();
   xInitRPS(isFieldCoding);
@@ -372,5 +242,5 @@
   m_cSliceEncoder.init( this );
   m_cCuEncoder.   init( this );
-  
+
 #if KWU_RC_MADPRED_E0227
   m_pcTAppEncTop = pcTAppEncTop;
@@ -378,19 +248,85 @@
   // initialize transform & quantization class
   m_pcCavlcCoder = getCavlcCoder();
-  
+
   m_cTrQuant.init( 1 << m_uiQuadtreeTULog2MaxSize,
-                  m_useRDOQ, 
-                  m_useRDOQTS,
-                  true 
+                   m_useRDOQ,
+                   m_useRDOQTS,
+#if T0196_SELECTIVE_RDOQ
+                   m_useSelectiveRDOQ,
+#endif
+                   true
                   ,m_useTransformSkipFast
-#if ADAPTIVE_QP_SELECTION                  
-                  , m_bUseAdaptQpSelect
+#if ADAPTIVE_QP_SELECTION
+                  ,m_bUseAdaptQpSelect
 #endif
                   );
-  
+
   // initialize encoder search class
-  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_iFastSearch, 0, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
+  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_iFastSearch, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
 
   m_iMaxRefPicNum = 0;
+
+  xInitScalingLists();
+}
+
+Void TEncTop::xInitScalingLists()
+{
+  // Initialise scaling lists
+  // The encoder will only use the SPS scaling lists. The PPS will never be marked present.
+  const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE] =
+  {
+      m_cSPS.getMaxLog2TrDynamicRange(CHANNEL_TYPE_LUMA),
+      m_cSPS.getMaxLog2TrDynamicRange(CHANNEL_TYPE_CHROMA)
+  };
+  if(getUseScalingListId() == SCALING_LIST_OFF)
+  {
+    getTrQuant()->setFlatScalingList(maxLog2TrDynamicRange, m_cSPS.getBitDepths());
+    getTrQuant()->setUseScalingList(false);
+    m_cSPS.setScalingListPresentFlag(false);
+    m_cPPS.setScalingListPresentFlag(false);
+  }
+  else if(getUseScalingListId() == SCALING_LIST_DEFAULT)
+  {
+    m_cSPS.getScalingList().setDefaultScalingList ();
+    m_cSPS.setScalingListPresentFlag(false);
+    m_cPPS.setScalingListPresentFlag(false);
+
+    getTrQuant()->setScalingList(&(m_cSPS.getScalingList()), maxLog2TrDynamicRange, m_cSPS.getBitDepths());
+    getTrQuant()->setUseScalingList(true);
+  }
+  else if(getUseScalingListId() == SCALING_LIST_FILE_READ)
+  {
+    m_cSPS.getScalingList().setDefaultScalingList ();
+    if(m_cSPS.getScalingList().xParseScalingList(getScalingListFile()))
+    {
+      Bool bParsedScalingList=false; // Use of boolean so that assertion outputs useful string
+      assert(bParsedScalingList);
+      exit(1);
+    }
+    m_cSPS.getScalingList().checkDcOfMatrix();
+    m_cSPS.setScalingListPresentFlag(m_cSPS.getScalingList().checkDefaultScalingList());
+    m_cPPS.setScalingListPresentFlag(false);
+    getTrQuant()->setScalingList(&(m_cSPS.getScalingList()), maxLog2TrDynamicRange, m_cSPS.getBitDepths());
+    getTrQuant()->setUseScalingList(true);
+  }
+  else
+  {
+    printf("error : ScalingList == %d not supported\n",getUseScalingListId());
+    assert(0);
+  }
+
+  if (getUseScalingListId() != SCALING_LIST_OFF)
+  {  
+    // Prepare delta's:
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    const Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
+
+    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId+=predListStep)
+    {
+      m_cSPS.getScalingList().checkPredMode( sizeId, listId );
+    }
+  }
+  }
 }
 
@@ -399,5 +335,5 @@
 // ====================================================================================================================
 
-#if H_MV
+#if NH_MV
 Void TEncTop::initNewPic( TComPicYuv* pcPicYuvOrg )
 {
@@ -413,21 +349,22 @@
     m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
   }
-#if H_MV
+#if NH_MV
   pcPicCurr->setLayerId( getLayerId()); 
 #endif
-#if H_3D
+#if NH_3D
   pcPicCurr->setScaleOffset( m_cameraParameters->getCodedScale(), m_cameraParameters->getCodedOffset() );
 #endif
 }
 #endif
+
 Void TEncTop::deletePicBuffer()
 {
   TComList<TComPic*>::iterator iterPic = m_cListPic.begin();
   Int iSize = Int( m_cListPic.size() );
-  
+
   for ( Int i = 0; i < iSize; i++ )
   {
     TComPic* pcPic = *(iterPic++);
-    
+
     pcPic->destroy();
     delete pcPic;
@@ -443,16 +380,18 @@
  \param   flush               cause encoder to encode a partial GOP
  \param   pcPicYuvOrg         original YUV picture
+ \param   pcPicYuvTrueOrg     
+ \param   snrCSC
  \retval  rcListPicYuvRecOut  list of reconstruction YUV pictures
- \retval  rcListBitstreamOut  list of output bitstreams
+ \retval  accessUnitsOut      list of output access units
  \retval  iNumEncoded         number of encoded pictures
  */
-#if H_MV
-Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded , Int gopId )
+#if NH_MV
+Void TEncTop::encode( Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Int gopId )
 {
 #else
-Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded )
-{
-#endif
-#if H_3D
+Void TEncTop::encode( Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded )
+{
+#endif
+#if NH_3D
   TComPic* picLastCoded = getPic( getGOPEncoder()->getPocLastCoded() );
   if( picLastCoded )
@@ -461,14 +400,17 @@
   }
 #endif
-#if H_MV
+#if NH_MV
   if( gopId == 0)
   {
     m_cGOPEncoder.initGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);  
 #else
-  if (pcPicYuvOrg) {
+  if (pcPicYuvOrg != NULL)
+  {
     // get original YUV
     TComPic* pcPicCurr = NULL;
+
     xGetNewPicBuffer( pcPicCurr );
     pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+    pcPicYuvTrueOrg->copyToPic( pcPicCurr->getPicYuvTrueOrg() );
 
     // compute image characteristics
@@ -478,6 +420,6 @@
     }
   }
-  
-  if (!m_iNumPicRcvd || (!flush && m_iPOCLast != 0 && m_iNumPicRcvd != m_iGOPSize && m_iGOPSize))
+
+  if ((m_iNumPicRcvd == 0) || (!flush && (m_iPOCLast != 0) && (m_iNumPicRcvd != m_iGOPSize) && (m_iGOPSize != 0)))
   {
     iNumEncoded = 0;
@@ -485,12 +427,11 @@
   }
 #endif
-  
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
   }
-#if H_MV
-  }
-  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, gopId, false, false );
+#if NH_MV
+  }
+  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE, gopId);
 
   if( gopId + 1 == m_cGOPEncoder.getGOPSize() )
@@ -498,23 +439,23 @@
 #else
   // compress GOP
-  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
-#endif
-
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE);
+#endif
   if ( m_RCEnableRateControl )
   {
     m_cRateCtrl.destroyRCGOP();
   }
-  
+
   iNumEncoded         = m_iNumPicRcvd;
   m_iNumPicRcvd       = 0;
   m_uiNumAllPicCoded += iNumEncoded;
-#if H_MV
-}
-#endif
-}
+#if NH_MV
+}
+#endif
+}
+
 /**------------------------------------------------
  Separate interlaced frame into two fields
  -------------------------------------------------**/
-void separateFields(Pel* org, Pel* dstField, UInt stride, UInt width, UInt height, bool isTop)
+Void separateFields(Pel* org, Pel* dstField, UInt stride, UInt width, UInt height, Bool isTop)
 {
   if (!isTop)
@@ -528,138 +469,91 @@
       dstField[x] = org[x];
     }
-    
+
     dstField += stride;
     org += stride*2;
   }
-  
-}
-
-#if H_MV
-Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff, Int gopId )
+
+}
+#if NH_MV
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff, Int gopId )
 {
   assert( 0 ); // Field coding and multiview need to be further harmonized. 
 }
 #else
-Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff)
-{
-  /* -- TOP FIELD -- */
-  
-  if (pcPicYuvOrg)
-  {
-    
-    /* -- Top field initialization -- */
-    
-    TComPic *pcTopField;
-    xGetNewPicBuffer( pcTopField );
-    pcTopField->setReconMark (false);
-    
-    pcTopField->getSlice(0)->setPOC( m_iPOCLast );
-    pcTopField->getPicYuvRec()->setBorderExtension(false);
-    pcTopField->setTopField(isTff);
-    
-    int nHeight = pcPicYuvOrg->getHeight();
-    int nWidth = pcPicYuvOrg->getWidth();
-    int nStride = pcPicYuvOrg->getStride();
-    int nPadLuma = pcPicYuvOrg->getLumaMargin();
-    int nPadChroma = pcPicYuvOrg->getChromaMargin();
-    
-    // Get pointers
-    Pel * PicBufY = pcPicYuvOrg->getBufY();
-    Pel * PicBufU = pcPicYuvOrg->getBufU();
-    Pel * PicBufV = pcPicYuvOrg->getBufV();
-    
-    Pel * pcTopFieldY =  pcTopField->getPicYuvOrg()->getLumaAddr();
-    Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
-    Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
-    
-    /* -- Defield -- */
-    
-    bool isTop = isTff;
-    
-    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcTopFieldY, nStride, nWidth, nHeight, isTop);
-    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
-    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
-    
-    // compute image characteristics
-    if ( getUseAdaptiveQP() )
-    {
-      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
-    }    
-  }
-  
-  if (m_iPOCLast == 0) // compress field 0
-  {
-    m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
-  }
-  
-  /* -- BOTTOM FIELD -- */
-  
-  if (pcPicYuvOrg)
-  {
-    
-    /* -- Bottom field initialization -- */
-    
-    TComPic* pcBottomField;
-    xGetNewPicBuffer( pcBottomField );
-    pcBottomField->setReconMark (false);
-    
-    TComPicYuv* rpcPicYuvRec;
-    if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
-    {
-      rpcPicYuvRec = rcListPicYuvRecOut.popFront();
-    }
-    else
-    {
-      rpcPicYuvRec = new TComPicYuv;
-      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
-    }
-    rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
-    
-    pcBottomField->getSlice(0)->setPOC( m_iPOCLast);
-    pcBottomField->getPicYuvRec()->setBorderExtension(false);
-    pcBottomField->setTopField(!isTff);
-    
-    int nHeight = pcPicYuvOrg->getHeight();
-    int nWidth = pcPicYuvOrg->getWidth();
-    int nStride = pcPicYuvOrg->getStride();
-    int nPadLuma = pcPicYuvOrg->getLumaMargin();
-    int nPadChroma = pcPicYuvOrg->getChromaMargin();
-    
-    // Get pointers
-    Pel * PicBufY = pcPicYuvOrg->getBufY();
-    Pel * PicBufU = pcPicYuvOrg->getBufU();
-    Pel * PicBufV = pcPicYuvOrg->getBufV();
-    
-    Pel * pcBottomFieldY =  pcBottomField->getPicYuvOrg()->getLumaAddr();
-    Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
-    Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
-    
-    /* -- Defield -- */
-    
-    bool isTop = !isTff;
-    
-    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcBottomFieldY, nStride, nWidth, nHeight, isTop);
-    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
-    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
-    
-    // Compute image characteristics
-    if ( getUseAdaptiveQP() )
-    {
-      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
-    }    
-  }
-  
-  if ( ( !(m_iNumPicRcvd) || (!flush && m_iPOCLast != 1 && m_iNumPicRcvd != m_iGOPSize && m_iGOPSize)) )
-  {
-    iNumEncoded = 0;
-    return;
-  }
-  
-  // compress GOP
-  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
-  
-  iNumEncoded = m_iNumPicRcvd;
-  m_iNumPicRcvd = 0;
-  m_uiNumAllPicCoded += iNumEncoded;
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff)
+{
+  iNumEncoded = 0;
+
+  for (Int fieldNum=0; fieldNum<2; fieldNum++)
+  {
+    if (pcPicYuvOrg)
+    {
+
+      /* -- field initialization -- */
+      const Bool isTopField=isTff==(fieldNum==0);
+
+      TComPic *pcField;
+      xGetNewPicBuffer( pcField );
+      pcField->setReconMark (false);                     // where is this normally?
+
+      if (fieldNum==1)                                   // where is this normally?
+      {
+        TComPicYuv* rpcPicYuvRec;
+
+        // org. buffer
+        if ( rcListPicYuvRecOut.size() >= (UInt)m_iGOPSize+1 ) // need to maintain field 0 in list of RecOuts while processing field 1. Hence +1 on m_iGOPSize.
+        {
+          rpcPicYuvRec = rcListPicYuvRecOut.popFront();
+        }
+        else
+        {
+          rpcPicYuvRec = new TComPicYuv;
+          rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth, true);
+        }
+        rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
+      }
+
+      pcField->getSlice(0)->setPOC( m_iPOCLast );        // superfluous?
+      pcField->getPicYuvRec()->setBorderExtension(false);// where is this normally?
+
+      pcField->setTopField(isTopField);                  // interlaced requirement
+
+      for (UInt componentIndex = 0; componentIndex < pcPicYuvOrg->getNumberValidComponents(); componentIndex++)
+      {
+        const ComponentID component = ComponentID(componentIndex);
+        const UInt stride = pcPicYuvOrg->getStride(component);
+
+        separateFields((pcPicYuvOrg->getBuf(component) + pcPicYuvOrg->getMarginX(component) + (pcPicYuvOrg->getMarginY(component) * stride)),
+                       pcField->getPicYuvOrg()->getAddr(component),
+                       pcPicYuvOrg->getStride(component),
+                       pcPicYuvOrg->getWidth(component),
+                       pcPicYuvOrg->getHeight(component),
+                       isTopField);
+
+        separateFields((pcPicYuvTrueOrg->getBuf(component) + pcPicYuvTrueOrg->getMarginX(component) + (pcPicYuvTrueOrg->getMarginY(component) * stride)),
+                       pcField->getPicYuvTrueOrg()->getAddr(component),
+                       pcPicYuvTrueOrg->getStride(component),
+                       pcPicYuvTrueOrg->getWidth(component),
+                       pcPicYuvTrueOrg->getHeight(component),
+                       isTopField);
+      }
+
+      // compute image characteristics
+      if ( getUseAdaptiveQP() )
+      {
+        m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcField ) );
+      }
+    }
+
+    if ( m_iNumPicRcvd && ((flush&&fieldNum==1) || (m_iPOCLast/2)==0 || m_iNumPicRcvd==m_iGOPSize ) )
+    {
+      // compress GOP
+      m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff, snrCSC, m_printFrameMSE);
+
+      iNumEncoded += m_iNumPicRcvd;
+      m_uiNumAllPicCoded += m_iNumPicRcvd;
+      m_iNumPicRcvd = 0;
+    }
+  }
 }
 #endif
@@ -677,6 +571,9 @@
 Void TEncTop::xGetNewPicBuffer ( TComPic*& rpcPic )
 {
+  // At this point, the SPS and PPS can be considered activated - they are copied to the new TComPic.
+
   TComSlice::sortPicList(m_cListPic);
-  
+
+
   if (m_cListPic.size() >= (UInt)(m_iGOPSize + getMaxDecPicBuffering(MAX_TLAYER-1) + 2) )
   {
@@ -697,6 +594,5 @@
     {
       TEncPic* pcEPic = new TEncPic;
-      pcEPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_cPPS.getMaxCuDQPDepth()+1 ,
-                      m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics);
+      pcEPic->create( m_cSPS, m_cPPS, m_cPPS.getMaxCuDQPDepth()+1, false);
       rpcPic = pcEPic;
     }
@@ -704,27 +600,48 @@
     {
       rpcPic = new TComPic;
-
-      rpcPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, 
-                      m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics);
-    }
+      rpcPic->create( m_cSPS, m_cPPS, false );
+    }
+
     m_cListPic.pushBack( rpcPic );
   }
   rpcPic->setReconMark (false);
-  
+
   m_iPOCLast++;
   m_iNumPicRcvd++;
-  
+
   rpcPic->getSlice(0)->setPOC( m_iPOCLast );
   // mark it should be extended
   rpcPic->getPicYuvRec()->setBorderExtension(false);
-
-#if H_MV
+#if NH_MV
   rpcPic->getPicYuvOrg()->setBorderExtension(false);
 #endif
+
+}
+
+Void TEncTop::xInitVPS()
+{
+  // The SPS must have already been set up.
+  // set the VPS profile information.
+#if NH_MV
+  // Do initialization in TAppEncTop
+#else
+  *m_cVPS.getPTL() = *m_cSPS.getPTL();
+  m_cVPS.setMaxOpSets(1);
+  m_cVPS.getTimingInfo()->setTimingInfoPresentFlag       ( false );
+  m_cVPS.setNumHrdParameters( 0 );
+
+  m_cVPS.createHrdParamBuffer();
+  for( UInt i = 0; i < m_cVPS.getNumHrdParameters(); i ++ )
+  {
+    m_cVPS.setHrdOpSetIdx( 0, i );
+    m_cVPS.setCprmsPresentFlag( false, i );
+    // Set up HrdParameters here.
+  }
+#endif
 }
 
 Void TEncTop::xInitSPS()
 {
-#if H_MV
+#if NH_MV
   m_cSPS.setSPSId( getLayerIdInVps() );
   m_cSPS.setLayerId( getLayerId() );
@@ -740,6 +657,11 @@
   profileTierLevel.setNonPackedConstraintFlag(m_nonPackedConstraintFlag);
   profileTierLevel.setFrameOnlyConstraintFlag(m_frameOnlyConstraintFlag);
-  
-  if (m_profile == Profile::MAIN10 && g_bitDepthY == 8 && g_bitDepthC == 8)
+  profileTierLevel.setBitDepthConstraint(m_bitDepthConstraintValue);
+  profileTierLevel.setChromaFormatConstraint(m_chromaFormatConstraintValue);
+  profileTierLevel.setIntraConstraintFlag(m_intraConstraintFlag);
+  profileTierLevel.setOnePictureOnlyConstraintFlag(m_onePictureOnlyConstraintFlag);
+  profileTierLevel.setLowerBitRateConstraintFlag(m_lowerBitRateConstraintFlag);
+
+  if ((m_profile == Profile::MAIN10) && (m_bitDepth[CHANNEL_TYPE_LUMA] == 8) && (m_bitDepth[CHANNEL_TYPE_CHROMA] == 8))
   {
     /* The above constraint is equal to Profile::MAIN */
@@ -754,6 +676,5 @@
   /* XXX: may be a good idea to refactor the above into a function
    * that chooses the actual compatibility based upon options */
-
-#if H_MV  
+#if NH_MV  
   m_cSPS.setUpdateRepFormatFlag           ( false );    
   Bool multiLayerExtensionFlag  = ( getLayerId() > 0 ) && ( m_cVPS->getNumRefLayers( getLayerId() ) > 0 ); 
@@ -764,5 +685,5 @@
     m_cSPS.setSpsInferScalingListFlag   ( true ); 
     m_cSPS.setSpsScalingListRefLayerId( m_cVPS->getIdRefLayer( getLayerId(), 0 ) ); 
-#if H_MV
+#if NH_MV
     if ( m_bUseDisparitySearchRangeRestriction )
     {
@@ -773,19 +694,22 @@
   m_cSPS.setSpsExtensionPresentFlag       ( true ); 
   m_cSPS.setSpsMultilayerExtensionFlag    ( true ); 
-#if H_3D
+#if NH_3D
   m_cSPS.setSps3dExtensionFlag            ( true ); 
 #endif
 #endif
-  m_cSPS.setPicWidthInLumaSamples         ( m_iSourceWidth      );
-  m_cSPS.setPicHeightInLumaSamples        ( m_iSourceHeight     );
-  m_cSPS.setConformanceWindow             ( m_conformanceWindow );
-  m_cSPS.setMaxCUWidth    ( g_uiMaxCUWidth      );
-  m_cSPS.setMaxCUHeight   ( g_uiMaxCUHeight     );
-  m_cSPS.setMaxCUDepth    ( g_uiMaxCUDepth      );
-#if H_3D_DISABLE_CHROMA
-  m_cSPS.setChromaFormatIdc( getIsDepth() ? CHROMA_400 : CHROMA_420 ); 
-#endif
-
-  Int minCUSize = m_cSPS.getMaxCUWidth() >> ( m_cSPS.getMaxCUDepth()-g_uiAddCUDepth );
+
+  m_cSPS.setPicWidthInLumaSamples  ( m_iSourceWidth      );
+  m_cSPS.setPicHeightInLumaSamples ( m_iSourceHeight     );
+  m_cSPS.setConformanceWindow      ( m_conformanceWindow );
+  m_cSPS.setMaxCUWidth             ( m_maxCUWidth        );
+  m_cSPS.setMaxCUHeight            ( m_maxCUHeight       );
+  m_cSPS.setMaxTotalCUDepth        ( m_maxTotalCUDepth   );
+#if NH_3D
+  assert( !getIsDepth()  || m_chromaFormatIDC == CHROMA_400 ); 
+#endif
+  m_cSPS.setChromaFormatIdc( m_chromaFormatIDC);
+  m_cSPS.setLog2DiffMaxMinCodingBlockSize(m_log2DiffMaxMinCodingBlockSize);
+
+  Int minCUSize = m_cSPS.getMaxCUWidth() >> ( m_cSPS.getLog2DiffMaxMinCodingBlockSize() );
   Int log2MinCUSize = 0;
   while(minCUSize > 1)
@@ -796,6 +720,5 @@
 
   m_cSPS.setLog2MinCodingBlockSize(log2MinCUSize);
-  m_cSPS.setLog2DiffMaxMinCodingBlockSize(m_cSPS.getMaxCUDepth()-g_uiAddCUDepth);
-  
+
   m_cSPS.setPCMLog2MinSize (m_uiPCMLog2MinSize);
   m_cSPS.setUsePCM        ( m_usePCM           );
@@ -806,40 +729,34 @@
   m_cSPS.setQuadtreeTUMaxDepthInter( m_uiQuadtreeTUMaxDepthInter    );
   m_cSPS.setQuadtreeTUMaxDepthIntra( m_uiQuadtreeTUMaxDepthIntra    );
-  
-  m_cSPS.setTMVPFlagsPresent(false);
+
+  m_cSPS.setTMVPFlagsPresent((getTMVPModeId() == 2 || getTMVPModeId() == 1));
 
   m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
-  
-  Int i;
-  
-  for (i = 0; i < g_uiMaxCUDepth-g_uiAddCUDepth; i++ )
-  {
-    m_cSPS.setAMPAcc( i, m_useAMP );
-    //m_cSPS.setAMPAcc( i, 1 );
-  }
 
   m_cSPS.setUseAMP ( m_useAMP );
 
-  for (i = g_uiMaxCUDepth-g_uiAddCUDepth; i < g_uiMaxCUDepth; i++ )
-  {
-    m_cSPS.setAMPAcc(i, 0);
-  }
-
-  m_cSPS.setBitDepthY( g_bitDepthY );
-  m_cSPS.setBitDepthC( g_bitDepthC );
-
-  m_cSPS.setQpBDOffsetY ( 6*(g_bitDepthY - 8) );
-  m_cSPS.setQpBDOffsetC ( 6*(g_bitDepthC - 8) );
-
-  m_cSPS.setUseSAO( m_bUseSAO );
+  for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+  {
+    m_cSPS.setBitDepth      (ChannelType(channelType), m_bitDepth[channelType] );
+#if O0043_BEST_EFFORT_DECODING
+    m_cSPS.setStreamBitDepth(ChannelType(channelType), m_bitDepth[channelType] );
+#endif
+    m_cSPS.setQpBDOffset  (ChannelType(channelType), (6 * (m_bitDepth[channelType] - 8)));
+    m_cSPS.setPCMBitDepth (ChannelType(channelType), m_PCMBitDepth[channelType]         );
+  }
+#if NH_MV
+  m_cSPS.inferRepFormat( m_cVPS, getLayerId(), true ); 
+#endif
+m_cSPS.setUseSAO( m_bUseSAO );
 
   m_cSPS.setMaxTLayers( m_maxTempLayer );
   m_cSPS.setTemporalIdNestingFlag( ( m_maxTempLayer == 1 ) ? true : false );
-  for ( i = 0; i < min(m_cSPS.getMaxTLayers(),(UInt) MAX_TLAYER); i++ )
+
+  for (Int i = 0; i < min(m_cSPS.getMaxTLayers(),(UInt) MAX_TLAYER); i++ )
   {
     m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
     m_cSPS.setNumReorderPics(m_numReorderPics[i], i);
   }
-#if H_MV
+#if NH_MV
   for ( Int ols = 0; ols < m_cVPS->getNumOutputLayerSets(); ols++)
   {
@@ -855,13 +772,11 @@
   }
 #endif
-  m_cSPS.setPCMBitDepthLuma (g_uiPCMBitDepthLuma);
-  m_cSPS.setPCMBitDepthChroma (g_uiPCMBitDepthChroma);
+
+
   m_cSPS.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag );
-
-  m_cSPS.setScalingListFlag ( (m_useScalingListId == 0) ? 0 : 1 );
-
+  m_cSPS.setScalingListFlag ( (m_useScalingListId == SCALING_LIST_OFF) ? 0 : 1 );
   m_cSPS.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
-
   m_cSPS.setVuiParametersPresentFlag(getVuiParametersPresentFlag());
+
   if (m_cSPS.getVuiParametersPresentFlag())
   {
@@ -873,8 +788,8 @@
     pcVUI->setOverscanInfoPresentFlag(getOverscanInfoPresentFlag());
     pcVUI->setOverscanAppropriateFlag(getOverscanAppropriateFlag());
-#if H_MV
+#if NH_MV
     pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag() && getLayerId() == 0 );
 #else
-   pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag());
+    pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag());
 #endif
     pcVUI->setVideoFormat(getVideoFormat());
@@ -903,11 +818,156 @@
     pcVUI->setLog2MaxMvLengthVertical(getLog2MaxMvLengthVertical());
   }
-}
+  m_cSPS.setNumLongTermRefPicSPS(NUM_LONG_TERM_REF_PIC_SPS);
+  assert (NUM_LONG_TERM_REF_PIC_SPS <= MAX_NUM_LONG_TERM_REF_PICS);
+  for (Int k = 0; k < NUM_LONG_TERM_REF_PIC_SPS; k++)
+  {
+    m_cSPS.setLtRefPicPocLsbSps(k, 0);
+    m_cSPS.setUsedByCurrPicLtSPSFlag(k, 0);
+  }
+  if( getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() )
+  {
+    xInitHrdParameters();
+  }
+  if( getBufferingPeriodSEIEnabled() || getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() )
+  {
+    m_cSPS.getVuiParameters()->setHrdParametersPresentFlag( true );
+  }
+
+  // Set up SPS range extension settings
+  m_cSPS.getSpsRangeExtension().setTransformSkipRotationEnabledFlag(m_transformSkipRotationEnabledFlag);
+  m_cSPS.getSpsRangeExtension().setTransformSkipContextEnabledFlag(m_transformSkipContextEnabledFlag);
+  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
+  {
+    m_cSPS.getSpsRangeExtension().setRdpcmEnabledFlag(RDPCMSignallingMode(signallingModeIndex), m_rdpcmEnabledFlag[signallingModeIndex]);
+  }
+  m_cSPS.getSpsRangeExtension().setExtendedPrecisionProcessingFlag(m_extendedPrecisionProcessingFlag);
+  m_cSPS.getSpsRangeExtension().setIntraSmoothingDisabledFlag( m_intraSmoothingDisabledFlag );
+  m_cSPS.getSpsRangeExtension().setHighPrecisionOffsetsEnabledFlag(m_highPrecisionOffsetsEnabledFlag);
+  m_cSPS.getSpsRangeExtension().setPersistentRiceAdaptationEnabledFlag(m_persistentRiceAdaptationEnabledFlag);
+  m_cSPS.getSpsRangeExtension().setCabacBypassAlignmentEnabledFlag(m_cabacBypassAlignmentEnabledFlag);
+#if NH_MV
+  m_cSPS.setSpsRangeExtensionsFlag( m_cSPS.getSpsRangeExtension().settingsDifferFromDefaults() );
+#endif
+
+}
+
+Void TEncTop::xInitHrdParameters()
+{
+  Bool useSubCpbParams = (getSliceMode() > 0) || (getSliceSegmentMode() > 0);
+  Int  bitRate         = getTargetBitrate();
+  Bool isRandomAccess  = getIntraPeriod() > 0;
+
+  if( !getVuiParametersPresentFlag() )
+  {
+    return;
+  }
+
+  TComVUI *vui = m_cSPS.getVuiParameters();
+  TComHRD *hrd = vui->getHrdParameters();
+
+  TimingInfo *timingInfo = vui->getTimingInfo();
+  timingInfo->setTimingInfoPresentFlag( true );
+  switch( getFrameRate() )
+  {
+  case 24:
+    timingInfo->setNumUnitsInTick( 1125000 );    timingInfo->setTimeScale    ( 27000000 );
+    break;
+  case 25:
+    timingInfo->setNumUnitsInTick( 1080000 );    timingInfo->setTimeScale    ( 27000000 );
+    break;
+  case 30:
+    timingInfo->setNumUnitsInTick( 900900 );     timingInfo->setTimeScale    ( 27000000 );
+    break;
+  case 50:
+    timingInfo->setNumUnitsInTick( 540000 );     timingInfo->setTimeScale    ( 27000000 );
+    break;
+  case 60:
+    timingInfo->setNumUnitsInTick( 450450 );     timingInfo->setTimeScale    ( 27000000 );
+    break;
+  default:
+    timingInfo->setNumUnitsInTick( 1001 );       timingInfo->setTimeScale    ( 60000 );
+    break;
+  }
+
+  Bool rateCnt = ( bitRate > 0 );
+  hrd->setNalHrdParametersPresentFlag( rateCnt );
+  hrd->setVclHrdParametersPresentFlag( rateCnt );
+
+  hrd->setSubPicCpbParamsPresentFlag( useSubCpbParams );
+
+  if( hrd->getSubPicCpbParamsPresentFlag() )
+  {
+    hrd->setTickDivisorMinus2( 100 - 2 );                          //
+    hrd->setDuCpbRemovalDelayLengthMinus1( 7 );                    // 8-bit precision ( plus 1 for last DU in AU )
+    hrd->setSubPicCpbParamsInPicTimingSEIFlag( true );
+    hrd->setDpbOutputDelayDuLengthMinus1( 5 + 7 );                 // With sub-clock tick factor of 100, at least 7 bits to have the same value as AU dpb delay
+  }
+  else
+  {
+    hrd->setSubPicCpbParamsInPicTimingSEIFlag( false );
+  }
+
+  hrd->setBitRateScale( 4 );                                       // in units of 2^( 6 + 4 ) = 1,024 bps
+  hrd->setCpbSizeScale( 6 );                                       // in units of 2^( 4 + 6 ) = 1,024 bit
+  hrd->setDuCpbSizeScale( 6 );                                     // in units of 2^( 4 + 6 ) = 1,024 bit
+
+  hrd->setInitialCpbRemovalDelayLengthMinus1(15);                  // assuming 0.5 sec, log2( 90,000 * 0.5 ) = 16-bit
+  if( isRandomAccess )
+  {
+    hrd->setCpbRemovalDelayLengthMinus1(5);                        // 32 = 2^5 (plus 1)
+    hrd->setDpbOutputDelayLengthMinus1 (5);                        // 32 + 3 = 2^6
+  }
+  else
+  {
+    hrd->setCpbRemovalDelayLengthMinus1(9);                        // max. 2^10
+    hrd->setDpbOutputDelayLengthMinus1 (9);                        // max. 2^10
+  }
+
+  // Note: parameters for all temporal layers are initialized with the same values
+  Int i, j;
+  UInt bitrateValue, cpbSizeValue;
+  UInt duCpbSizeValue;
+  UInt duBitRateValue = 0;
+
+  for( i = 0; i < MAX_TLAYER; i ++ )
+  {
+    hrd->setFixedPicRateFlag( i, 1 );
+    hrd->setPicDurationInTcMinus1( i, 0 );
+    hrd->setLowDelayHrdFlag( i, 0 );
+    hrd->setCpbCntMinus1( i, 0 );
+
+    //! \todo check for possible PTL violations
+    // BitRate[ i ] = ( bit_rate_value_minus1[ i ] + 1 ) * 2^( 6 + bit_rate_scale )
+    bitrateValue = bitRate / (1 << (6 + hrd->getBitRateScale()) );      // bitRate is in bits, so it needs to be scaled down
+    // CpbSize[ i ] = ( cpb_size_value_minus1[ i ] + 1 ) * 2^( 4 + cpb_size_scale )
+    cpbSizeValue = bitRate / (1 << (4 + hrd->getCpbSizeScale()) );      // using bitRate results in 1 second CPB size
+
+    // DU CPB size could be smaller (i.e. bitrateValue / number of DUs), but we don't know 
+    // in how many DUs the slice segment settings will result 
+    duCpbSizeValue = bitrateValue;
+    duBitRateValue = cpbSizeValue;
+
+    for( j = 0; j < ( hrd->getCpbCntMinus1( i ) + 1 ); j ++ )
+    {
+      hrd->setBitRateValueMinus1( i, j, 0, ( bitrateValue - 1 ) );
+      hrd->setCpbSizeValueMinus1( i, j, 0, ( cpbSizeValue - 1 ) );
+      hrd->setDuCpbSizeValueMinus1( i, j, 0, ( duCpbSizeValue - 1 ) );
+      hrd->setCbrFlag( i, j, 0, false );
+
+      hrd->setBitRateValueMinus1( i, j, 1, ( bitrateValue - 1) );
+      hrd->setCpbSizeValueMinus1( i, j, 1, ( cpbSizeValue - 1 ) );
+      hrd->setDuCpbSizeValueMinus1( i, j, 1, ( duCpbSizeValue - 1 ) );
+      hrd->setDuBitRateValueMinus1( i, j, 1, ( duBitRateValue - 1 ) );
+      hrd->setCbrFlag( i, j, 1, false );
+    }
+  }
+}
+
 
 Void TEncTop::xInitPPS()
 {
-#if H_MV
+#if NH_MV
   m_cPPS.setLayerId( getLayerId() );
-#if H_3D
+#if NH_3D
   // Check if this condition is still correct
   if( getVPS()->getNumRefListLayers( getLayerId() ) > 0 )
@@ -921,6 +981,7 @@
   m_cPPS.setSPSId( getLayerIdInVps() );
   m_cPPS.setPpsMultilayerExtensionFlag    ( true ); 
-#if H_3D
-  m_cPPS.setPps3dExtensionFlag            ( true ); 
+#if NH_3D
+  // Might be used for DLT
+  m_cPPS.setPps3dExtensionFlag            ( getIsDepth() ); 
 #endif
 #endif
@@ -929,17 +990,28 @@
   m_cPPS.setDLT( getDLT() );
 #endif
+
   m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
   Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
 
-      if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
-      {
-        bUseDQP = true;
-      }
-
-  if(bUseDQP)
+  if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
+  {
+    bUseDQP = true;
+  }
+
+  if (m_costMode==COST_SEQUENCE_LEVEL_LOSSLESS || m_costMode==COST_LOSSLESS_CODING)
+  {
+    bUseDQP=false;
+  }
+
+
+  if ( m_RCEnableRateControl )
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+  }
+  else if(bUseDQP)
   {
     m_cPPS.setUseDQP(true);
     m_cPPS.setMaxCuDQPDepth( m_iMaxCuDQPDepth );
-    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
   }
   else
@@ -947,18 +1019,25 @@
     m_cPPS.setUseDQP(false);
     m_cPPS.setMaxCuDQPDepth( 0 );
-    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
-  }
-
-  if ( m_RCEnableRateControl )
-  {
-    m_cPPS.setUseDQP(true);
-    m_cPPS.setMaxCuDQPDepth( 0 );
-    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
-  }
-
-  m_cPPS.setChromaCbQpOffset( m_chromaCbQpOffset );
-  m_cPPS.setChromaCrQpOffset( m_chromaCrQpOffset );
-
-  m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams);
+  }
+
+  if ( m_diffCuChromaQpOffsetDepth >= 0 )
+  {
+    m_cPPS.getPpsRangeExtension().setDiffCuChromaQpOffsetDepth(m_diffCuChromaQpOffsetDepth);
+    m_cPPS.getPpsRangeExtension().clearChromaQpOffsetList();
+    m_cPPS.getPpsRangeExtension().setChromaQpOffsetListEntry(1, 6, 6);
+    /* todo, insert table entries from command line (NB, 0 should not be touched) */
+  }
+  else
+  {
+    m_cPPS.getPpsRangeExtension().setDiffCuChromaQpOffsetDepth(0);
+    m_cPPS.getPpsRangeExtension().clearChromaQpOffsetList();
+  }
+  m_cPPS.getPpsRangeExtension().setCrossComponentPredictionEnabledFlag(m_crossComponentPredictionEnabledFlag);
+  m_cPPS.getPpsRangeExtension().setLog2SaoOffsetScale(CHANNEL_TYPE_LUMA,   m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA  ]);
+  m_cPPS.getPpsRangeExtension().setLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA, m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA]);
+
+  m_cPPS.setQpOffset(COMPONENT_Cb, m_chromaCbQpOffset );
+  m_cPPS.setQpOffset(COMPONENT_Cr, m_chromaCrQpOffset );
+
   m_cPPS.setEntropyCodingSyncEnabledFlag( m_iWaveFrontSynchro > 0 );
   m_cPPS.setTilesEnabledFlag( (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0) );
@@ -966,5 +1045,5 @@
   m_cPPS.setWPBiPred( m_useWeightedBiPred );
   m_cPPS.setOutputFlagPresentFlag( false );
-#if H_MV
+#if NH_MV
   m_cPPS.setNumExtraSliceHeaderBits( 3 ); 
 #endif
@@ -972,17 +1051,37 @@
   if ( getDeblockingFilterMetric() )
   {
-    m_cPPS.setDeblockingFilterControlPresentFlag (true);
     m_cPPS.setDeblockingFilterOverrideEnabledFlag(true);
     m_cPPS.setPicDisableDeblockingFilterFlag(false);
+  }
+  else
+  {
+      m_cPPS.setDeblockingFilterOverrideEnabledFlag( !getLoopFilterOffsetInPPS() );
+      m_cPPS.setPicDisableDeblockingFilterFlag( getLoopFilterDisable() );
+    }
+
+  if (! m_cPPS.getPicDisableDeblockingFilterFlag())
+  {
+    m_cPPS.setDeblockingFilterBetaOffsetDiv2( getLoopFilterBetaOffset() );
+    m_cPPS.setDeblockingFilterTcOffsetDiv2( getLoopFilterTcOffset() );
+  }
+  else
+  {
     m_cPPS.setDeblockingFilterBetaOffsetDiv2(0);
     m_cPPS.setDeblockingFilterTcOffsetDiv2(0);
-  } 
-  else
-  {
-    m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
-  }
+  }
+
+  // deblockingFilterControlPresentFlag is true if any of the settings differ from the inferred values:
+  const Bool deblockingFilterControlPresentFlag = m_cPPS.getDeblockingFilterOverrideEnabledFlag() ||
+                                                  m_cPPS.getPicDisableDeblockingFilterFlag()      ||
+                                                  m_cPPS.getDeblockingFilterBetaOffsetDiv2() != 0 ||
+                                                  m_cPPS.getDeblockingFilterTcOffsetDiv2() != 0;
+
+  m_cPPS.setDeblockingFilterControlPresentFlag(deblockingFilterControlPresentFlag);
+
   m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
   m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
   m_cPPS.setLoopFilterAcrossSlicesEnabledFlag( m_bLFCrossSliceBoundaryFlag );
+
+
   Int histogram[MAX_NUM_REF + 1];
   for( Int i = 0; i <= MAX_NUM_REF; i++ )
@@ -990,9 +1089,10 @@
     histogram[i]=0;
   }
-  for( Int i = 0; i < getGOPSize(); i++ )
+  for( Int i = 0; i < getGOPSize(); i++)
   {
     assert(getGOPEntry(i).m_numRefPicsActive >= 0 && getGOPEntry(i).m_numRefPicsActive <= MAX_NUM_REF);
     histogram[getGOPEntry(i).m_numRefPicsActive]++;
   }
+
   Int maxHist=-1;
   Int bestPos=0;
@@ -1010,19 +1110,9 @@
   m_cPPS.setTransquantBypassEnableFlag(getTransquantBypassEnableFlag());
   m_cPPS.setUseTransformSkip( m_useTransformSkip );
-  if (m_sliceSegmentMode)
+  m_cPPS.getPpsRangeExtension().setLog2MaxTransformSkipBlockSize( m_log2MaxTransformSkipBlockSize  );
+
+  if (m_sliceSegmentMode != NO_SLICES)
   {
     m_cPPS.setDependentSliceSegmentsEnabledFlag( true );
-  }
-  if( m_cPPS.getDependentSliceSegmentsEnabledFlag() )
-  {
-    Int NumCtx = m_cPPS.getEntropyCodingSyncEnabledFlag()?2:1;
-    m_cSliceEncoder.initCtxMem( NumCtx );
-    for ( UInt st = 0; st < NumCtx; st++ )
-    {
-      TEncSbac* ctx = NULL;
-      ctx = new TEncSbac;
-      ctx->init( &m_cBinCoderCABAC );
-      m_cSliceEncoder.setCtxMem( ctx, st );
-    }
   }
 }
@@ -1032,9 +1122,9 @@
 {
   TComReferencePictureSet*      rps;
-  
-  m_cSPS.createRPSList(getGOPSize()+m_extraRPSs+1);
+
+  m_cSPS.createRPSList(getGOPSize() + m_extraRPSs + 1);
   TComRPSList* rpsList = m_cSPS.getRPSList();
 
-  for( Int i = 0; i < getGOPSize()+m_extraRPSs; i++) 
+  for( Int i = 0; i < getGOPSize()+m_extraRPSs; i++)
   {
     GOPEntry ge = getGOPEntry(i);
@@ -1061,11 +1151,11 @@
 
     // handle inter RPS intialization from the config file.
-#if AUTO_INTER_RPS
     rps->setInterRPSPrediction(ge.m_interRPSPrediction > 0);  // not very clean, converting anything > 0 to true.
     rps->setDeltaRIdxMinus1(0);                               // index to the Reference RPS is always the previous one.
-    TComReferencePictureSet*     RPSRef = rpsList->getReferencePictureSet(i-1);  // get the reference RPS
+    TComReferencePictureSet*     RPSRef = i>0 ? rpsList->getReferencePictureSet(i-1): NULL;  // get the reference RPS
 
     if (ge.m_interRPSPrediction == 2)  // Automatic generation of the inter RPS idc based on the RIdx provided.
     {
+      assert (RPSRef!=NULL);
       Int deltaRPS = getGOPEntry(i-1).m_POC - ge.m_POC;  // the ref POC - current POC
       Int numRefDeltaPOC = RPSRef->getNumberOfPictures();
@@ -1080,5 +1170,5 @@
         for (Int k = 0; k < rps->getNumberOfPictures(); k++ )  // cycle through pics in current RPS.
         {
-          if (rps->getDeltaPOC(k) == ( RefDeltaPOC + deltaRPS))  // if the current RPS has a same picture as the reference RPS. 
+          if (rps->getDeltaPOC(k) == ( RefDeltaPOC + deltaRPS))  // if the current RPS has a same picture as the reference RPS.
           {
               rps->setRefIdc(j, (rps->getUsed(k)?1:2));
@@ -1096,4 +1186,5 @@
     else if (ge.m_interRPSPrediction == 1)  // inter RPS idc based on the RefIdc values provided in config file.
     {
+      assert (RPSRef!=NULL);
       rps->setDeltaRPS(ge.m_deltaRPS);
       rps->setNumRefIdc(ge.m_numRefIdc);
@@ -1102,6 +1193,5 @@
         rps->setRefIdc(j, ge.m_refIdc[j]);
       }
-#if WRITE_BACK
-      // the folowing code overwrite the deltaPOC and Used by current values read from the config file with the ones
+      // the following code overwrite the deltaPOC and Used by current values read from the config file with the ones
       // computed from the RefIdc.  A warning is printed if they are not identical.
       numNeg = 0;
@@ -1141,5 +1231,5 @@
       RPSTemp.setNumberOfNegativePictures(numNeg);
       RPSTemp.sortDeltaPOC();     // sort the created delta POC before comparing
-      // check if Delta POC and Used are the same 
+      // check if Delta POC and Used are the same
       // print warning if they are not.
       for (Int j = 0; j < ge.m_numRefIdc; j++ )
@@ -1156,51 +1246,9 @@
         }
       }
-#endif
-    }
-#else
-    rps->setInterRPSPrediction(ge.m_interRPSPrediction);
-    if (ge.m_interRPSPrediction)
-    {
-      rps->setDeltaRIdxMinus1(0);
-      rps->setDeltaRPS(ge.m_deltaRPS);
-      rps->setNumRefIdc(ge.m_numRefIdc);
-      for (Int j = 0; j < ge.m_numRefIdc; j++ )
-      {
-        rps->setRefIdc(j, ge.m_refIdc[j]);
-      }
-#if WRITE_BACK
-      // the folowing code overwrite the deltaPOC and Used by current values read from the config file with the ones
-      // computed from the RefIdc.  This is not necessary if both are identical. Currently there is no check to see if they are identical.
-      numNeg = 0;
-      numPos = 0;
-      TComReferencePictureSet*     RPSRef = m_RPSList.getReferencePictureSet(i-1);
-
-      for (Int j = 0; j < ge.m_numRefIdc; j++ )
-      {
-        if (ge.m_refIdc[j])
-        {
-          Int deltaPOC = ge.m_deltaRPS + ((j < RPSRef->getNumberOfPictures())? RPSRef->getDeltaPOC(j) : 0);
-          rps->setDeltaPOC((numNeg+numPos),deltaPOC);
-          rps->setUsed((numNeg+numPos),ge.m_refIdc[j]==1?1:0);
-          if (deltaPOC<0)
-          {
-            numNeg++;
-          }
-          else
-          {
-            numPos++;
-          }
-        }
-      }
-      rps->setNumberOfNegativePictures(numNeg);
-      rps->setNumberOfPositivePictures(numPos);
-      rps->sortDeltaPOC();
-#endif
-    }
-#endif //INTER_RPS_AUTO
-  }
-  //In case of field coding, we need to set special parameters for the first bottom field of the sequence, since it is not specified in the cfg file. 
-  //The position = GOPSize + extraRPSs which is (a priori) unused is reserved for this field in the RPS. 
-  if (isFieldCoding) 
+    }
+  }
+  //In case of field coding, we need to set special parameters for the first bottom field of the sequence, since it is not specified in the cfg file.
+  //The position = GOPSize + extraRPSs which is (a priori) unused is reserved for this field in the RPS.
+  if (isFieldCoding)
   {
     rps = rpsList->getReferencePictureSet(getGOPSize()+m_extraRPSs);
@@ -1216,13 +1264,13 @@
     rps->setDeltaRPS(0);
     rps->setNumRefIdc(0);
-}
-}
-
-   // This is a function that 
-   // determines what Reference Picture Set to use 
+  }
+}
+
+   // This is a function that
+   // determines what Reference Picture Set to use
    // for a specific slice (with POC = POCCurr)
 Void TEncTop::selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid )
 {
-#if H_MV
+#if NH_MV
   if( slice->getRapPicFlag() == true && getLayerId() > 0 && POCCurr == 0 )
   {
@@ -1240,5 +1288,5 @@
 
   for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
-  {    
+  {
     if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
     {
@@ -1261,4 +1309,5 @@
     }
   }
+
   if(POCCurr == 1 && slice->getPic()->isField())
   {
@@ -1266,18 +1315,20 @@
   }
 
-  slice->setRPS(getSPS()->getRPSList()->getReferencePictureSet(slice->getRPSidx()));
+  TComReferencePictureSet *rps=slice->getLocalRPS();
+  (*rps) = *(slice->getSPS()->getRPSList()->getReferencePictureSet(slice->getRPSidx()));
+  slice->setRPS(rps);
   slice->getRPS()->setNumberOfPictures(slice->getRPS()->getNumberOfNegativePictures()+slice->getRPS()->getNumberOfPositivePictures());
-#if H_MV
-  }
-#endif
-
-}
-
-Int TEncTop::getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid )
-{
-  int rpsIdx = GOPid;
+#if NH_MV
+  }
+#endif
+
+}
+
+Int TEncTop::getReferencePictureSetIdxForSOP(Int POCCurr, Int GOPid )
+{
+  Int rpsIdx = GOPid;
 
   for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
-  {    
+  {
     if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
     {
@@ -1317,14 +1368,10 @@
 
   // # substreams is "per tile" when tiles are independent.
-  if (m_iWaveFrontSynchro )
-  {
-    m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams * (m_iNumColumnsMinus1+1));
-  }
 }
 
 Void  TEncCfg::xCheckGSParameters()
 {
-  Int   iWidthInCU = ( m_iSourceWidth%g_uiMaxCUWidth ) ? m_iSourceWidth/g_uiMaxCUWidth + 1 : m_iSourceWidth/g_uiMaxCUWidth;
-  Int   iHeightInCU = ( m_iSourceHeight%g_uiMaxCUHeight ) ? m_iSourceHeight/g_uiMaxCUHeight + 1 : m_iSourceHeight/g_uiMaxCUHeight;
+  Int   iWidthInCU = ( m_iSourceWidth%m_maxCUWidth ) ? m_iSourceWidth/m_maxCUWidth + 1 : m_iSourceWidth/m_maxCUWidth;
+  Int   iHeightInCU = ( m_iSourceHeight%m_maxCUHeight ) ? m_iSourceHeight/m_maxCUHeight + 1 : m_iSourceHeight/m_maxCUHeight;
   UInt  uiCummulativeColumnWidth = 0;
   UInt  uiCummulativeRowHeight = 0;
@@ -1373,5 +1420,7 @@
   {
     for(Int i=0; i<m_iNumRowsMinus1; i++)
+    {
       uiCummulativeRowHeight += m_tileRowHeight[i];
+    }
 
     if( uiCummulativeRowHeight >= iHeightInCU )
@@ -1382,40 +1431,6 @@
   }
 }
-#if H_MV
-Void TEncTop::printSummary( Int numAllPicCoded, Bool isField )
-{
-  assert ( !isField ); // Multiview and field coding need to be further unified
-  assert (numAllPicCoded == m_cAnalyzeAll.getNumPic());
-
-  //--CFG_KDY
-  m_cAnalyzeAll.setFrmRate( getFrameRate() );
-  m_cAnalyzeI.setFrmRate( getFrameRate() );
-  m_cAnalyzeP.setFrmRate( getFrameRate() );
-  m_cAnalyzeB.setFrmRate( getFrameRate() );
-
-  //-- all
-  printf( "\n\nSUMMARY ------------------------------------------- LayerId %2d\n", m_layerId );
-
-  m_cAnalyzeAll.printOut('a');
-
-  printf( "\n\nI Slices--------------------------------------------------------\n" );
-  m_cAnalyzeI.printOut('i');
-
-  printf( "\n\nP Slices--------------------------------------------------------\n" );
-  m_cAnalyzeP.printOut('p');
-
-  printf( "\n\nB Slices--------------------------------------------------------\n" );
-  m_cAnalyzeB.printOut('b');
-
-#if _SUMMARY_OUT_
-  m_cAnalyzeAll.printSummaryOut();
-#endif
-#if _SUMMARY_PIC_
-  m_cAnalyzeI.printSummary('I');
-  m_cAnalyzeP.printSummary('P');
-  m_cAnalyzeB.printSummary('B');
-#endif
-}
-
+
+#if NH_MV
 Int TEncTop::getFrameId(Int iGOPid)  
 {
@@ -1444,11 +1459,12 @@
   return pcPic;
 }
-#endif
-
-#if H_3D_VSO
-Void TEncTop::setupRenModel( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset )
+
+#endif
+
+#if NH_3D_VSO
+Void TEncTop::setupRenModel( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset, Int maxCuHeight )
 {
   TRenModel* rendererModel = m_cRdCost.getRenModel(); 
-  rendererModel->setupPart( iHorOffset, std::min( (Int) g_uiMaxCUHeight, (Int) ( m_iSourceHeight - iHorOffset ) )) ; 
+  rendererModel->setupPart( iHorOffset, std::min( maxCuHeight, (Int) ( m_iSourceHeight - iHorOffset ) )) ; 
   
   Int iEncViewSIdx = m_cameraParameters->getBaseId2SortedId()[ iEncViewIdx ];
@@ -1545,3 +1561,4 @@
 }
 #endif
+
 //! \}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncTop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/TEncTop.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -43,4 +43,5 @@
 #include "TLibCommon/TComPrediction.h"
 #include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComLoopFilter.h"
 #include "TLibCommon/AccessUnit.h"
 
@@ -76,6 +77,6 @@
   UInt                    m_uiNumAllPicCoded;             ///< number of coded pictures
   TComList<TComPic*>      m_cListPic;                     ///< dynamic list of pictures
-  
-#if H_MV
+
+#if NH_MV
   TComPicLists*           m_ivPicLists;                   ///< access to picture lists of other layers 
 #endif
@@ -87,5 +88,5 @@
   TEncSearch              m_cSearch;                      ///< encoder search class
   //TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
-  TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder  
+  TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder
   // coding tool
   TComTrQuant             m_cTrQuant;                     ///< transform & quantization class
@@ -96,7 +97,5 @@
   TEncSbac                m_cSbacCoder;                   ///< SBAC encoder
   TEncBinCABAC            m_cBinCoderCABAC;               ///< bin coder CABAC
-  TEncSbac*               m_pcSbacCoders;                 ///< SBAC encoders (to encode substreams )
-  TEncBinCABAC*           m_pcBinCoderCABACs;             ///< bin coders CABAC (one per substream)
-  
+
   // processing unit
   TEncGOP                 m_cGOPEncoder;                  ///< GOP encoder
@@ -104,8 +103,7 @@
   TEncCu                  m_cCuEncoder;                   ///< CU encoder
   // SPS
-  TComSPS                 m_cSPS;                         ///< SPS
-  TComPPS                 m_cPPS;                         ///< PPS
+  TComSPS                 m_cSPS;                         ///< SPS. This is the base value. This is copied to TComPicSym
+  TComPPS                 m_cPPS;                         ///< PPS. This is the base value. This is copied to TComPicSym
   // RD cost computation
-  TComBitCounter          m_cBitCounter;                  ///< bit counter for RD optimization
   TComRdCost              m_cRdCost;                      ///< RD cost computation class
   TEncSbac***             m_pppcRDSbacCoder;              ///< temporal storage for RD computation
@@ -118,16 +116,8 @@
   TEncBinCABAC            m_cRDGoOnBinCoderCABAC;         ///< going on bin coder CABAC for RD stage
 #endif
-  Int                     m_iNumSubstreams;                ///< # of top-level elements allocated.
-  TComBitCounter*         m_pcBitCounters;                 ///< bit counters for RD optimization per substream
-  TComRdCost*             m_pcRdCosts;                     ///< RD cost computation class per substream
-  TEncSbac****            m_ppppcRDSbacCoders;             ///< temporal storage for RD computation per substream
-  TEncSbac*               m_pcRDGoOnSbacCoders;            ///< going on SBAC model for RD stage per substream
-  TEncBinCABAC****        m_ppppcBinCodersCABAC;           ///< temporal CABAC state storage for RD computation per substream
-  TEncBinCABAC*           m_pcRDGoOnBinCodersCABAC;        ///< going on bin coder CABAC for RD stage per substream
 
   // quality control
   TEncPreanalyzer         m_cPreanalyzer;                 ///< image characteristics analyzer for TM5-step3-like adaptive QP
 
-  TComScalingList         m_scalingList;                 ///< quantization matrix information
   TEncRateCtrl            m_cRateCtrl;                    ///< Rate control class
 
@@ -136,64 +126,26 @@
   TAppComCamPara*         m_cCamParam;
 #endif
-  
-#if H_MV
+#if NH_MV
   TEncAnalyze             m_cAnalyzeAll;
   TEncAnalyze             m_cAnalyzeI;
   TEncAnalyze             m_cAnalyzeP;
-  TEncAnalyze             m_cAnalyzeB;  
+  TEncAnalyze             m_cAnalyzeB;
+  TEncAnalyze             m_cAnalyzeAll_in;
 #endif
 protected:
   Void  xGetNewPicBuffer  ( TComPic*& rpcPic );           ///< get picture buffer which will be processed
+  Void  xInitVPS          ();                             ///< initialize VPS from encoder options
   Void  xInitSPS          ();                             ///< initialize SPS from encoder options
   Void  xInitPPS          ();                             ///< initialize PPS from encoder options
-  
+  Void  xInitScalingLists();                              ///< initialize scaling lists
+  Void  xInitHrdParameters();                             ///< initialize HRD parameters
+
   Void  xInitPPSforTiles  ();
   Void  xInitRPS          (Bool isFieldCoding);           ///< initialize PPS from encoder options
-#if H_MV
-
-  template <class T>     Void  xDelete( Bool ar, T inArray ) 
-  {
-    if( inArray != NULL)
-    {
-      if ( ar )
-      {      
-        delete[] inArray; 
-      }
-      else
-      {
-        delete inArray;
-      }
-    }
-  }
-
-  template <class T>     Void  xDelete( Bool ar, T inArray, Int idx1 ) 
-  {
-    if( inArray != NULL)
-    {
-        xDelete( ar, inArray[idx1]); 
-    }
-  }
-
-  template <class T>     Void  xDelete( Bool ar, T inArray, Int idx1, Int idx2 ) 
-  {
-    if( inArray != NULL )
-    {
-      xDelete( ar, inArray[idx1], idx2 ); 
-    }
-  }
-
-  template <class T>     Void  xDelete( Bool ar, T inArray, Int idx1, Int idx2, Int idx3 ) 
-  {
-    if( inArray != NULL )
-    {
-      xDelete( ar, inArray[idx1], idx2, idx3 ); 
-    }
-  }
-
-#endif
+
 public:
   TEncTop();
   virtual ~TEncTop();
-  
+
   Void      create          ();
   Void      destroy         ();
@@ -203,6 +155,5 @@
   Void      init            (Bool isFieldCoding);
 #endif
-
-#if H_MV  
+#if NH_MV  
   TComPicLists* getIvPicLists() { return m_ivPicLists; }
 #endif
@@ -212,8 +163,5 @@
 #endif
   Void      deletePicBuffer ();
-
-  Void      createWPPCoders(Int iNumSubstreams);
-  
-#if H_MV
+#if NH_MV
   Void      initNewPic(TComPicYuv* pcPicYuvOrg);
 #endif
@@ -221,8 +169,8 @@
   // member access functions
   // -------------------------------------------------------------------------------------------------------------------
-  
+
   TComList<TComPic*>*     getListPic            () { return  &m_cListPic;             }
   TEncSearch*             getPredSearch         () { return  &m_cSearch;              }
-  
+
   TComTrQuant*            getTrQuant            () { return  &m_cTrQuant;             }
   TComLoopFilter*         getLoopFilter         () { return  &m_cLoopFilter;          }
@@ -235,15 +183,8 @@
   TEncSbac*               getSbacCoder          () { return  &m_cSbacCoder;           }
   TEncBinCABAC*           getBinCABAC           () { return  &m_cBinCoderCABAC;       }
-  TEncSbac*               getSbacCoders     () { return  m_pcSbacCoders;      }
-  TEncBinCABAC*           getBinCABACs          () { return  m_pcBinCoderCABACs;      }
-  
-  TComBitCounter*         getBitCounter         () { return  &m_cBitCounter;          }
+
   TComRdCost*             getRdCost             () { return  &m_cRdCost;              }
   TEncSbac***             getRDSbacCoder        () { return  m_pppcRDSbacCoder;       }
   TEncSbac*               getRDGoOnSbacCoder    () { return  &m_cRDGoOnSbacCoder;     }
-  TComBitCounter*         getBitCounters        () { return  m_pcBitCounters;         }
-  TComRdCost*             getRdCosts            () { return  m_pcRdCosts;             }
-  TEncSbac****            getRDSbacCoders       () { return  m_ppppcRDSbacCoders;     }
-  TEncSbac*               getRDGoOnSbacCoders   () { return  m_pcRDGoOnSbacCoders;   }
   TEncRateCtrl*           getRateCtrl           () { return &m_cRateCtrl;             }
 #if KWU_RC_MADPRED_E0227
@@ -252,23 +193,17 @@
   Void                    setCamParam(TAppComCamPara * pCamparam)                 { m_cCamParam = pCamparam;}
 #endif
-  TComSPS*                getSPS                () { return  &m_cSPS;                 }
-  TComPPS*                getPPS                () { return  &m_cPPS;                 }
   Void selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid );
-  Int getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid );
-  TComScalingList*        getScalingList        () { return  &m_scalingList;         }
-#if H_MV
+  Int getReferencePictureSetIdxForSOP(Int POCCurr, Int GOPid );
+#if NH_MV
   TEncAnalyze*            getAnalyzeAll         () { return &m_cAnalyzeAll; }
   TEncAnalyze*            getAnalyzeI           () { return &m_cAnalyzeI;   }
   TEncAnalyze*            getAnalyzeP           () { return &m_cAnalyzeP;   }
   TEncAnalyze*            getAnalyzeB           () { return &m_cAnalyzeB;   }
-
-  Int                     getNumAllPicCoded     () { return m_uiNumAllPicCoded; }
- 
-  Int                     getFrameId            (Int iGOPid);
-  
+  Int                     getNumAllPicCoded     () { return m_uiNumAllPicCoded; } 
+  Int                     getFrameId            (Int iGOPid);  
   TComPic*                getPic                ( Int poc );
   Void                    setIvPicLists         ( TComPicLists* picLists) { m_ivPicLists = picLists; }
 #endif
-#if H_3D
+#if NH_3D
   Void                    setSps3dExtension     ( TComSps3dExtension sps3dExtension ) { m_cSPS.setSps3dExtension( sps3dExtension );  };
 #endif
@@ -282,28 +217,33 @@
 
   /// encode several number of pictures until end-of-sequence
-#if H_MV
-  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded  , Int gopId  );  
-
-   /// encode several number of pictures until end-of-sequence
-  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
-              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff  , Int gopId );
-
+#if NH_MV
+  Void encode( Bool bEos,
+    TComPicYuv* pcPicYuvOrg,
+    TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, // used for SNR calculations. Picture in original colour space.
+    TComList<TComPicYuv*>& rcListPicYuvRecOut,
+    std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Int gopId );
+
+  /// encode several number of pictures until end-of-sequence
+  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg,
+    TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, // used for SNR calculations. Picture in original colour space.
+    TComList<TComPicYuv*>& rcListPicYuvRecOut,
+    std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff, Int gopId);
 #else
-  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
-              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded ); 
-   /// encode several number of pictures until end-of-sequence
-  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
-              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff);
-
-#endif
-
-#if H_MV
-  Void printSummary      ( Int numAllPicCoded, bool isField ); 
-#else
-  Void printSummary(bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField); }
-#endif
-
-#if H_3D
-   Void setupRenModel( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset );
+  Void encode( Bool bEos,
+               TComPicYuv* pcPicYuvOrg,
+               TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, // used for SNR calculations. Picture in original colour space.
+               TComList<TComPicYuv*>& rcListPicYuvRecOut,
+               std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded );
+
+  /// encode several number of pictures until end-of-sequence
+  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg,
+               TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, // used for SNR calculations. Picture in original colour space.
+               TComList<TComPicYuv*>& rcListPicYuvRecOut,
+               std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff);
+#endif
+  Void printSummary(Bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField, m_printMSEBasedSequencePSNR, m_printSequenceMSE, m_cSPS.getBitDepths()); }
+
+#if NH_3D_VSO
+   Void setupRenModel( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset, Int maxCuHeight ); 
 #endif
 };
@@ -312,2 +252,3 @@
 
 #endif // __TENCTOP__
+
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -36,5 +36,5 @@
 */
 
-#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/CommonDef.h"
 #include "../TLibCommon/TComSlice.h"
 #include "../TLibCommon/TComPic.h"
@@ -47,13 +47,11 @@
 WeightPredAnalysis::WeightPredAnalysis()
 {
-  m_weighted_pred_flag = false;
-  m_weighted_bipred_flag = false;
-  for ( Int iList =0 ; iList<2 ; iList++ )
-  {
-    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
-    {
-      for ( Int comp=0 ; comp<3 ;comp++ )
-      {
-        wpScalingParam  *pwp   = &(m_wp[iList][iRefIdx][comp]);
+  for ( UInt lst =0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+    {
+      for ( Int comp=0 ; comp<MAX_NUM_COMPONENT ;comp++ )
+      {
+        WPScalingParam  *pwp   = &(m_wp[lst][iRefIdx][comp]);
         pwp->bPresentFlag      = false;
         pwp->uiLog2WeightDenom = 0;
@@ -65,82 +63,75 @@
 }
 
-/** calculate AC and DC values for current original image
- * \param TComSlice *slice
- * \returns Void
- */
-Bool  WeightPredAnalysis::xCalcACDCParamSlice(TComSlice *slice)
+
+//! calculate AC and DC values for current original image
+Void WeightPredAnalysis::xCalcACDCParamSlice(TComSlice *const slice)
 {
   //===== calculate AC/DC value =====
   TComPicYuv*   pPic = slice->getPic()->getPicYuvOrg();
-  Int   iSample  = 0;
-
-  // calculate DC/AC value for Y
-  Pel*  pOrg    = pPic->getLumaAddr();
-  Int64  iOrgDCY = xCalcDCValueSlice(slice, pOrg, &iSample);
-  Int64  iOrgNormDCY = ((iOrgDCY+(iSample>>1)) / iSample);
-  pOrg = pPic->getLumaAddr();
-  Int64  iOrgACY  = xCalcACValueSlice(slice, pOrg, iOrgNormDCY);
-
-  // calculate DC/AC value for Cb
-  pOrg = pPic->getCbAddr();
-  Int64  iOrgDCCb = xCalcDCValueUVSlice(slice, pOrg, &iSample);
-  Int64  iOrgNormDCCb = ((iOrgDCCb+(iSample>>1)) / (iSample));
-  pOrg = pPic->getCbAddr();
-  Int64  iOrgACCb  = xCalcACValueUVSlice(slice, pOrg, iOrgNormDCCb);
-
-  // calculate DC/AC value for Cr
-  pOrg = pPic->getCrAddr();
-  Int64  iOrgDCCr = xCalcDCValueUVSlice(slice, pOrg, &iSample);
-  Int64  iOrgNormDCCr = ((iOrgDCCr+(iSample>>1)) / (iSample));
-  pOrg = pPic->getCrAddr();
-  Int64  iOrgACCr  = xCalcACValueUVSlice(slice, pOrg, iOrgNormDCCr);
-
-  wpACDCParam weightACDCParam[3];
-  weightACDCParam[0].iAC = iOrgACY;
-  weightACDCParam[0].iDC = iOrgNormDCY;
-  weightACDCParam[1].iAC = iOrgACCb;
-  weightACDCParam[1].iDC = iOrgNormDCCb;
-  weightACDCParam[2].iAC = iOrgACCr;
-  weightACDCParam[2].iDC = iOrgNormDCCr;
+
+  WPACDCParam weightACDCParam[MAX_NUM_COMPONENT];
+
+  for(Int componentIndex = 0; componentIndex < pPic->getNumberValidComponents(); componentIndex++)
+  {
+    const ComponentID compID = ComponentID(componentIndex);
+
+    // calculate DC/AC value for channel
+
+    const Int iStride = pPic->getStride(compID);
+    const Int iWidth  = pPic->getWidth(compID);
+    const Int iHeight = pPic->getHeight(compID);
+
+    const Int iSample = iWidth*iHeight;
+
+    Int64 iOrgDC = 0;
+    {
+      const Pel *pPel = pPic->getAddr(compID);
+
+      for(Int y = 0; y < iHeight; y++, pPel+=iStride )
+      {
+        for(Int x = 0; x < iWidth; x++ )
+        {
+          iOrgDC += (Int)( pPel[x] );
+        }
+      }
+    }
+
+    const Int64 iOrgNormDC = ((iOrgDC+(iSample>>1)) / iSample);
+
+    Int64 iOrgAC = 0;
+    {
+      const Pel *pPel = pPic->getAddr(compID);
+
+      for(Int y = 0; y < iHeight; y++, pPel += iStride )
+      {
+        for(Int x = 0; x < iWidth; x++ )
+        {
+          iOrgAC += abs( (Int)pPel[x] - (Int)iOrgNormDC );
+        }
+      }
+    }
+
+    const Int fixedBitShift = (slice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag())?RExt__PREDICTION_WEIGHTING_ANALYSIS_DC_PRECISION:0;
+    weightACDCParam[compID].iDC = (((iOrgDC<<fixedBitShift)+(iSample>>1)) / iSample);
+    weightACDCParam[compID].iAC = iOrgAC;
+  }
 
   slice->setWpAcDcParam(weightACDCParam);
-  return (true);
-}
-
-/** store weighted_pred_flag and weighted_bipred_idc values
- * \param weighted_pred_flag
- * \param weighted_bipred_idc
- * \returns Void
- */
-Void  WeightPredAnalysis::xStoreWPparam(Bool weighted_pred_flag, Bool weighted_bipred_flag)
-{
-  m_weighted_pred_flag = weighted_pred_flag;
-  m_weighted_bipred_flag = weighted_bipred_flag;
-}
-
-/** restore weighted_pred_flag and weighted_bipred_idc values
- * \param TComSlice *slice
- * \returns Void
- */
-Void  WeightPredAnalysis::xRestoreWPparam(TComSlice *slice)
-{
-  slice->getPPS()->setUseWP(m_weighted_pred_flag);
-  slice->getPPS()->setWPBiPred(m_weighted_bipred_flag);
-}
-
-/** check weighted pred or non-weighted pred
- * \param TComSlice *slice
- * \returns Void
- */
-Void  WeightPredAnalysis::xCheckWPEnable(TComSlice *slice)
-{
+}
+
+
+//! check weighted pred or non-weighted pred
+Void  WeightPredAnalysis::xCheckWPEnable(TComSlice *const slice)
+{
+  const TComPicYuv *pPic = slice->getPic()->getPicYuvOrg();
+
   Int iPresentCnt = 0;
-  for ( Int iList=0 ; iList<2 ; iList++ )
-  {
-    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
-    {
-      for ( Int iComp=0 ; iComp<3 ;iComp++ ) 
-      {
-        wpScalingParam  *pwp = &(m_wp[iList][iRefIdx][iComp]);
+  for ( UInt lst=0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+    {
+      for(Int componentIndex = 0; componentIndex < pPic->getNumberValidComponents(); componentIndex++)
+      {
+        WPScalingParam  *pwp = &(m_wp[lst][iRefIdx][componentIndex]);
         iPresentCnt += (Int)pwp->bPresentFlag;
       }
@@ -150,13 +141,15 @@
   if(iPresentCnt==0)
   {
-    slice->getPPS()->setUseWP(false);
-    slice->getPPS()->setWPBiPred(false);
-    for ( Int iList=0 ; iList<2 ; iList++ )
-    {
-      for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
-      {
-        for ( Int iComp=0 ; iComp<3 ;iComp++ ) 
-        {
-          wpScalingParam  *pwp = &(m_wp[iList][iRefIdx][iComp]);
+    slice->setTestWeightPred(false);
+    slice->setTestWeightBiPred(false);
+
+    for ( UInt lst=0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
+    {
+      for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+      {
+        for(Int componentIndex = 0; componentIndex < pPic->getNumberValidComponents(); componentIndex++)
+        {
+          WPScalingParam  *pwp = &(m_wp[lst][iRefIdx][componentIndex]);
+
           pwp->bPresentFlag      = false;
           pwp->uiLog2WeightDenom = 0;
@@ -168,23 +161,26 @@
     slice->setWpScaling( m_wp );
   }
-}
-
-/** estimate wp tables for explicit wp
- * \param TComSlice *slice
- * \returns Bool
- */
-Bool  WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *slice)
-{
-  Int iDenom  = 6;
+  else
+  {
+    slice->setTestWeightPred(slice->getPPS()->getUseWP());
+    slice->setTestWeightBiPred(slice->getPPS()->getWPBiPred());
+  }
+}
+
+
+//! estimate wp tables for explicit wp
+Void WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *const slice)
+{
+  Int  iDenom         = 6;
   Bool validRangeFlag = false;
 
   if(slice->getNumRefIdx(REF_PIC_LIST_0)>3)
   {
-    iDenom  = 7;
+    iDenom = 7;
   }
 
   do
   {
-    validRangeFlag = xUpdatingWPParameters(slice, m_wp, iDenom);
+    validRangeFlag = xUpdatingWPParameters(slice, iDenom);
     if (!validRangeFlag)
     {
@@ -193,286 +189,163 @@
   } while (validRangeFlag == false);
 
-  // selecting whether WP is used, or not
-  xSelectWP(slice, m_wp, iDenom);
-  
+  // selecting whether WP is used, or not (fast search)
+  // NOTE: This is not operating on a slice, but the entire picture.
+  xSelectWP(slice, iDenom);
+
   slice->setWpScaling( m_wp );
-
-  return (true);
-}
-
-/** update wp tables for explicit wp w.r.t ramge limitation
- * \param TComSlice *slice
- * \returns Bool
- */
-Bool WeightPredAnalysis::xUpdatingWPParameters(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int log2Denom)
-{
-  Int numPredDir = slice->isInterP() ? 1 : 2;
+}
+
+
+//! update wp tables for explicit wp w.r.t range limitation
+Bool WeightPredAnalysis::xUpdatingWPParameters(TComSlice *const slice, const Int log2Denom)
+{
+  const Int  numComp                    = slice->getPic()->getPicYuvOrg()->getNumberValidComponents();
+  const Bool bUseHighPrecisionWeighting = slice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
+  const Int numPredDir                  = slice->isInterP() ? 1 : 2;
+
+  assert (numPredDir <= Int(NUM_REF_PIC_LIST_01));
+
   for ( Int refList = 0; refList < numPredDir; refList++ )
   {
-    RefPicList  eRefPicList = ( refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    const RefPicList eRefPicList = ( refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
     for ( Int refIdxTemp = 0; refIdxTemp < slice->getNumRefIdx(eRefPicList); refIdxTemp++ )
     {
-      wpACDCParam *currWeightACDCParam, *refWeightACDCParam;
+      WPACDCParam *currWeightACDCParam, *refWeightACDCParam;
       slice->getWpAcDcParam(currWeightACDCParam);
       slice->getRefPic(eRefPicList, refIdxTemp)->getSlice(0)->getWpAcDcParam(refWeightACDCParam);
 
-      for ( Int comp = 0; comp < 3; comp++ )
-      {
-        Int bitDepth = comp ? g_bitDepthC : g_bitDepthY;
-        Int realLog2Denom = log2Denom + bitDepth-8;
-        Int realOffset = ((Int)1<<(realLog2Denom-1));
+      for ( Int comp = 0; comp < numComp; comp++ )
+      {
+        const ComponentID compID        = ComponentID(comp);
+        const Int         bitDepth      = slice->getSPS()->getBitDepth(toChannelType(compID));
+        const Int         range         = bUseHighPrecisionWeighting ? (1<<bitDepth)/2 : 128;
+        const Int         realLog2Denom = log2Denom + (bUseHighPrecisionWeighting ? RExt__PREDICTION_WEIGHTING_ANALYSIS_DC_PRECISION : (bitDepth - 8));
+        const Int         realOffset    = ((Int)1<<(realLog2Denom-1));
 
         // current frame
-        Int64 currDC = currWeightACDCParam[comp].iDC;
-        Int64 currAC = currWeightACDCParam[comp].iAC;
+        const Int64 currDC = currWeightACDCParam[comp].iDC;
+        const Int64 currAC = currWeightACDCParam[comp].iAC;
         // reference frame
-        Int64 refDC = refWeightACDCParam[comp].iDC;
-        Int64 refAC = refWeightACDCParam[comp].iAC;
+        const Int64 refDC  = refWeightACDCParam[comp].iDC;
+        const Int64 refAC  = refWeightACDCParam[comp].iAC;
 
         // calculating iWeight and iOffset params
-        Double dWeight = (refAC==0) ? (Double)1.0 : Clip3( -16.0, 15.0, ((Double)currAC / (Double)refAC) );
-        Int weight = (Int)( 0.5 + dWeight * (Double)(1<<log2Denom) );
-        Int offset = (Int)( ((currDC<<log2Denom) - ((Int64)weight * refDC) + (Int64)realOffset) >> realLog2Denom );
-
-        // Chroma offset range limitation
-        if(comp)
-        {
-          Int pred = ( 128 - ( ( 128*weight)>>(log2Denom) ) );
-          Int deltaOffset = Clip3( -512, 511, (offset - pred) );    // signed 10bit
-          offset = Clip3( -128, 127, (deltaOffset + pred) );        // signed 8bit
-        }
-        // Luma offset range limitation
-        else
-        {
-          offset = Clip3( -128, 127, offset);
+        const Double dWeight = (refAC==0) ? (Double)1.0 : Clip3( -16.0, 15.0, ((Double)currAC / (Double)refAC) );
+        const Int weight     = (Int)( 0.5 + dWeight * (Double)(1<<log2Denom) );
+        const Int offset     = (Int)( ((currDC<<log2Denom) - ((Int64)weight * refDC) + (Int64)realOffset) >> realLog2Denom );
+
+        Int clippedOffset;
+        if(isChroma(compID)) // Chroma offset range limination
+        {
+          const Int pred        = ( range - ( ( range*weight)>>(log2Denom) ) );
+          const Int deltaOffset = Clip3( -4*range, 4*range-1, (offset - pred) ); // signed 10bit
+
+          clippedOffset = Clip3( -range, range-1, (deltaOffset + pred) );  // signed 8bit
+        }
+        else // Luma offset range limitation
+        {
+          clippedOffset = Clip3( -range, range-1, offset);
         }
 
         // Weighting factor limitation
-        Int defaultWeight = (1<<log2Denom);
-        Int deltaWeight = (defaultWeight - weight);
-        if(deltaWeight > 127 || deltaWeight < -128)
-          return (false);
-
-        m_wp[refList][refIdxTemp][comp].bPresentFlag = true;
-        m_wp[refList][refIdxTemp][comp].iWeight = (Int)weight;
-        m_wp[refList][refIdxTemp][comp].iOffset = (Int)offset;
-        m_wp[refList][refIdxTemp][comp].uiLog2WeightDenom = (Int)log2Denom;
-      }
-    }
-  }
-  return (true);
-}
-
-/** select whether weighted pred enables or not. 
- * \param TComSlice *slice
- * \param wpScalingParam
- * \param iDenom
- * \returns Bool
- */
-Bool WeightPredAnalysis::xSelectWP(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int iDenom)
-{
-  TComPicYuv*   pPic = slice->getPic()->getPicYuvOrg();
-  Int iWidth  = pPic->getWidth();
-  Int iHeight = pPic->getHeight();
-  Int iDefaultWeight = ((Int)1<<iDenom);
-  Int iNumPredDir = slice->isInterP() ? 1 : 2;
+        const Int defaultWeight = (1<<log2Denom);
+        const Int deltaWeight   = (defaultWeight - weight);
+
+        if(deltaWeight >= range || deltaWeight < -range)
+        {
+          return false;
+        }
+
+        m_wp[refList][refIdxTemp][comp].bPresentFlag      = true;
+        m_wp[refList][refIdxTemp][comp].iWeight           = weight;
+        m_wp[refList][refIdxTemp][comp].iOffset           = clippedOffset;
+        m_wp[refList][refIdxTemp][comp].uiLog2WeightDenom = log2Denom;
+      }
+    }
+  }
+  return true;
+}
+
+
+//! select whether weighted pred enables or not.
+Bool WeightPredAnalysis::xSelectWP(TComSlice *const slice, const Int log2Denom)
+{
+        TComPicYuv *const pPic                                = slice->getPic()->getPicYuvOrg();
+  const Int               iDefaultWeight                      = ((Int)1<<log2Denom);
+  const Int               iNumPredDir                         = slice->isInterP() ? 1 : 2;
+  const Bool              useHighPrecisionPredictionWeighting = slice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
+
+  assert (iNumPredDir <= Int(NUM_REF_PIC_LIST_01));
 
   for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
   {
-    Int64 iSADWP = 0, iSADnoWP = 0;
-    RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    const RefPicList eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
     for ( Int iRefIdxTemp = 0; iRefIdxTemp < slice->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
     {
-      Pel*  pOrg    = pPic->getLumaAddr();
-      Pel*  pRef    = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getLumaAddr();
-      Int   iOrgStride = pPic->getStride();
-      Int   iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getStride();
-
-      // calculate SAD costs with/without wp for luma
-      iSADWP   = this->xCalcSADvalueWP(g_bitDepthY, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][0].iWeight, weightPredTable[iRefList][iRefIdxTemp][0].iOffset);
-      iSADnoWP = this->xCalcSADvalueWP(g_bitDepthY, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
-
-      pOrg = pPic->getCbAddr();
-      pRef = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCbAddr();
-      iOrgStride = pPic->getCStride();
-      iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCStride();
-
-      // calculate SAD costs with/without wp for chroma cb
-      iSADWP   += this->xCalcSADvalueWP(g_bitDepthC, pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][1].iWeight, weightPredTable[iRefList][iRefIdxTemp][1].iOffset);
-      iSADnoWP += this->xCalcSADvalueWP(g_bitDepthC, pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
-
-      pOrg = pPic->getCrAddr();
-      pRef = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCrAddr();
-
-      // calculate SAD costs with/without wp for chroma cr
-      iSADWP   += this->xCalcSADvalueWP(g_bitDepthC, pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][2].iWeight, weightPredTable[iRefList][iRefIdxTemp][2].iOffset);
-      iSADnoWP += this->xCalcSADvalueWP(g_bitDepthC, pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
-
-      Double dRatio = ((Double)iSADWP / (Double)iSADnoWP);
+      Int64 iSADWP = 0, iSADnoWP = 0;
+
+      for(Int comp=0; comp<pPic->getNumberValidComponents(); comp++)
+      {
+        const ComponentID  compID     = ComponentID(comp);
+              Pel         *pOrg       = pPic->getAddr(compID);
+              Pel         *pRef       = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getAddr(compID);
+        const Int          iOrgStride = pPic->getStride(compID);
+        const Int          iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getStride(compID);
+        const Int          iWidth     = pPic->getWidth(compID);
+        const Int          iHeight    = pPic->getHeight(compID);
+        const Int          bitDepth   = slice->getSPS()->getBitDepth(toChannelType(compID));
+
+        // calculate SAD costs with/without wp for luma
+        iSADWP   += xCalcSADvalueWP(bitDepth, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, log2Denom, m_wp[iRefList][iRefIdxTemp][compID].iWeight, m_wp[iRefList][iRefIdxTemp][compID].iOffset, useHighPrecisionPredictionWeighting);
+        iSADnoWP += xCalcSADvalueWP(bitDepth, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, log2Denom, iDefaultWeight, 0, useHighPrecisionPredictionWeighting);
+      }
+
+      const Double dRatio = ((Double)iSADWP / (Double)iSADnoWP);
       if(dRatio >= (Double)DTHRESH)
       {
-        for ( Int iComp = 0; iComp < 3; iComp++ )
-        {
-          weightPredTable[iRefList][iRefIdxTemp][iComp].bPresentFlag = false;
-          weightPredTable[iRefList][iRefIdxTemp][iComp].iOffset = (Int)0;
-          weightPredTable[iRefList][iRefIdxTemp][iComp].iWeight = (Int)iDefaultWeight;
-          weightPredTable[iRefList][iRefIdxTemp][iComp].uiLog2WeightDenom = (Int)iDenom;
-        }
-      }
-    }
-  }
-  return (true);
-}
-
-/** calculate DC value of original image for luma. 
- * \param TComSlice *slice
- * \param Pel *pPel
- * \param Int *iSample
- * \returns Int64
- */
-Int64 WeightPredAnalysis::xCalcDCValueSlice(TComSlice *slice, Pel *pPel, Int *iSample)
-{
-  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
-  Int iStride = pPic->getStride();
-
-  *iSample = 0;
-  Int iWidth  = pPic->getWidth();
-  Int iHeight = pPic->getHeight();
-  *iSample = iWidth*iHeight;
-  Int64 iDC = xCalcDCValue(pPel, iWidth, iHeight, iStride);
-
-  return (iDC);
-}
-
-/** calculate AC value of original image for luma. 
- * \param TComSlice *slice
- * \param Pel *pPel
- * \param Int iDC
- * \returns Int64
- */
-Int64 WeightPredAnalysis::xCalcACValueSlice(TComSlice *slice, Pel *pPel, Int64 iDC)
-{
-  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
-  Int iStride = pPic->getStride();
-
-  Int iWidth  = pPic->getWidth();
-  Int iHeight = pPic->getHeight();
-  Int64 iAC = xCalcACValue(pPel, iWidth, iHeight, iStride, iDC);
-
-  return (iAC);
-}
-
-/** calculate DC value of original image for chroma. 
- * \param TComSlice *slice
- * \param Pel *pPel
- * \param Int *iSample
- * \returns Int64
- */
-Int64 WeightPredAnalysis::xCalcDCValueUVSlice(TComSlice *slice, Pel *pPel, Int *iSample)
-{
-  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
-  Int iCStride = pPic->getCStride();
-
-  *iSample = 0;
-  Int iWidth  = pPic->getWidth()>>1;
-  Int iHeight = pPic->getHeight()>>1;
-  *iSample = iWidth*iHeight;
-  Int64 iDC = xCalcDCValue(pPel, iWidth, iHeight, iCStride);
-
-  return (iDC);
-}
-
-/** calculate AC value of original image for chroma. 
- * \param TComSlice *slice
- * \param Pel *pPel
- * \param Int iDC
- * \returns Int64
- */
-Int64 WeightPredAnalysis::xCalcACValueUVSlice(TComSlice *slice, Pel *pPel, Int64 iDC)
-{
-  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
-  Int iCStride = pPic->getCStride();
-
-  Int iWidth  = pPic->getWidth()>>1;
-  Int iHeight = pPic->getHeight()>>1;
-  Int64 iAC = xCalcACValue(pPel, iWidth, iHeight, iCStride, iDC);
-
-  return (iAC);
-}
-
-/** calculate DC value. 
- * \param Pel *pPel
- * \param Int iWidth
- * \param Int iHeight
- * \param Int iStride
- * \returns Int64
- */
-Int64 WeightPredAnalysis::xCalcDCValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride)
-{
-  Int x, y;
-  Int64 iDC = 0;
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iDC += (Int)( pPel[x] );
-    }
-    pPel += iStride;
-  }
-  return (iDC);
-}
-
-/** calculate AC value. 
- * \param Pel *pPel
- * \param Int iWidth
- * \param Int iHeight
- * \param Int iStride
- * \param Int iDC
- * \returns Int64
- */
-Int64 WeightPredAnalysis::xCalcACValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride, Int64 iDC)
-{
-  Int x, y;
-  Int64 iAC = 0;
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iAC += abs( (Int)pPel[x] - (Int)iDC );
-    }
-    pPel += iStride;
-  }
-  return (iAC);
-}
-
-/** calculate SAD values for both WP version and non-WP version. 
- * \param Pel *pOrgPel
- * \param Pel *pRefPel
- * \param Int iWidth
- * \param Int iHeight
- * \param Int iOrgStride
- * \param Int iRefStride
- * \param Int iDenom
- * \param Int iWeight
- * \param Int iOffset
- * \returns Int64
- */
-Int64 WeightPredAnalysis::xCalcSADvalueWP(Int bitDepth, Pel *pOrgPel, Pel *pRefPel, Int iWidth, Int iHeight, Int iOrgStride, Int iRefStride, Int iDenom, Int iWeight, Int iOffset)
-{
-  Int x, y;
+        for(Int comp=0; comp<pPic->getNumberValidComponents(); comp++)
+        {
+          m_wp[iRefList][iRefIdxTemp][comp].bPresentFlag      = false;
+          m_wp[iRefList][iRefIdxTemp][comp].iOffset           = 0;
+          m_wp[iRefList][iRefIdxTemp][comp].iWeight           = iDefaultWeight;
+          m_wp[iRefList][iRefIdxTemp][comp].uiLog2WeightDenom = log2Denom;
+        }
+      }
+    }
+  }
+
+  return true;
+}
+
+
+//! calculate SAD values for both WP version and non-WP version.
+Int64 WeightPredAnalysis::xCalcSADvalueWP(const Int   bitDepth,
+                                          const Pel  *pOrgPel,
+                                          const Pel  *pRefPel,
+                                          const Int   iWidth,
+                                          const Int   iHeight,
+                                          const Int   iOrgStride,
+                                          const Int   iRefStride,
+                                          const Int   iLog2Denom,
+                                          const Int   iWeight,
+                                          const Int   iOffset,
+                                          const Bool  useHighPrecisionPredictionWeighting)
+{
+  const Int64 iSize          = iWidth*iHeight;
+  const Int64 iRealLog2Denom = useHighPrecisionPredictionWeighting ? iLog2Denom : (iLog2Denom + (bitDepth - 8));
+
   Int64 iSAD = 0;
-  Int64 iSize   = iWidth*iHeight;
-  Int64 iRealDenom = iDenom + bitDepth-8;
-  for( y = 0; y < iHeight; y++ )
-  {
-    for( x = 0; x < iWidth; x++ )
-    {
-      iSAD += ABS(( ((Int64)pOrgPel[x]<<(Int64)iDenom) - ( (Int64)pRefPel[x] * (Int64)iWeight + ((Int64)iOffset<<iRealDenom) ) ) );
+  for( Int y = 0; y < iHeight; y++ )
+  {
+    for( Int x = 0; x < iWidth; x++ )
+    {
+      iSAD += ABS(( ((Int64)pOrgPel[x]<<(Int64)iLog2Denom) - ( (Int64)pRefPel[x] * (Int64)iWeight + ((Int64)iOffset<<iRealLog2Denom) ) ) );
     }
     pOrgPel += iOrgStride;
     pRefPel += iRefStride;
   }
+
   return (iSAD/iSize);
 }
-
-
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -38,5 +38,5 @@
 #define __WEIGHTPREDANALYSIS__
 
-#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/CommonDef.h"
 #include "../TLibCommon/TComSlice.h"
 #include "TEncCavlc.h"
@@ -44,19 +44,25 @@
 class  WeightPredAnalysis
 {
-  Bool m_weighted_pred_flag;
-  Bool  m_weighted_bipred_flag;
-  wpScalingParam  m_wp[2][MAX_NUM_REF][3];
+private:
 
-  Int64   xCalcDCValueSlice(TComSlice *slice, Pel *pPel,Int *iSample);
-  Int64   xCalcACValueSlice(TComSlice *slice, Pel *pPel, Int64 iDC);
-  Int64   xCalcDCValueUVSlice(TComSlice *slice, Pel *pPel, Int *iSample);
-  Int64   xCalcACValueUVSlice(TComSlice *slice, Pel *pPel, Int64 iDC);
-  Int64   xCalcSADvalueWPSlice(TComSlice *slice, Pel *pOrgPel, Pel *pRefPel, Int iDenom, Int iWeight, Int iOffset);
+  // member variables
+  WPScalingParam  m_wp[NUM_REF_PIC_LIST_01][MAX_NUM_REF][MAX_NUM_COMPONENT];
 
-  Int64   xCalcDCValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride);
-  Int64   xCalcACValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride, Int64 iDC);
-  Int64   xCalcSADvalueWP(Int bitDepth, Pel *pOrgPel, Pel *pRefPel, Int iWidth, Int iHeight, Int iOrgStride, Int iRefStride, Int iDenom, Int iWeight, Int iOffset);
-  Bool    xSelectWP(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int iDenom);
-  Bool    xUpdatingWPParameters(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int log2Denom);
+  // member functions
+
+  Bool  xSelectWP            (TComSlice *const slice, const Int log2Denom);
+  Bool  xUpdatingWPParameters(TComSlice *const slice, const Int log2Denom);
+
+  Int64 xCalcSADvalueWP      (const Int   bitDepth,
+                              const Pel  *pOrgPel,
+                              const Pel  *pRefPel,
+                              const Int   iWidth,
+                              const Int   iHeight,
+                              const Int   iOrgStride,
+                              const Int   iRefStride,
+                              const Int   iLog2Denom,
+                              const Int   iWeight,
+                              const Int   iOffset,
+                              const Bool  useHighPrecisionPredictionWeighting);
 
 public:
@@ -65,12 +71,8 @@
 
   // WP analysis :
-  Bool  xCalcACDCParamSlice(TComSlice *slice);
-  Bool  xEstimateWPParamSlice(TComSlice *slice);
-  Void  xStoreWPparam(Bool weighted_pred_flag, Bool weighted_bipred_flag);
-  Void  xRestoreWPparam(TComSlice *slice);
-  Void  xCheckWPEnable(TComSlice *slice);
+  Void  xCalcACDCParamSlice  (TComSlice *const slice);
+  Void  xEstimateWPParamSlice(TComSlice *const slice);
+  Void  xCheckWPEnable       (TComSlice *const slice);
 };
 
 #endif // __WEIGHTPREDANALYSIS__
-
-
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibExtractor/TExtrTop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 1200)
@@ -37,5 +37,5 @@
 
 #include "TExtrTop.h"
-#if H_MV
+#if NH_MV
 TExtrTop::TExtrTop()
 {
@@ -56,10 +56,12 @@
 {
   //extraction now has to be done using layer_id
-  UInt uiLayerId      = nalu.m_layerId;
+  UInt uiLayerId      = nalu.m_nuhLayerId;
 
   
   // Initialize entropy decoder
   m_cEntropyDecoder.setEntropyDecoder( &m_cCavlcDecoder );
-  m_cEntropyDecoder.setBitstream     ( nalu.m_Bitstream );
+
+  TComInputBitstream inpBs = nalu.getBitstream(); 
+  m_cEntropyDecoder.setBitstream     ( &inpBs );
   
   if ( nalu.m_nalUnitType == NAL_UNIT_VPS )
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibExtractor/TExtrTop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibExtractor/TExtrTop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibExtractor/TExtrTop.h	(revision 1200)
@@ -46,5 +46,5 @@
 #include <set>
 
-#if H_MV
+#if NH_MV
 // ====================================================================================================================
 // Class definition
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenFilter.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 1200)
@@ -36,8 +36,9 @@
 #include "TRenFilter.h"
 #include "TRenInterpFilter.h"
-#if H_3D
+#if NH_3D
 
 ///// COMMON /////
-Void TRenFilter::setSubPelShiftLUT( Int iLutPrec, Int** piSubPelShiftLUT, Int iShift )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::setSubPelShiftLUT( Int iLutPrec, Int** piSubPelShiftLUT, Int iShift )
 {
   //ToDo: use same rounding for left and right
@@ -59,6 +60,6 @@
   }
 }
-
-Void TRenFilter::setupZLUT( Bool bBlendUseDistWeight, Int iBlendZThresPerc, Int iRelDistToLeft, Int** ppiBaseShiftLUTLeft, Int** ppiBaseShiftLUTRight, Int& riBlendZThres, Int& riBlendDistWeight, Int* piInvZLUTLeft, Int* piInvZLUTRight )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::setupZLUT( Bool bBlendUseDistWeight, Int iBlendZThresPerc, Int iRelDistToLeft, Int** ppiBaseShiftLUTLeft, Int** ppiBaseShiftLUTRight, Int& riBlendZThres, Int& riBlendDistWeight, Int* piInvZLUTLeft, Int* piInvZLUTRight )
 {
   AOT( iRelDistToLeft == -1 );
@@ -75,5 +76,6 @@
 }
 
-Void TRenFilter::filledToUsedPelMap( PelImage* pcFilledImage, PelImage* pcUsedPelsImage, Int iUsedPelMapMarExt )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::filledToUsedPelMap( PelImage* pcFilledImage, PelImage* pcUsedPelsImage, Int iUsedPelMapMarExt )
 {
   // Convert to binary map
@@ -156,5 +158,6 @@
 
 /////////// Copy /////////////
-Void TRenFilter::copy(Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::copy(const Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
 {
   xDistributeArray(pcInputPlaneData, iInputStride, 1, 1, iWidth, iHeight ,pcOutputPlaneData, iOutputStride, 1 , 1 );
@@ -163,6 +166,6 @@
 
 /////////// Horizontal Mirror ///////////
-template <typename T>
-Void TRenFilter::mirrorHor( TRenImage<T> *pcImage )
+template<UInt bitDepth> template <typename T> 
+Void TRenFilter<bitDepth>::mirrorHor( TRenImage<T> *pcImage )
 {
   for (UInt uCurPlane = 0 ; uCurPlane < pcImage->getNumberOfPlanes(); uCurPlane++ )
@@ -172,6 +175,6 @@
 }
 
-template <typename T>
-Void TRenFilter::mirrorHor( TRenImagePlane<T> *pcImagePlane )
+template<UInt bitDepth> template <typename T> 
+Void TRenFilter<bitDepth>::mirrorHor( TRenImagePlane<T> *pcImagePlane )
 {
   T* pcPlaneData = pcImagePlane->getPlaneDataOrg();
@@ -194,5 +197,6 @@
 
 /////////// Comparison ///////////
-Int64 TRenFilter::SSE   (PelImagePlane* pcInputPlane1, PelImagePlane* pcInputPlane2, Bool bLuma )
+template<UInt bitDepth>
+Int64 TRenFilter<bitDepth>::SSE   (PelImagePlane* pcInputPlane1, PelImagePlane* pcInputPlane2, Bool bLuma )
 {
   UInt uiWidth     = pcInputPlane1->getWidth();
@@ -208,10 +212,11 @@
 }
 
-Int64 TRenFilter::SSE( Pel* piSrc1, Int iSrcStride1, Int iWidth, Int iHeight,  Pel* piSrc2, Int iSrcStride2, Bool bLuma )
+template<UInt bitDepth>
+Int64 TRenFilter<bitDepth>::SSE( Pel* piSrc1, Int iSrcStride1, Int iWidth, Int iHeight,  Pel* piSrc2, Int iSrcStride2, Bool bLuma )
 {
   Int64 iSSE = 0;
 
 
-  Int iShift = DISTORTION_PRECISION_ADJUSTMENT( ( bLuma ? g_bitDepthY : g_bitDepthC ) - 8 ) << 1 ;
+  Int iShift = ( bitDepth  - 8 ) << 1 ;
   for(Int iPosY = 0; iPosY < iHeight; iPosY++)
   {
@@ -227,6 +232,6 @@
 }
 
-template <typename T>
-Bool TRenFilter::compare( TRenImage<T> *pInputImage1, TRenImage<T> *pInputImage2 )
+template<UInt bitDepth> template <typename T> 
+Bool TRenFilter<bitDepth>::compare( TRenImage<T> *pInputImage1, TRenImage<T> *pInputImage2 )
 {
   Bool bIsEqual = true;
@@ -238,6 +243,6 @@
 }
 
-template <typename T>
-Bool TRenFilter::compare   (TRenImagePlane<T>* pcInputPlane1  , TRenImagePlane<T>* pcInputPlane2   )
+template<UInt bitDepth> template <typename T> 
+Bool TRenFilter<bitDepth>::compare   (TRenImagePlane<T>* pcInputPlane1  , TRenImagePlane<T>* pcInputPlane2   )
 {
   UInt uiWidth  = pcInputPlane1->getWidth();
@@ -265,9 +270,8 @@
 
 /////////// Sampling ///////////
-
-inline Void TRenFilter::sampleUp2Tap13(PelImage* pcInputImage, PelImage* pcOutputImage)
+template<UInt bitDepth>
+inline Void TRenFilter<bitDepth>::sampleUp2Tap13(PelImage* pcInputImage, PelImage* pcOutputImage)
 { // UpSampling from JSVM Software (DownConvertStatic) ???
 
-  AOF( g_bitDepthC == g_bitDepthY ); 
   UInt uiNumPlanes = pcInputImage->getNumberOfPlanes();
 
@@ -400,5 +404,5 @@
       {
         // Scale and copy to image buffer.
-        pcOutputPlaneData[iOffset+i] = ClipY((Pel) ((piDst[i] + iAddH) / iDivH));
+        pcOutputPlaneData[iOffset+i] = ClipBD((Pel) ((piDst[i] + iAddH) / iDivH), bitDepth);
       }
     }
@@ -410,6 +414,6 @@
 }
 
-
-Void TRenFilter::sampleDown2Tap13(PelImage* pcInputImage, PelImage* pcOutputImage)
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleDown2Tap13(PelImage* pcInputImage, PelImage* pcOutputImage)
 { // DownSampling from JSVM Software (DownConvertStatic) ??
 
@@ -422,8 +426,7 @@
 };
 
-Void TRenFilter::sampleDown2Tap13( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleDown2Tap13( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
 { // DownSampling from JSVM Software (DownConvertStatic) ??
-  
-  AOF( g_bitDepthC == g_bitDepthY ); 
 
   Int iOffset, iPosX, iPosY, k;
@@ -549,5 +552,5 @@
     {
       // Scale and copy back to image buffer.
-      pcOutputPlaneData[iOutputStride*iPosY+iPosX] = ClipY( ( Pel) ( (piDst[iPosY] + iAddV) / iDivV));
+      pcOutputPlaneData[iOutputStride*iPosY+iPosX] = ClipBD( ( Pel) ( (piDst[iPosY] + iAddV) / iDivV), bitDepth );
     }
   }
@@ -557,5 +560,6 @@
 }
 
-Void TRenFilter::sampleDown2Tap13(PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane)
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleDown2Tap13(PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane)
 { // DownSampling from JSVM Software (DownConvertStatic) ??
   Int iWidth       = pcInputPlane->getWidth();
@@ -574,7 +578,7 @@
 };
 
-Void TRenFilter::sampleVerDown2Tap13( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad)
-{ 
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleVerDown2Tap13( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad)
+{   
   // DownSampling from JSVM Software (DownConvertStatic) ??
   Int iWidth       = pcInputPlane->getWidth();
@@ -622,5 +626,5 @@
 
       Int iSum = iTmp4 + iTmp3 - iTmp2 + ((iTmp0 + iTmp4 + iTmp5 - iTmp2) << 1) + ( ( iTmp3 - iTmp1)  << 2) + (  iTmp5 << 3 ) + (( iTmp4 + iTmp5 ) << 4);
-      pcOutputPlaneData[ iXPos ] = (Pel) ClipY((iSum + 32) >> 6);
+      pcOutputPlaneData[ iXPos ] = (Pel) ClipBD((iSum + 32) >> 6, bitDepth);
       pcTmpIn++;
     }
@@ -630,8 +634,8 @@
 };
 
-Void TRenFilter::sampleHorDown2Tap13( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleHorDown2Tap13( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad )
 { 
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
-  // DownSampling from JSVM Software (DownConvertStatic) ??
+    // DownSampling from JSVM Software (DownConvertStatic) ??
   Int iWidth       = pcInputPlane->getWidth();
   Int iHeight      = pcInputPlane->getHeight();
@@ -663,5 +667,5 @@
 
       Int iSum = iTmp4 + iTmp3 - iTmp2 + ((iTmp0 + iTmp4 + iTmp5 - iTmp2) << 1) + ( ( iTmp3 - iTmp1)  << 2) + (  iTmp5 << 3 ) + (( iTmp4 + iTmp5 ) << 4);
-      pcOutputPlaneData[ iXPos ] = (Pel) ClipY((iSum + 32) >> 6);
+      pcOutputPlaneData[ iXPos ] = (Pel) ClipBD((iSum + 32) >> 6, bitDepth);
       pcTmpIn += 2;
     }
@@ -671,5 +675,6 @@
 };
 
-inline Pel TRenFilter::xMedian3(Pel* pcData)
+template<UInt bitDepth>
+inline Pel TRenFilter<bitDepth>::xMedian3(Pel* pcData)
 {
   Bool bGT01 = pcData[0] >  pcData[1];
@@ -680,6 +685,6 @@
 }
 
-
-Void TRenFilter::lineMedian3( PelImage* pcImage )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::lineMedian3( PelImage* pcImage )
 {
 
@@ -722,6 +727,6 @@
 }
 
-
-Void TRenFilter::convRect( PelImage* pcImage, UInt uiSize )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::convRect( PelImage* pcImage, UInt uiSize )
 {
   DoubleImage cKernel(uiSize, uiSize,1,0);
@@ -730,5 +735,6 @@
 }
 
-Void TRenFilter::binominal( PelImage* pcInputImage, PelImage* pcOutputImage, UInt uiSize )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::binominal( PelImage* pcInputImage, PelImage* pcOutputImage, UInt uiSize )
 {
   assert( pcInputImage->getNumberOfFullPlanes()   == pcOutputImage->getNumberOfFullPlanes  () );
@@ -747,5 +753,6 @@
 }
 
-Void TRenFilter::binominal( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, UInt uiSize )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::binominal( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, UInt uiSize )
 {
   Int iWidth  = pcInputPlane ->getWidth ();
@@ -777,14 +784,14 @@
   {
   case 1:
-    fpFilter = &TRenFilter::xFiltBinom3;
+    fpFilter = &TRenFilter<bitDepth>::xFiltBinom3;
     break;
   case 2:
-    fpFilter = &TRenFilter::xFiltBinom5;
+    fpFilter = &TRenFilter<bitDepth>::xFiltBinom5;
     break;
   case 3:
-    fpFilter = &TRenFilter::xFiltBinom7;
+    fpFilter = &TRenFilter<bitDepth>::xFiltBinom7;
     break;
   case 4:
-    fpFilter = &TRenFilter::xFiltBinom9;
+    fpFilter = &TRenFilter<bitDepth>::xFiltBinom9;
     break;
   default:
@@ -818,16 +825,15 @@
 }
 
-Pel TRenFilter::xFiltBinom3( Pel* pcInputData, Int iStride )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+Pel TRenFilter<bitDepth>::xFiltBinom3( Pel* pcInputData, Int iStride )
+{
   Int iSum = pcInputData[-1 * iStride ] + pcInputData[ 0 ] +  (pcInputData[iStride ] << 1 );
-  return ClipY( (iSum +  2) >>  2 );
-}
-
-Pel TRenFilter::xFiltBinom5( Pel* pcInputData, Int iStride )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
-  // { 1,4,6,4,1 }
+  return ClipBD( (iSum +  2) >>  2 , bitDepth);
+}
+
+template<UInt bitDepth>
+Pel TRenFilter<bitDepth>::xFiltBinom5( Pel* pcInputData, Int iStride )
+{
+    // { 1,4,6,4,1 }
   Int iStride0  = 0;
   Int iStrideM1 = iStride0  - iStride;
@@ -841,11 +847,11 @@
 
   Int iSum = iTmp0 +  (iTmp2 << 1) + ((iTmp1 + iTmp2) << 2);
-  return ClipY( (iSum +  8) >>  4 );
-}
-
-Pel TRenFilter::xFiltBinom7( Pel* pcInputData, Int iStride )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
-  // { 1,6,15,20,15,6,1 }
+  return ClipBD( (iSum +  8) >>  4 , bitDepth);
+}
+
+template<UInt bitDepth>
+Pel TRenFilter<bitDepth>::xFiltBinom7( Pel* pcInputData, Int iStride )
+{
+    // { 1,6,15,20,15,6,1 }
   Int iStride0  = 0;
   Int iStrideM1 = iStride0  - iStride;
@@ -863,10 +869,10 @@
   Int iSum = iTmp0 - iTmp2 + ( iTmp1  << 1) + ( (iTmp1 + iTmp3) << 2) + ((iTmp2 + iTmp3) << 4);
 
-  return ClipY( (iSum +  32) >>  6 );
-}
-
-Pel TRenFilter::xFiltBinom9( Pel* pcInputData, Int iStride )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+  return ClipBD( (iSum +  32) >>  6 , bitDepth);
+}
+
+template<UInt bitDepth>
+Pel TRenFilter<bitDepth>::xFiltBinom9( Pel* pcInputData, Int iStride )
+{  
   // {  1     8    28    56    70    56    28     8     1 }
   Int iStride0  = 0;
@@ -888,9 +894,9 @@
   Int iSum = iTmp0 + ((iTmp4 ) << 1) + ( ( iTmp4 - iTmp2 ) << 2) +  ( (iTmp1 - iTmp3) << 3 ) +  ((iTmp2 ) << 5) + ((iTmp3+ iTmp4 ) << 6);
 
-  return ClipY( (iSum +  128) >>  8 );
-}
-
-
-Pel TRenFilter::interpCHSpline(Double dX, Double dS0, Double dS1, Int iQ0, Int iQ1, Int iQ2, Int iQ3)
+  return ClipBD( (iSum +  128) >>  8 , bitDepth);
+}
+
+template<UInt bitDepth>
+Pel TRenFilter<bitDepth>::interpCHSpline(Double dX, Double dS0, Double dS1, Int iQ0, Int iQ1, Int iQ2, Int iQ3)
 {
   Double dSq = (dX - dS0) / (dS1 - dS0);
@@ -916,5 +922,6 @@
 }
 
-Void TRenFilter::diffHorSym(PelImage* pcInputImage, IntImage* pcOutputImage)
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::diffHorSym(PelImage* pcInputImage, IntImage* pcOutputImage)
 {
   for (UInt uiCurPlane = 0; uiCurPlane < pcInputImage->getNumberOfPlanes(); uiCurPlane++)
@@ -924,5 +931,6 @@
 }
 
-Void TRenFilter::diffHorSym(PelImagePlane* pcInputPlane, IntImagePlane* pcOutputPlane)
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::diffHorSym(PelImagePlane* pcInputPlane, IntImagePlane* pcOutputPlane)
 {
   UInt uiInputStride = pcInputPlane ->getStride();
@@ -950,5 +958,6 @@
 }
 
-Void TRenFilter::laplace( DoubleImage* pcInputImage, DoubleImage* pcOutputImage )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::laplace( DoubleImage* pcInputImage, DoubleImage* pcOutputImage )
 {
   for (UInt uiCurPlane = 0; uiCurPlane < pcInputImage->getNumberOfPlanes(); uiCurPlane++)
@@ -1022,6 +1031,6 @@
 }
 
-
-Void TRenFilter::conv( PelImage* pcImage, DoubleImage* pcKernel )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::conv( PelImage* pcImage, DoubleImage* pcKernel )
 {
   PelImage* pcTemp = pcImage->create();
@@ -1096,7 +1105,8 @@
 
 // Horizontal Up sampling luma
-Void TRenFilter::sampleHorUp( Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
-{
-  TRenInterpFilter cFilter;
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleHorUp( Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  TRenInterpFilter<bitDepth> cFilter;
   switch ( iLog2HorSampFac )
   {
@@ -1118,5 +1128,6 @@
 
 // horizontal up sampling chroma
-Void TRenFilter::sampleCHorUp(Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleCHorUp(Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
 {
   switch ( iLog2HorSampFac )
@@ -1127,16 +1138,17 @@
   case 1:
     xDistributeArray( pcInputPlaneData,   iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                  , iOutputStride, 2 , 1 );
-    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +1, iOutputStride, 2 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +1, iOutputStride, 2 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VPS04_C_HAL );
     break;
   case 2:
     xDistributeArray( pcInputPlaneData,   iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                  , iOutputStride, 4 , 1 );
-    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +1, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA0 );
-    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +2, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
-    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +3, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA1 );
-    break;
-  }
-}
-
-Void TRenFilter::sampleCUpHorUp( Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +1, iOutputStride, 4 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +2, iOutputStride, 4 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +3, iOutputStride, 4 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_QUA1 );
+    break;
+  }
+}
+
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleCUpHorUp( Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
 {
 
@@ -1145,24 +1157,24 @@
   case 0:
     xDistributeArray( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData                -2, iOutputStride, 2,  2 );
-    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-2, iOutputStride, 2 , 2, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 2, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData+1                , iOutputStride, 2 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-2, iOutputStride, 2 , 2, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 2, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData+1                , iOutputStride, 2 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VPS04_C_HAL );
     break;
   case 1:
     xDistributeArray( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData                -4, iOutputStride, 4 , 2 );
-    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-4, iOutputStride, 4 , 2, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +1, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA0 );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +2, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +3, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA1 );
+    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-4, iOutputStride, 4 , 2, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +1, iOutputStride, 4 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +2, iOutputStride, 4 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +3, iOutputStride, 4 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_QUA1 );
     break;
   case 2:
     xDistributeArray( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData                -8, iOutputStride, 8 , 2 );
-    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-8, iOutputStride, 8 , 2, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +1, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_OCT0 );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +2, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA0 );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +3, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_OCT1 );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +4, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +5, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_OCT2 );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +6, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA1 );
-    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +7, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_OCT3 );
+    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-8, iOutputStride, 8 , 2, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +1, iOutputStride, 8 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_OCT0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +2, iOutputStride, 8 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +3, iOutputStride, 8 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_OCT1 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +4, iOutputStride, 8 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +5, iOutputStride, 8 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_OCT2 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +6, iOutputStride, 8 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_QUA1 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +7, iOutputStride, 8 , 1, &TRenInterpFilter<REN_BIT_DEPTH>::xCTI_Filter_VP04_C_OCT3 );
     break;
   }
@@ -1171,5 +1183,6 @@
 // Down Sampling
 // Down sample luma
-Void TRenFilter::sampleHorDown(Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleHorDown(Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
 {
   switch ( iLog2HorSampFac )
@@ -1187,6 +1200,6 @@
 }
 
-
-Void TRenFilter::sampleCHorDown(Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleCHorDown(Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
 {
   //GT: currently the same as for luma
@@ -1197,5 +1210,6 @@
 
 // Up sampling chroma
-Void TRenFilter::sampleCDownHorDown( Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iInputHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::sampleCDownHorDown( Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iInputHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
 {
   // create buffer
@@ -1219,5 +1233,6 @@
 }
 
-Void TRenFilter::xDistributeArray(Pel* pcSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* pcDst, Int iDstStride, Int iDstStepX, Int iDstStepY)
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::xDistributeArray(const Pel* pcSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* pcDst, Int iDstStride, Int iDstStepX, Int iDstStepY)
 {
   iDstStride *= iDstStepY;
@@ -1226,5 +1241,5 @@
   {
     Pel* pcCurDst = pcDst;
-    Pel* pcCurSrc  = pcSrc;
+    const Pel* pcCurSrc  = pcSrc;
     for (Int iXPos = 0; iXPos < iWidth; iXPos ++)
     {
@@ -1239,11 +1254,11 @@
 }
 
-Void TRenFilter::xInterpHorChroma( Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::xInterpHorChroma( Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter )
+{
   Int   iSum;
   Pel*  piSrcTmp;
 
-  TRenInterpFilter cFilter;
+  TRenInterpFilter<REN_BIT_DEPTH> cFilter;
   for ( Int y = iHeight; y != 0; y-- )
   {
@@ -1252,5 +1267,5 @@
     {
       iSum      = (cFilter.*fpFilter)( piSrcTmp,  iSrcStepX );
-      piDst[x * iDstStepX ] =  ClipC ((iSum +  32) >>  6 );
+      piDst[x * iDstStepX ] =  ClipBD ((iSum +  32) >>  6 , bitDepth);
       piSrcTmp+= iSrcStepX;
     }
@@ -1260,11 +1275,11 @@
 }
 
-Void TRenFilter::xInterpVerChroma( Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::xInterpVerChroma( Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter )
+{  
   Int   iSum;
   Pel*  piSrcTmp;
 
-  TRenInterpFilter cFilter;
+  TRenInterpFilter<bitDepth> cFilter;
   for ( Int y = iHeight; y != 0; y-- )
   {
@@ -1273,5 +1288,5 @@
     {
       iSum      = (cFilter.*fpFilter)( piSrcTmp,  iSrcStepY * iSrcStride );
-      piDst[x * iDstStepX ]  =  ClipC ((iSum +  32) >>  6 );
+      piDst[x * iDstStepX ]  =  ClipBD ((iSum +  32) >>  6, bitDepth );
       piSrcTmp += iSrcStepX;
     }
@@ -1281,9 +1296,7 @@
 }
 
-
-Void TRenFilter::xSampleDownHor2( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
-{
-  
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::xSampleDownHor2( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{ 
 
   Int   iSum;
@@ -1298,5 +1311,5 @@
       // { 1,2,1 }
       iSum = piSrcTmp[0] + piSrcTmp[2] +  (piSrcTmp[1] << 1);
-      piDst[x] = ClipY( (iSum +  2) >>  2 );
+      piDst[x] = ClipBD( (iSum +  2) >>  2 , bitDepth);
       piSrcTmp += 2;
     }
@@ -1306,8 +1319,7 @@
 };
 
-Void TRenFilter::xSampleDownVer2( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iSrcHeight, Pel* piDst, Int iDstStride  )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::xSampleDownVer2( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iSrcHeight, Pel* piDst, Int iDstStride  )
+{
   Int   iSum;
   Pel*  piSrcTmp;
@@ -1320,5 +1332,5 @@
       // { 1,2,1 }
       iSum = piSrcTmp[0] + piSrcTmp[ iSrcStride << 1] +  (piSrcTmp[ iSrcStride ] << 1);
-      piDst[x] = ClipY( (iSum +  2) >>  2 );
+      piDst[x] = ClipBD( (iSum +  2) >>  2, bitDepth );
       piSrcTmp += 1;
     }
@@ -1328,7 +1340,7 @@
 };
 
-Void TRenFilter::xSampleDownHor4( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::xSampleDownHor4( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{ 
 
   Int   iSum;
@@ -1348,5 +1360,5 @@
 
       iSum = iTmp0 +  (iTmp2 << 1) + ((iTmp1 + iTmp2) << 2);
-      piDst[x] = ClipY( (iSum +  8) >>  4 );
+      piDst[x] = ClipBD( (iSum +  8) >>  4, bitDepth );
       piSrcTmp += 4;
     }
@@ -1356,8 +1368,7 @@
 };
 
-Void TRenFilter::xSampleDownHor8( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
-{
-  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::xSampleDownHor8( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{
   Int   iSum;
   Pel*  piSrcTmp;
@@ -1377,5 +1388,5 @@
 
       iSum = iTmp0 - iTmp2 + ( iTmp1  << 1) + ( (iTmp1 + iTmp3) << 2) + ((iTmp2 + iTmp3) << 4);
-      piDst[x] = ClipY( (iSum +  32) >>  6 );
+      piDst[x] = ClipBD( (iSum +  32) >>  6 , bitDepth);
       piSrcTmp += 8;
     }
@@ -1385,5 +1396,6 @@
 };
 
-Void TRenFilter::xDilate( Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iSize, Bool bVerticalDir, Bool bToTopOrLeft )
+template<UInt bitDepth>
+Void TRenFilter<bitDepth>::xDilate( Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iSize, Bool bVerticalDir, Bool bToTopOrLeft )
 {
   Int iFDimStart   = 0;
@@ -1452,11 +1464,13 @@
 
 
-template Bool TRenFilter::compare   (TRenImage<Pel     >*, TRenImage<Pel>*      );
-template Bool TRenFilter::compare   (TRenImagePlane<Pel>*, TRenImagePlane<Pel>* );
-
-template Void TRenFilter::mirrorHor(        TRenImage<Double>        *pcImage );
-template Void TRenFilter::mirrorHor(        TRenImage<Pel>           *pcImage );
-template Void TRenFilter::mirrorHor(        TRenImage<Int>           *pcImage );
-template Void TRenFilter::mirrorHor(        TRenImagePlane<Pel>      *pcImagePlane );
+template class TRenFilter<REN_BIT_DEPTH>;
+
+template Bool TRenFilter<REN_BIT_DEPTH>::compare   (TRenImage<Pel     >*, TRenImage<Pel>*      );
+template Bool TRenFilter<REN_BIT_DEPTH>::compare   (TRenImagePlane<Pel>*, TRenImagePlane<Pel>* );
+                         
+template Void TRenFilter<REN_BIT_DEPTH>::mirrorHor( TRenImage<Double>        *pcImage );
+template Void TRenFilter<REN_BIT_DEPTH>::mirrorHor( TRenImage<Pel>           *pcImage );
+template Void TRenFilter<REN_BIT_DEPTH>::mirrorHor( TRenImage<Int>           *pcImage );
+template Void TRenFilter<REN_BIT_DEPTH>::mirrorHor( TRenImagePlane<Pel>      *pcImagePlane );
 
 #endif 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenFilter.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenFilter.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenFilter.h	(revision 1200)
@@ -39,8 +39,9 @@
 #include "TRenImage.h"
 #include "TRenInterpFilter.h"
-#if H_3D
+#if NH_3D
 
-typedef Int (TRenInterpFilter::*FpChromaIntFilt) ( Pel*, Int );
+typedef Int (TRenInterpFilter<REN_BIT_DEPTH>::*FpChromaIntFilt) ( Pel*, Int );
 
+template<UInt bitDepthLuma>
 class TRenFilter
 {
@@ -53,5 +54,5 @@
 
   /////////// Copy ///////////
-  static Void copy( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride);
+  static Void copy( const Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride);
 
   /////////// Horizontal Mirroring ///////////
@@ -129,5 +130,5 @@
   static Void xInterpVerChroma(Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter);
   static Void xInterpHorChroma(Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter);
-  static Void xDistributeArray(Pel* pcSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* pcDst, Int iDstStride, Int iDstStepX, Int iDstStepY );
+  static Void xDistributeArray(const Pel* pcSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* pcDst, Int iDstStride, Int iDstStepX, Int iDstStepY );
 
   // Binominal Filtering
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImage.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImage.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImage.cpp	(revision 1200)
@@ -37,10 +37,10 @@
 #include "TRenFilter.h"
 #include "assert.h"
-#if H_3D
+#if NH_3D
 
 
 template<typename T>
 TRenImage<T>::TRenImage( TRenImage& rcIn )
-{
+{  
   allocatePlanes( rcIn.getPlane(0)->getWidth(), rcIn.getPlane(0)->getHeight(), rcIn.getNumberOfFullPlanes(), rcIn.getNumberOfQuaterPlanes() ) ; assign(&rcIn);
 }
@@ -48,5 +48,5 @@
 template<typename T>
 TRenImage<T>::TRenImage( UInt uiWidth, UInt uiHeight, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes )
-{
+{  
   allocatePlanes( uiWidth, uiHeight, uiNumberOfFullPlanes, uiNumberOfQuaterPlanes );
 }
@@ -55,5 +55,5 @@
 TRenImage<T>::TRenImage() : m_uiNumberOfFullPlanes(0), m_uiNumberOfQuaterPlanes(0), m_uiNumberOfPlanes(0), m_apcPlanes(0)
 {
-
+  
 }
 
@@ -61,5 +61,5 @@
 template<>
 TRenImage<Pel>::TRenImage( TComPicYuv* pcPicYuv, Bool bFirstPlaneOnly )
-{
+{ 
   if (bFirstPlaneOnly) //400
   {
@@ -68,5 +68,5 @@
     m_uiNumberOfQuaterPlanes = 0;
     m_apcPlanes    = new TRenImagePlane<Pel>*[ m_uiNumberOfPlanes ];
-    m_apcPlanes[0] = new TRenImagePlane<Pel>( pcPicYuv->getBufY(), pcPicYuv->getWidth() + (REN_LUMA_MARGIN << 1),   pcPicYuv->getHeight()+ (REN_LUMA_MARGIN << 1), pcPicYuv->getStride (), REN_LUMA_MARGIN );
+    m_apcPlanes[0] = new TRenImagePlane<Pel>( pcPicYuv->getBuf( COMPONENT_Y ), pcPicYuv->getWidth( COMPONENT_Y  ) + (REN_LUMA_MARGIN << 1),   pcPicYuv->getHeight( COMPONENT_Y  ) + (REN_LUMA_MARGIN << 1), pcPicYuv->getStride( COMPONENT_Y ), REN_LUMA_MARGIN );
   }
   else //420
@@ -77,7 +77,7 @@
 
     m_apcPlanes    = new TRenImagePlane<Pel>*[ m_uiNumberOfPlanes ];
-    m_apcPlanes[0] = new TRenImagePlane<Pel>( pcPicYuv->getBufY(),   pcPicYuv->getWidth()     + (REN_LUMA_MARGIN << 1),  pcPicYuv->getHeight()      + (REN_LUMA_MARGIN << 1), pcPicYuv->getStride (), REN_LUMA_MARGIN );
-    m_apcPlanes[1] = new TRenImagePlane<Pel>( pcPicYuv->getBufU(),   (pcPicYuv->getWidth()>>1)+  REN_LUMA_MARGIN      ,  (pcPicYuv->getHeight()>>1) +  REN_LUMA_MARGIN      , pcPicYuv->getCStride(), REN_LUMA_MARGIN >> 1 );
-    m_apcPlanes[2] = new TRenImagePlane<Pel>( pcPicYuv->getBufV(),   (pcPicYuv->getWidth()>>1)+  REN_LUMA_MARGIN      ,  (pcPicYuv->getHeight()>>1) +  REN_LUMA_MARGIN      , pcPicYuv->getCStride(), REN_LUMA_MARGIN >> 1 );
+    m_apcPlanes[0] = new TRenImagePlane<Pel>( pcPicYuv->getBuf( COMPONENT_Y  ), pcPicYuv->getWidth( COMPONENT_Y  ) + (REN_LUMA_MARGIN << 1),  pcPicYuv->getHeight( COMPONENT_Y  ) + (REN_LUMA_MARGIN << 1), pcPicYuv->getStride( COMPONENT_Y ), REN_LUMA_MARGIN );
+    m_apcPlanes[1] = new TRenImagePlane<Pel>( pcPicYuv->getBuf( COMPONENT_Cb ), pcPicYuv->getWidth( COMPONENT_Cb ) +  REN_LUMA_MARGIN      ,  pcPicYuv->getHeight( COMPONENT_Cb ) +  REN_LUMA_MARGIN      , pcPicYuv->getStride( COMPONENT_Cb), REN_LUMA_MARGIN >> 1 );
+    m_apcPlanes[2] = new TRenImagePlane<Pel>( pcPicYuv->getBuf( COMPONENT_Cr ), pcPicYuv->getWidth( COMPONENT_Cr ) +  REN_LUMA_MARGIN      ,  pcPicYuv->getHeight( COMPONENT_Cr ) +  REN_LUMA_MARGIN      , pcPicYuv->getStride( COMPONENT_Cr), REN_LUMA_MARGIN >> 1 );
   }
 }
@@ -109,5 +109,5 @@
 
 template<typename T>
-Void TRenImage<T>::getDataAndStrides( T** pptData, Int* piStrides )
+Void TRenImage<T>::getDataAndStrides( T** pptData, Int* piStrides ) const
 {
   for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++ )
@@ -120,5 +120,5 @@
 
 template<typename T>
-Void TRenImage<T>::getWidthAndHeight( Int* ppiWidths, Int* ppiHeights )
+Void TRenImage<T>::getWidthAndHeight( Int* ppiWidths, Int* ppiHeights ) const
 {
   for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++ )
@@ -233,11 +233,12 @@
   for (UInt uiCurPlane = 1; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
   {
-    m_apcPlanes[uiCurPlane]->assign( (Pel) ( 1 << ( g_bitDepthC - 1 ) ) );
-  }
-}
-
-
-template<class T>
-TRenImage<T>::~TRenImage() {
+    m_apcPlanes[uiCurPlane]->assign( (Pel) ( 1 << ( REN_BIT_DEPTH - 1 ) ) );
+  }
+}
+
+
+template<class T>
+TRenImage<T>::~TRenImage()
+{
   xDeletePlanes();
   delete[] m_apcPlanes;
@@ -272,3 +273,3 @@
 template Void TRenImage<Pel>::assign<Pel>    (TRenImage<Pel>*   );
 
-#endif // H_3D
+#endif // NH_3D
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImage.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImage.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImage.h	(revision 1200)
@@ -39,5 +39,5 @@
 #include "../TLibCommon/TComPicYuv.h"
 #include "TRenImagePlane.h"
-#if H_3D
+#if NH_3D
 
 
@@ -70,13 +70,13 @@
   TRenImagePlane<T>** getPlanes() const;
 
-  Void getDataAndStrides( T**    pptData, Int*  piStrides );
-  Void getWidthAndHeight( Int*  piWidths, Int*  piHeights );
+  Void getDataAndStrides ( T**    pptData, Int*  piStrides ) const ;
+  Void getWidthAndHeight ( Int*  piWidths, Int*  piHeights ) const ;
 
   UInt getNumberOfPlanes()  const;
   UInt getNumberOfQuaterPlanes() const;
   UInt getNumberOfFullPlanes() const;
-  Bool is420() {return m_uiNumberOfFullPlanes == 1 && m_uiNumberOfQuaterPlanes == 2; };
-  Bool is444() {return m_uiNumberOfFullPlanes == 3 && m_uiNumberOfQuaterPlanes == 0; };
-  Bool is400() {return m_uiNumberOfFullPlanes == 1 && m_uiNumberOfQuaterPlanes == 0; };
+  Bool is420() const {return m_uiNumberOfFullPlanes == 1 && m_uiNumberOfQuaterPlanes == 2; };
+  Bool is444() const {return m_uiNumberOfFullPlanes == 3 && m_uiNumberOfQuaterPlanes == 0; };
+  Bool is400() const {return m_uiNumberOfFullPlanes == 1 && m_uiNumberOfQuaterPlanes == 0; };
 
   // Assign
@@ -95,4 +95,5 @@
   UInt m_uiNumberOfQuaterPlanes;
   UInt m_uiNumberOfPlanes;
+  UInt m_bitDepth;
   TRenImagePlane<T> ** m_apcPlanes;   // First Full Planes, then Quater Planes
 
@@ -100,5 +101,5 @@
 };
 
-#endif // H_3D
+#endif // NH_3D
 #endif // __TRENIMAGE__
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImagePlane.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 1200)
@@ -36,5 +36,5 @@
 #include "TRenFilter.h"
 #include <string.h>
-#if H_3D
+#if NH_3D
 
 /////// TRenImagePlane ///////
@@ -528,4 +528,4 @@
 template class TRenImagePlanePart<Bool>;
 template class TRenImagePlanePart<Int>;
-#endif // H_3D
-
+#endif // NH_3D
+
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImagePlane.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 1200)
@@ -39,5 +39,5 @@
 #include "../TLibCommon/TComPicYuv.h"
 
-#if H_3D
+#if NH_3D
 #define PelImagePlane     TRenImagePlane<Pel>
 #define DoubleImagePlane  TRenImagePlane<Double>
@@ -122,4 +122,4 @@
 };
 
-#endif // H_3D
+#endif // NH_3D
 #endif // __TRENIMAGEPLANE__
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenInterpFilter.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 1200)
@@ -39,5 +39,5 @@
 
 #include "TRenInterpFilter.h"
-#if H_3D
+#if NH_3D
 
 // ====================================================================================================================
@@ -45,9 +45,11 @@
 // ====================================================================================================================
 
-TRenInterpFilter::TRenInterpFilter()
+template<UInt bitDepthLuma>
+TRenInterpFilter<bitDepthLuma>::TRenInterpFilter()
 {
   // initial number of taps for Luma
 }
 
-#endif // H_3D
+template class TRenInterpFilter<REN_BIT_DEPTH>;
+#endif // NH_3D
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenInterpFilter.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 1200)
@@ -44,5 +44,5 @@
 #include "TLibCommon/CommonDef.h"
 #include "assert.h"
-#if H_3D
+#if NH_3D
 
 // ====================================================================================================================
@@ -60,4 +60,5 @@
 
 /// interpolation filter class
+template<UInt bitDepth>
 class TRenInterpFilter
 {
@@ -104,4 +105,7 @@
    __inline Int xCTI_Filter_VP04_C_OCT3( Pel* pSrc, Int iStride );
    __inline Int xCTI_Filter_VI04_C_OCT3( Int* pSrc, Int iStride );
+private:
+  __inline Int xClipY( Pel x ) { return std::min<Pel>(Pel((1 << bitDepth)-1), std::max<Pel>( Pel(0), x)); } 
+  __inline Int xClipC( Pel x ) { return std::min<Pel>(Pel((1 << bitDepth)-1), std::max<Pel>( Pel(0), x)); }
 
 };
@@ -111,9 +115,7 @@
 // DCTIF filters
 // ------------------------------------------------------------------------------------------------
-
-__inline Void TRenInterpFilter::xCTI_FilterHalfHor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterHalfHor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
   Pel*  piDst    = rpiDst;
   Int   iSum;
@@ -146,5 +148,5 @@
             -    iTmp0 -  iTmp2;
 
-      piDst   [x * iDstStep] = ClipY( (iSum +  32) >>  6 );
+      piDst   [x * iDstStep] = xClipY( (iSum +  32) >>  6 );
       piSrcTmp += iSrcStep;
     }
@@ -155,8 +157,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterHalfHor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterHalfHor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
   Pel*  piDst    = rpiDst;
   Int   iSum;
@@ -189,5 +190,5 @@
             -    iTmp0 -  iTmp2;
       
-      piDst   [x * iDstStep] = ClipY( (iSum +  2048) >>  12 );
+      piDst   [x * iDstStep] = xClipY( (iSum +  2048) >>  12 );
       piSrcTmp += iSrcStep;
     }
@@ -198,7 +199,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterQuarter0Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterQuarter0Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{  
   Pel*  piDst    = rpiDst;
   Int   iSum;
@@ -229,5 +230,5 @@
              + (   piSrcTmp[iSrcStep4]           << 4 );
       
-      piDst   [x * iDstStep] = ClipY(( (iSum +  32) >>  6 )+ piSrcTmp[iSrcStep3]);
+      piDst   [x * iDstStep] = xClipY(( (iSum +  32) >>  6 )+ piSrcTmp[iSrcStep3]);
       piSrcTmp += iSrcStep;
     }
@@ -238,8 +239,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterQuarter0Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterQuarter0Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
   Pel*  piDst    = rpiDst;
   Int   iSum;
@@ -271,5 +271,5 @@
             + (   piSrcTmp[iSrcStep3]           << 6 );
       
-      piDst   [x * iDstStep] = ClipY( (iSum +  2048) >>  12 );
+      piDst   [x * iDstStep] = xClipY( (iSum +  2048) >>  12 );
       piSrcTmp += iSrcStep;
     }
@@ -280,7 +280,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterQuarter1Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterQuarter1Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
   Pel*  piDst    = rpiDst;
   Int   iSum;
@@ -310,5 +310,5 @@
             + (   piSrcTmp[iSrcStep3]           << 4 );
       
-      piDst   [x * iDstStep] = ClipY( ((iSum +  32) >>  6) + piSrcTmp[iSrcStep4] );
+      piDst   [x * iDstStep] = xClipY( ((iSum +  32) >>  6) + piSrcTmp[iSrcStep4] );
       piSrcTmp += iSrcStep;
     }
@@ -319,8 +319,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterQuarter1Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterQuarter1Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
   Pel*  piDst    = rpiDst;
   Int   iSum;
@@ -351,5 +350,5 @@
             + (   piSrcTmp[iSrcStep4]           << 6 );
       
-      piDst   [x * iDstStep] = ClipY( (iSum +  2048) >>  12 );
+      piDst   [x * iDstStep] = xClipY( (iSum +  2048) >>  12 );
       piSrcTmp += iSrcStep;
     }
@@ -360,7 +359,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst, Int iDstStridePel, Pel*& rpiDstPel )
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst, Int iDstStridePel, Pel*& rpiDstPel )
+{
   Int*  piDst = rpiDst;
   Pel*  piDstPel = rpiDstPel;
@@ -394,5 +393,5 @@
       
       piDst[x * iDstStep]    = iSum;
-      piDstPel[x * iDstStep] = ClipY( (iSum +  32) >>  6 );
+      piDstPel[x * iDstStep] = xClipY( (iSum +  32) >>  6 );
       piSrcTmp += iSrcStep;
     }
@@ -404,5 +403,6 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
 {
   Int*  piDst = rpiDst;
@@ -444,7 +444,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
   Pel*  piDst = rpiDst;
   Int   iSum;
@@ -477,5 +477,5 @@
             -    iTmp0 -  iTmp2;        
       
-      piDst[x * iDstStep] = ClipY( (iSum +  32) >>  6 );
+      piDst[x * iDstStep] = xClipY( (iSum +  32) >>  6 );
       piSrcTmp += iSrcStep;
     }
@@ -486,5 +486,6 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
 {
   Int*  piDst = rpiDst;
@@ -525,7 +526,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY );  // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
   Pel*  piDst = rpiDst;
   Int   iSum;
@@ -556,5 +557,5 @@
             + (   piSrcTmp[iSrcStride4]           << 4 );
       
-      piDst[x * iDstStep] = ClipY( ((iSum +  32) >>  6) + piSrcTmp[iSrcStride3] );
+      piDst[x * iDstStep] = xClipY( ((iSum +  32) >>  6) + piSrcTmp[iSrcStride3] );
       piSrcTmp += iSrcStep;
     }
@@ -565,5 +566,6 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
 {
   Int*  piDst = rpiDst;
@@ -604,8 +606,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
   Pel*  piDst = rpiDst;
   Int   iSum;
@@ -635,5 +636,5 @@
             + (   piSrcTmp[iSrcStride3]           << 4 );
             
-      piDst[x * iDstStep] = ClipY( ((iSum +  32) >>  6) +  piSrcTmp[iSrcStride4] );
+      piDst[x * iDstStep] = xClipY( ((iSum +  32) >>  6) +  piSrcTmp[iSrcStride4] );
       piSrcTmp += iSrcStep;
     }
@@ -647,5 +648,6 @@
 // DCTIF filters for Chroma
 // ------------------------------------------------------------------------------------------------
-__inline Void TRenInterpFilter::xCTI_Filter2DVerC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Int*& rpiDst, Int iMV)
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_Filter2DVerC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Int*& rpiDst, Int iMV)
 {
   Int*  piDst = rpiDst;
@@ -774,7 +776,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_Filter2DHorC(Int* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_Filter2DHorC(Int* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
+{
   Pel*  piDst    = rpiDst;
   Int   iSum;
@@ -791,5 +793,5 @@
         {
           iSum         = xCTI_Filter_VI04_C_OCT0( piSrcTmp, 1 );
-          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piDst   [x ] = xClipC ((iSum +  2048) >>  12 );
           piSrcTmp++;
         }
@@ -807,5 +809,5 @@
         {
           iSum         = xCTI_Filter_VI04_C_QUA0( piSrcTmp, 1 );
-          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piDst   [x ] = xClipC ((iSum +  2048) >>  12 );
           piSrcTmp++;
         }
@@ -823,5 +825,5 @@
         {
           iSum         = xCTI_Filter_VI04_C_QUA1( piSrcTmp, 1 );
-          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piDst   [x ] = xClipC ((iSum +  2048) >>  12 );
           piSrcTmp++;
         }
@@ -839,5 +841,5 @@
         {
           iSum         = xCTI_Filter_VI04_C_OCT1( piSrcTmp, 1 );
-          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piDst   [x ] = xClipC ((iSum +  2048) >>  12 );
           piSrcTmp++;
         }
@@ -855,5 +857,5 @@
         {
           iSum         = xCTI_Filter_VI04_C_OCT2( piSrcTmp, 1 );
-          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piDst   [x ] = xClipC ((iSum +  2048) >>  12 );
           piSrcTmp++;
         }
@@ -871,5 +873,5 @@
         {
           iSum         = xCTI_Filter_VI04_C_OCT3( piSrcTmp, 1 );
-          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piDst   [x ] = xClipC ((iSum +  2048) >>  12 );
           piSrcTmp++;
         }
@@ -887,5 +889,5 @@
         {
           iSum      = xCTI_Filter_VIS04_C_HAL( piSrcTmp, 1 );
-          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piDst   [x ] = xClipC ((iSum +  2048) >>  12 );
           piSrcTmp++;
         }
@@ -902,8 +904,7 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_Filter1DVerC (Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
-{
-  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
-
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_Filter1DVerC (Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
+{
   Pel*  piDst = rpiDst;
   Int   iSum;
@@ -920,5 +921,5 @@
         {
           iSum      = xCTI_Filter_VP04_C_OCT0( piSrcTmp,  iSrcStride );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -936,5 +937,5 @@
         {
           iSum      = xCTI_Filter_VP04_C_QUA0( piSrcTmp,  iSrcStride );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -952,5 +953,5 @@
         {
           iSum      = xCTI_Filter_VP04_C_QUA1( piSrcTmp,  iSrcStride );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -968,5 +969,5 @@
         {
           iSum      = xCTI_Filter_VP04_C_OCT1( piSrcTmp,  iSrcStride );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -984,5 +985,5 @@
         {
           iSum      = xCTI_Filter_VP04_C_OCT2( piSrcTmp,  iSrcStride );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1000,5 +1001,5 @@
         {
           iSum      = xCTI_Filter_VP04_C_OCT3( piSrcTmp,  iSrcStride );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1016,5 +1017,5 @@
         {
           iSum      = xCTI_Filter_VPS04_C_HAL( piSrcTmp, iSrcStride );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1030,5 +1031,6 @@
 }
 
-__inline Void TRenInterpFilter::xCTI_Filter1DHorC(Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride, Pel*& rpiDst, Int iMV)
+template<UInt bitDepth>
+__inline Void TRenInterpFilter<bitDepth>::xCTI_Filter1DHorC(Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride, Pel*& rpiDst, Int iMV)
 {
   Pel*  piDst    = rpiDst;
@@ -1046,5 +1048,5 @@
         {
           iSum         = xCTI_Filter_VP04_C_OCT0( piSrcTmp,  1 );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1062,5 +1064,5 @@
         {
           iSum         = xCTI_Filter_VP04_C_QUA0( piSrcTmp,  1 );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1078,5 +1080,5 @@
         {
           iSum         = xCTI_Filter_VP04_C_QUA1( piSrcTmp,  1 );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1094,5 +1096,5 @@
         {
           iSum         = xCTI_Filter_VP04_C_OCT1( piSrcTmp,  1 );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1110,5 +1112,5 @@
         {
           iSum         = xCTI_Filter_VP04_C_OCT2( piSrcTmp,  1 );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1126,5 +1128,5 @@
         {
           iSum         = xCTI_Filter_VP04_C_OCT3( piSrcTmp,  1 );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1142,5 +1144,5 @@
         {
           iSum         = xCTI_Filter_VPS04_C_HAL( piSrcTmp,  1 );
-          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piDst[x ] = xClipC ((iSum +  32) >>  6 );
           piSrcTmp++;
         }
@@ -1156,5 +1158,6 @@
 }
 
-__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT0( Pel* pSrc,  Int iStride )
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VP04_C_OCT0( Pel* pSrc,  Int iStride )
 {// {  -3,  60,   8,   -1,} // 1/8
   Int iSum, iIdx = 0;
@@ -1168,5 +1171,6 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT0( Int* pSrc, Int iStride )
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VI04_C_OCT0( Int* pSrc, Int iStride )
 { // {  -3,  60,   8,   -1,} //1/8
   Int iSum, iIdx = 0;
@@ -1180,5 +1184,6 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_QUA0( Pel* pSrc,  Int iStride )
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VP04_C_QUA0( Pel* pSrc,  Int iStride )
 {// {  -4,  54,  16,   -2,} // 1/4
   Int iSum, iIdx = 0;
@@ -1192,5 +1197,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_QUA0( Int* pSrc, Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VI04_C_QUA0( Int* pSrc, Int iStride )
 { // {  -4,  54,  16,   -2,} //1/4
   Int iSum, iIdx = 0;
@@ -1204,5 +1211,6 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_QUA1( Pel* pSrc,  Int iStride )
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VP04_C_QUA1( Pel* pSrc,  Int iStride )
 {// {  -2,  16,  54,   -4,}// 3/4
   Int iSum, iIdx = 0;
@@ -1216,5 +1224,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_QUA1( Int* pSrc, Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VI04_C_QUA1( Int* pSrc, Int iStride )
 {// {  -2,  16,  54,   -4,}// 3/4
   Int iSum, iIdx = 0;
@@ -1228,5 +1238,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT1( Pel* pSrc,  Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VP04_C_OCT1( Pel* pSrc,  Int iStride )
 {// {  -5,  46,  27,   -4,} // 3/8
   Int iSum, iIdx = 0;
@@ -1241,5 +1253,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT1( Int* pSrc, Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VI04_C_OCT1( Int* pSrc, Int iStride )
 { // {  -5,  46,  27,   -4,} //3/8
   Int iSum, iIdx = 0;
@@ -1254,5 +1268,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VPS04_C_HAL( Pel* pSrc, Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VPS04_C_HAL( Pel* pSrc, Int iStride )
 {
   // {  -4,  36,  36,   -4,}, // 1/2
@@ -1265,5 +1281,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VIS04_C_HAL( Int* pSrc, Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VIS04_C_HAL( Int* pSrc, Int iStride )
 {
   // {  -4,  36,  36,   -4,}, //1/2
@@ -1276,5 +1294,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT2( Pel* pSrc,  Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VP04_C_OCT2( Pel* pSrc,  Int iStride )
 {// {  -4,  27,  46,   -5,}, // 5/8
   Int iSum, iIdx = 0;
@@ -1289,5 +1309,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT2( Int* pSrc, Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VI04_C_OCT2( Int* pSrc, Int iStride )
 { // {  -4,  27,  46,   -5,}, // 5/8
   Int iSum, iIdx = 0;
@@ -1302,5 +1324,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT3( Pel* pSrc,  Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VP04_C_OCT3( Pel* pSrc,  Int iStride )
 {// {  -1,   8,  60,   -3,} // 7/8
   Int iSum, iIdx = 0;
@@ -1314,5 +1338,7 @@
   return iSum;
 }
-__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT3( Int* pSrc, Int iStride )
+
+template<UInt bitDepth>
+__inline Int TRenInterpFilter<bitDepth>::xCTI_Filter_VI04_C_OCT3( Int* pSrc, Int iStride )
 { // {  -1,   8,  60,   -3,} // 7/8
   Int iSum, iIdx = 0;
@@ -1326,4 +1352,5 @@
   return iSum;
 }
-#endif // H_3D
+
+#endif // NH_3D
 #endif // __TRENINTERP__
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 1200)
@@ -37,5 +37,5 @@
 #include "TRenModSetupStrParser.h"
 
-#if H_3D
+#if NH_3D
 Int
 TRenModSetupStrParser::getNumOfModels()
@@ -451,4 +451,4 @@
   rcNextChar = m_pchSetStr[iPos];
 }
-#endif // H_3D
-
+#endif // NH_3D
+
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModSetupStrParser.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 1200)
@@ -39,5 +39,5 @@
 #include "../TLibCommon/TypeDef.h"
 #include "../TAppCommon/TAppComCamPara.h"
-#if H_3D
+#if NH_3D
 
 
@@ -128,5 +128,5 @@
 };
 
-#endif // H_3D
+#endif // NH_3D
 #endif //__TRENMODEL__
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModel.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModel.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModel.cpp	(revision 1200)
@@ -36,5 +36,5 @@
 #include "TRenModel.h"
 
-#if H_3D_VSO
+#if NH_3D_VSO
 ///////////  TRENMODEL //////////////////////
 TRenModel::TRenModel()
@@ -242,6 +242,6 @@
   }
 
-  TRenFilter::setSubPelShiftLUT( m_iShiftPrec, m_aaaiSubPelShiftLut[0], 0 );
-  TRenFilter::setSubPelShiftLUT( m_iShiftPrec, m_aaaiSubPelShiftLut[1], 0 );
+  TRenFilter<REN_BIT_DEPTH>::setSubPelShiftLUT( m_iShiftPrec, m_aaaiSubPelShiftLut[0], 0 );
+  TRenFilter<REN_BIT_DEPTH>::setSubPelShiftLUT( m_iShiftPrec, m_aaaiSubPelShiftLut[1], 0 );
 
   m_iSampledWidth       = iWidth << m_iShiftPrec;
@@ -357,8 +357,7 @@
   AOT( iBaseViewNum != -1 && iBaseViewNum != iLeftViewNum && iBaseViewNum != iRightViewNum );
   AOT( iContent      < -1 || iContent > 1 );
-  AOT( iBlendMode < -1 || iBlendMode > 2 );
-  AOT( g_bitDepthY  != g_bitDepthC ); 
-
-  Bool bBitInc = ( DISTORTION_PRECISION_ADJUSTMENT( g_bitDepthY - 8 ) != 0);
+  AOT( iBlendMode < -1 || iBlendMode > 2 );  
+
+  Bool bBitInc = ( REN_BIT_DEPTH != ENC_INTERNAL_BIT_DEPTH );
 
   AOT( m_apcRenModels[iModelNum] );
@@ -437,13 +436,15 @@
 {
   AOT( iViewNum < 0 || iViewNum > m_iNumOfBaseViews );
-  AOF( pcPicYuvVideoData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvVideoData->getWidth() == m_iWidth );
-  AOF( pcPicYuvDepthData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvDepthData->getWidth() == m_iWidth );
-
+  AOF( pcPicYuvVideoData->getHeight( COMPONENT_Y ) >= m_iUsedHeight + m_uiHorOff && pcPicYuvVideoData->getWidth( COMPONENT_Y ) == m_iWidth );
+  AOF( pcPicYuvDepthData->getHeight( COMPONENT_Y ) >= m_iUsedHeight + m_uiHorOff && pcPicYuvDepthData->getWidth( COMPONENT_Y ) == m_iWidth );
+  
+  AOF( pcPicYuvVideoData   ->getChromaFormat() == CHROMA_420 );
+  
   pcPicYuvVideoData->extendPicBorder();
 
-  TRenFilter::sampleHorUp   ( m_iShiftPrec, pcPicYuvVideoData->getLumaAddr() +  m_uiHorOff        * pcPicYuvVideoData->getStride () , pcPicYuvVideoData->getStride() , m_iWidth,      m_iUsedHeight,      m_aapiCurVideoPel[ iViewNum ][0], m_aaiCurVideoStrides[iViewNum][0] );
-  TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvVideoData->getCbAddr()   + (m_uiHorOff >> 1 ) * pcPicYuvVideoData->getCStride() , pcPicYuvVideoData->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiCurVideoPel[ iViewNum ][1], m_aaiCurVideoStrides[iViewNum][1] );
-  TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvVideoData->getCrAddr()   + (m_uiHorOff >> 1 ) * pcPicYuvVideoData->getCStride() , pcPicYuvVideoData->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiCurVideoPel[ iViewNum ][2], m_aaiCurVideoStrides[iViewNum][2] );
-  TRenFilter::copy          (               pcPicYuvDepthData->getLumaAddr() +  m_uiHorOff        * pcPicYuvDepthData->getStride () , pcPicYuvDepthData->getStride(),  m_iWidth,      m_iUsedHeight,      m_apiCurDepthPel [ iViewNum],     m_aiCurDepthStrides [iViewNum]    );
+  TRenFilter<REN_BIT_DEPTH>::sampleHorUp   ( m_iShiftPrec, pcPicYuvVideoData->getAddr( COMPONENT_Y  ) +  m_uiHorOff        * pcPicYuvVideoData->getStride( COMPONENT_Y ) , pcPicYuvVideoData->getStride( COMPONENT_Y  ) , m_iWidth,      m_iUsedHeight,      m_aapiCurVideoPel[ iViewNum ][0], m_aaiCurVideoStrides[iViewNum][0] );
+  TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp( m_iShiftPrec, pcPicYuvVideoData->getAddr( COMPONENT_Cb ) + (m_uiHorOff >> 1 ) * pcPicYuvVideoData->getStride( COMPONENT_Cb) , pcPicYuvVideoData->getStride( COMPONENT_Cb ), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiCurVideoPel[ iViewNum ][1], m_aaiCurVideoStrides[iViewNum][1] );
+  TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp( m_iShiftPrec, pcPicYuvVideoData->getAddr( COMPONENT_Cr ) + (m_uiHorOff >> 1 ) * pcPicYuvVideoData->getStride( COMPONENT_Cr) , pcPicYuvVideoData->getStride( COMPONENT_Cr ), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiCurVideoPel[ iViewNum ][2], m_aaiCurVideoStrides[iViewNum][2] );
+  TRenFilter<REN_BIT_DEPTH>::copy          (               pcPicYuvDepthData->getAddr( COMPONENT_Y  ) +  m_uiHorOff        * pcPicYuvDepthData->getStride( COMPONENT_Y ) , pcPicYuvDepthData->getStride( COMPONENT_Y  ),  m_iWidth,      m_iUsedHeight,      m_apiCurDepthPel [ iViewNum],     m_aiCurDepthStrides [iViewNum]    );
 
   // Used for rendering reference pic from original video data
@@ -453,15 +454,16 @@
   if ( m_abSetupVideoFromOrgForView[iViewNum] )
   {
-    AOF( pcPicYuvOrgVideoData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvOrgVideoData->getWidth() == m_iWidth );
+    AOF( pcPicYuvOrgVideoData->getChromaFormat() == CHROMA_420 );
+    AOF( pcPicYuvOrgVideoData->getHeight( COMPONENT_Y ) >= m_iUsedHeight + m_uiHorOff && pcPicYuvOrgVideoData->getWidth( COMPONENT_Y) == m_iWidth );    
     pcPicYuvOrgVideoData->extendPicBorder();
-    TRenFilter::sampleHorUp   ( m_iShiftPrec, pcPicYuvOrgVideoData->getLumaAddr() +  m_uiHorOff        * pcPicYuvOrgVideoData->getStride() , pcPicYuvOrgVideoData->getStride() , m_iWidth,      m_iUsedHeight,      m_aapiOrgVideoPel[ iViewNum ][0], m_aaiOrgVideoStrides[iViewNum][0] );
-    TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvOrgVideoData->getCbAddr()   + (m_uiHorOff >> 1 ) * pcPicYuvOrgVideoData->getCStride(), pcPicYuvOrgVideoData->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiOrgVideoPel[ iViewNum ][1], m_aaiOrgVideoStrides[iViewNum][1] );
-    TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvOrgVideoData->getCrAddr()   + (m_uiHorOff >> 1 ) * pcPicYuvOrgVideoData->getCStride(), pcPicYuvOrgVideoData->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiOrgVideoPel[ iViewNum ][2], m_aaiOrgVideoStrides[iViewNum][2] );
+    TRenFilter<REN_BIT_DEPTH>::sampleHorUp   ( m_iShiftPrec, pcPicYuvOrgVideoData->getAddr( COMPONENT_Y  ) +  m_uiHorOff          * pcPicYuvOrgVideoData->getStride( COMPONENT_Y  ), pcPicYuvOrgVideoData->getStride( COMPONENT_Y  ) , m_iWidth,      m_iUsedHeight,      m_aapiOrgVideoPel[ iViewNum ][0], m_aaiOrgVideoStrides[iViewNum][0] );
+    TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp( m_iShiftPrec, pcPicYuvOrgVideoData->getAddr( COMPONENT_Cb )   + (m_uiHorOff >> 1 ) * pcPicYuvOrgVideoData->getStride( COMPONENT_Cb ), pcPicYuvOrgVideoData->getStride( COMPONENT_Cb ), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiOrgVideoPel[ iViewNum ][1], m_aaiOrgVideoStrides[iViewNum][1] );
+    TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp( m_iShiftPrec, pcPicYuvOrgVideoData->getAddr( COMPONENT_Cr )   + (m_uiHorOff >> 1 ) * pcPicYuvOrgVideoData->getStride( COMPONENT_Cr ), pcPicYuvOrgVideoData->getStride( COMPONENT_Cr ), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiOrgVideoPel[ iViewNum ][2], m_aaiOrgVideoStrides[iViewNum][2] );
   }
 
   if ( m_abSetupDepthFromOrgForView[iViewNum] )
-  {
-    AOF( pcPicYuvOrgDepthData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvOrgDepthData->getWidth() == m_iWidth );
-    TRenFilter::copy          (               pcPicYuvOrgDepthData->getLumaAddr() +  m_uiHorOff        * pcPicYuvOrgDepthData->getStride() , pcPicYuvOrgDepthData->getStride(),  m_iWidth,     m_iUsedHeight,      m_apiOrgDepthPel [ iViewNum],     m_aiOrgDepthStrides [iViewNum]    );
+  {    
+    AOF( pcPicYuvOrgDepthData->getHeight( COMPONENT_Y ) >= m_iUsedHeight + m_uiHorOff && pcPicYuvOrgDepthData->getWidth( COMPONENT_Y ) == m_iWidth );
+    TRenFilter<REN_BIT_DEPTH>::copy          (               pcPicYuvOrgDepthData->getAddr( COMPONENT_Y ) +  m_uiHorOff        * pcPicYuvOrgDepthData->getStride( COMPONENT_Y) , pcPicYuvOrgDepthData->getStride( COMPONENT_Y),  m_iWidth,     m_iUsedHeight,      m_apiOrgDepthPel [ iViewNum],     m_aiOrgDepthStrides [iViewNum]    );
   }
 }
@@ -592,5 +594,5 @@
 
 Void
-TRenModel::setData( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+TRenModel::setData( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData )
 {
   iStartPosY -= m_uiHorOff; 
@@ -625,5 +627,5 @@
   {
     Int iTargetStride = m_aiCurDepthStrides[ m_iCurrentView ];
-    TRenFilter::copy( piNewData, iStride, iWidth, iHeight,  m_apiCurDepthPel[ m_iCurrentView ] + iStartPosY * iTargetStride + iStartPosX, iTargetStride );
+    TRenFilter<REN_BIT_DEPTH>::copy( piNewData, iStride, iWidth, iHeight,  m_apiCurDepthPel[ m_iCurrentView ] + iStartPosY * iTargetStride + iStartPosX, iTargetStride );
   }
 #endif
@@ -646,8 +648,8 @@
 {
   TComPicYuv cPicYuvSynth;
-  cPicYuvSynth.create( m_iWidth, m_iUsedHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  cPicYuvSynth.create( m_iWidth, m_iUsedHeight, CHROMA_420, 1, 1, 1, true);
 
   TComPicYuv cPicYuvTempRef;
-  cPicYuvTempRef.create( m_iWidth, m_iUsedHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+  cPicYuvTempRef.create( m_iWidth, m_iUsedHeight, CHROMA_420, 1, 1, 1, true);
 
   Int64 iSSEY = 0;
@@ -660,7 +662,7 @@
     m_apcCurRenModels[iCurModel]->getRefVideo  ( m_aiCurPosInModels[iCurModel], &cPicYuvTempRef   );
 
-    iSSEY += TRenFilter::SSE( cPicYuvSynth.getLumaAddr(), cPicYuvSynth.getStride(),  m_iWidth,      m_iUsedHeight     , cPicYuvTempRef.getLumaAddr(), cPicYuvTempRef.getStride() , true  );
-    iSSEU += TRenFilter::SSE( cPicYuvSynth.getCbAddr()  , cPicYuvSynth.getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, cPicYuvTempRef.getCbAddr()  , cPicYuvTempRef.getCStride(), false );
-    iSSEV += TRenFilter::SSE( cPicYuvSynth.getCrAddr()  , cPicYuvSynth.getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, cPicYuvTempRef.getCrAddr()  , cPicYuvTempRef.getCStride(), false );
+    iSSEY += TRenFilter<REN_BIT_DEPTH>::SSE( cPicYuvSynth.getAddr(  COMPONENT_Y ), cPicYuvSynth.getStride( COMPONENT_Y  ),  m_iWidth,      m_iUsedHeight    , cPicYuvTempRef.getAddr( COMPONENT_Y  ), cPicYuvTempRef.getStride( COMPONENT_Y  ), true  );
+    iSSEU += TRenFilter<REN_BIT_DEPTH>::SSE( cPicYuvSynth.getAddr( COMPONENT_Cb ), cPicYuvSynth.getStride( COMPONENT_Cb ), m_iWidth >> 1, m_iUsedHeight >> 1, cPicYuvTempRef.getAddr( COMPONENT_Cb ), cPicYuvTempRef.getStride( COMPONENT_Cb ), false );
+    iSSEV += TRenFilter<REN_BIT_DEPTH>::SSE( cPicYuvSynth.getAddr( COMPONENT_Cr ), cPicYuvSynth.getStride( COMPONENT_Cr ), m_iWidth >> 1, m_iUsedHeight >> 1, cPicYuvTempRef.getAddr( COMPONENT_Cr ), cPicYuvTempRef.getStride( COMPONENT_Cr ), false );
   }
 
@@ -699,3 +701,3 @@
   }
 }
-#endif // H_3D
+#endif // NH_3D
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModel.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModel.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenModel.h	(revision 1200)
@@ -42,5 +42,5 @@
 #include "../TLibCommon/TypeDef.h"
 
-#if H_3D_VSO
+#if NH_3D_VSO
 
 class TRenModel
@@ -75,5 +75,5 @@
   Int64 getDist          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData  );
 #endif
-  Void  setData          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData  );
+  Void  setData          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData  );
 
   // Get Rendered View
@@ -157,5 +157,5 @@
 };
 
-#endif // H_3D
+#endif // NH_3D
 #endif //__TRENMODEL__
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenSingleModel.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 1200)
@@ -36,10 +36,10 @@
 #include "TRenSingleModel.h"
 
-#if H_3D_VSO
+#if NH_3D_VSO
 
 ////////////// TRENSINGLE MODEL ///////////////
 template <BlenMod iBM, Bool bBitInc>
 TRenSingleModelC<iBM,bBitInc>::TRenSingleModelC()
-:  m_iDistShift ( ( g_bitDepthY - 8) << 1 )
+:  m_iDistShift ( ( ENC_INTERNAL_BIT_DEPTH  - REN_BIT_DEPTH) << 1 )
 {
   m_iWidth  = -1;
@@ -259,7 +259,9 @@
   if ( pcOrgVideo && !bKeepReference )
   {
-    TRenFilter::copy(             pcOrgVideo->getLumaAddr() +  m_iHorOffset       * pcOrgVideo->getStride() , pcOrgVideo->getStride() , m_iWidth,      m_iUsedHeight,      m_aapiRefVideoPel[0], m_aiRefVideoStrides[0]);
-    TRenFilter::sampleCUpHorUp(0, pcOrgVideo->getCbAddr()   + (m_iHorOffset >> 1) * pcOrgVideo->getCStride(), pcOrgVideo->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiRefVideoPel[1], m_aiRefVideoStrides[1]);
-    TRenFilter::sampleCUpHorUp(0, pcOrgVideo->getCrAddr()   + (m_iHorOffset >> 1) * pcOrgVideo->getCStride(), pcOrgVideo->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiRefVideoPel[2], m_aiRefVideoStrides[2]);    
+    assert( pcOrgVideo->getChromaFormat() != CHROMA_420 );     
+
+    TRenFilter<REN_BIT_DEPTH>::copy(             pcOrgVideo->getAddr( COMPONENT_Y  ) +  m_iHorOffset       * pcOrgVideo->getStride( COMPONENT_Y  ), pcOrgVideo->getStride( COMPONENT_Y  ), m_iWidth,      m_iUsedHeight,      m_aapiRefVideoPel[0], m_aiRefVideoStrides[0]);
+    TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp(0, pcOrgVideo->getAddr( COMPONENT_Cb ) + (m_iHorOffset >> 1) * pcOrgVideo->getStride( COMPONENT_Cb ), pcOrgVideo->getStride( COMPONENT_Cb ), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiRefVideoPel[1], m_aiRefVideoStrides[1]);
+    TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp(0, pcOrgVideo->getAddr( COMPONENT_Cr ) + (m_iHorOffset >> 1) * pcOrgVideo->getStride( COMPONENT_Cr ), pcOrgVideo->getStride( COMPONENT_Cr ), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiRefVideoPel[2], m_aiRefVideoStrides[2]);    
     xSetStructRefView();
   }
@@ -285,5 +287,5 @@
     break;
   case 2:
-    TRenFilter::setupZLUT( true, 30, iDistToLeft, ppiBaseShiftLutLeft, ppiBaseShiftLutRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight );
+    TRenFilter<REN_BIT_DEPTH>::setupZLUT( true, 30, iDistToLeft, ppiBaseShiftLutLeft, ppiBaseShiftLutRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight );
 #if H_3D_VSO_EARLY_SKIP
     xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0],false);
@@ -452,12 +454,12 @@
 #if H_3D_VSO_COLOR_PLANES             
       // U Planes                    
-      pcOutSampleRow[iPosX].iULeft        = 1 << (g_bitDepthC - 1);
-      pcOutSampleRow[iPosX].iURight       = 1 << (g_bitDepthC - 1);
-      pcOutSampleRow[iPosX].iUBlended     = 1 << (g_bitDepthC - 1);
-                                     
-      // V Planes                    
-      pcOutSampleRow[iPosX].iVLeft        = 1 << (g_bitDepthC - 1);
-      pcOutSampleRow[iPosX].iVRight       = 1 << (g_bitDepthC - 1);
-      pcOutSampleRow[iPosX].iVBlended     = 1 << (g_bitDepthC - 1);
+      pcOutSampleRow[iPosX].iULeft        = 1 << (REN_BIT_DEPTH  - 1);
+      pcOutSampleRow[iPosX].iURight       = 1 << (REN_BIT_DEPTH  - 1);
+      pcOutSampleRow[iPosX].iUBlended     = 1 << (REN_BIT_DEPTH  - 1);
+                                                  
+      // V Planes                                  
+      pcOutSampleRow[iPosX].iVLeft        = 1 << (REN_BIT_DEPTH  - 1);
+      pcOutSampleRow[iPosX].iVRight       = 1 << (REN_BIT_DEPTH  - 1);
+      pcOutSampleRow[iPosX].iVBlended     = 1 << (REN_BIT_DEPTH  - 1);
 #endif
       //// Input Samples
@@ -475,8 +477,8 @@
 #if H_3D_VSO_EARLY_SKIP
 template <BlenMod iBM, Bool bBitInc> RMDist
-TRenSingleModelC<iBM,bBitInc>::getDistDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData , Pel * piOrgData, Int iOrgStride )
+TRenSingleModelC<iBM,bBitInc>::getDistDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData , const Pel * piOrgData, Int iOrgStride )
 #else
 template <BlenMod iBM, Bool bBitInc> RMDist
-TRenSingleModelC<iBM,bBitInc>::getDistDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+TRenSingleModelC<iBM,bBitInc>::getDistDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData )
 #endif
 {
@@ -517,8 +519,8 @@
 #if H_3D_VSO_EARLY_SKIP
 template <BlenMod iBM, Bool bBitInc> Void
-TRenSingleModelC<iBM,bBitInc>::setDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel* piOrgData, Int iOrgStride )
+TRenSingleModelC<iBM,bBitInc>::setDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel* piOrgData, Int iOrgStride )
 #else
 template <BlenMod iBM, Bool bBitInc> Void
-TRenSingleModelC<iBM,bBitInc>::setDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+TRenSingleModelC<iBM,bBitInc>::setDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData )
 #endif
 {
@@ -558,6 +560,8 @@
 TRenSingleModelC<iBM,bBitInc>::getSynthVideo( Int iViewPos, TComPicYuv* pcPicYuv )
 {  
-  AOT( pcPicYuv->getWidth() != m_iWidth );
-  AOT( pcPicYuv->getHeight() < m_iUsedHeight + m_iHorOffset );
+  AOT( pcPicYuv->getWidth( COMPONENT_Y  )  != m_iWidth );
+  AOT( pcPicYuv->getChromaFormat()         != CHROMA_420 ); 
+
+  AOT( pcPicYuv->getHeight( COMPONENT_Y ) < m_iUsedHeight + m_iHorOffset );
 
 #if H_3D_VSO_COLOR_PLANES
@@ -590,11 +594,12 @@
 {  
   AOT( iViewPos != 0 && iViewPos != 1); 
-  AOT( pcPicYuv->getWidth()  != m_iWidth  );
-  AOT( pcPicYuv->getHeight() < m_iUsedHeight + m_iHorOffset );
+  AOT( pcPicYuv->getWidth( COMPONENT_Y)  != m_iWidth  );
+  AOT( pcPicYuv->getChromaFormat( )  != CHROMA_420 );
+  AOT( pcPicYuv->getHeight( COMPONENT_Y ) < m_iUsedHeight + m_iHorOffset );
 
   Pel RenModelOutPels::* piD = 0;
   xGetSampleStrDepthPtrs(iViewPos, piD); 
-  xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piD, pcPicYuv->getLumaAddr() + pcPicYuv->getStride() * m_iHorOffset, pcPicYuv->getStride(), m_iWidth, m_iUsedHeight );
-  pcPicYuv->setChromaTo( 1 << (g_bitDepthC - 1) );   
+  xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piD, pcPicYuv->getAddr( COMPONENT_Y ) + pcPicYuv->getStride( COMPONENT_Y ) * m_iHorOffset, pcPicYuv->getStride( COMPONENT_Y ), m_iWidth, m_iUsedHeight );
+  pcPicYuv->setChromaTo( 1 << (REN_BIT_DEPTH - 1) );   
 }
 
@@ -603,6 +608,7 @@
 TRenSingleModelC<iBM,bBitInc>::getRefVideo ( Int iViewPos, TComPicYuv* pcPicYuv )
 {  
-  AOT( pcPicYuv->getWidth()  != m_iWidth  );
-  AOT( pcPicYuv->getHeight() <  m_iUsedHeight + m_iHorOffset);
+  AOT( pcPicYuv->getChromaFormat( ) != CHROMA_420 );
+  AOT( pcPicYuv->getWidth( COMPONENT_Y )  != m_iWidth  );
+  AOT( pcPicYuv->getHeight( COMPONENT_Y ) <  m_iUsedHeight + m_iHorOffset);
 
 #if H_3D_VSO_COLOR_PLANES
@@ -633,5 +639,5 @@
 
 template <BlenMod iBM, Bool bBitInc> RMDist
-TRenSingleModelC<iBM,bBitInc>::getDistVideo( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+TRenSingleModelC<iBM,bBitInc>::getDistVideo( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData )
 {
   AOF(false);
@@ -640,5 +646,5 @@
 
 template <BlenMod iBM, Bool bBitInc> Void
-TRenSingleModelC<iBM,bBitInc>::setVideo( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+TRenSingleModelC<iBM,bBitInc>::setVideo( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData )
 {
   AOF(false);
@@ -665,8 +671,8 @@
 #if H_3D_VSO_EARLY_SKIP
 template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline RMDist 
-TRenSingleModelC<iBM,bBitInc>::xRenderL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bFast)
+TRenSingleModelC<iBM,bBitInc>::xRenderL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, Bool bFast)
 #else
 template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline RMDist 
-TRenSingleModelC<iBM,bBitInc>::xRenderL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData)
+TRenSingleModelC<iBM,bBitInc>::xRenderL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData)
 #endif
 {
@@ -789,8 +795,8 @@
 #ifdef  H_3D_VSO_EARLY_SKIP
 template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline RMDist
-TRenSingleModelC<iBM,bBitInc>::xRenderR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData , Bool bFast)
+TRenSingleModelC<iBM,bBitInc>::xRenderR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData , Bool bFast)
 #else
 template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline RMDist
-TRenSingleModelC<iBM,bBitInc>::xRenderR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+TRenSingleModelC<iBM,bBitInc>::xRenderR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData )
 #endif
 {
@@ -1877,7 +1883,7 @@
 TRenSingleModelC<iBM,bBitInc>::xCopy2PicYuv( Pel** ppiSrcVideoPel, Int* piStrides, TComPicYuv* rpcPicYuvTarget )
 {
-  TRenFilter::copy            ( ppiSrcVideoPel[0], piStrides[0], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getLumaAddr() +  m_iHorOffset       * rpcPicYuvTarget->getStride() , rpcPicYuvTarget->getStride () );
-  TRenFilter::sampleDown2Tap13( ppiSrcVideoPel[1], piStrides[1], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getCbAddr  () + (m_iHorOffset >> 1) * rpcPicYuvTarget->getCStride(), rpcPicYuvTarget->getCStride() );
-  TRenFilter::sampleDown2Tap13( ppiSrcVideoPel[2], piStrides[2], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getCrAddr  () + (m_iHorOffset >> 1) * rpcPicYuvTarget->getCStride(), rpcPicYuvTarget->getCStride() );
+  TRenFilter<REN_BIT_DEPTH>::copy            ( ppiSrcVideoPel[0], piStrides[0], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getAddr( COMPONENT_Y  ) +  m_iHorOffset       * rpcPicYuvTarget->getStride( COMPONENT_Y  ), rpcPicYuvTarget->getStride( COMPONENT_Y ) );
+  TRenFilter<REN_BIT_DEPTH>::sampleDown2Tap13( ppiSrcVideoPel[1], piStrides[1], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getAddr( COMPONENT_Cb ) + (m_iHorOffset >> 1) * rpcPicYuvTarget->getStride( COMPONENT_Cb ), rpcPicYuvTarget->getStride( COMPONENT_Cb) );
+  TRenFilter<REN_BIT_DEPTH>::sampleDown2Tap13( ppiSrcVideoPel[2], piStrides[2], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getAddr( COMPONENT_Cr ) + (m_iHorOffset >> 1) * rpcPicYuvTarget->getStride( COMPONENT_Cr ), rpcPicYuvTarget->getStride( COMPONENT_Cr) );
 }
 
@@ -1895,5 +1901,5 @@
 template <BlenMod iBM, Bool bBitInc> 
 __inline Bool
-TRenSingleModelC<iBM,bBitInc>::xDetectEarlySkipL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData,Pel* piOrgData, Int iOrgStride)
+TRenSingleModelC<iBM,bBitInc>::xDetectEarlySkipL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel* piOrgData, Int iOrgStride)
 {
   RM_AOF( m_bEarlySkip ); 
@@ -1927,5 +1933,5 @@
 template <BlenMod iBM, Bool bBitInc> 
 __inline Bool
-TRenSingleModelC<iBM,bBitInc>::xDetectEarlySkipR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData,Pel* piOrgData, Int iOrgStride)
+TRenSingleModelC<iBM,bBitInc>::xDetectEarlySkipR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel* piOrgData, Int iOrgStride)
 {
   RM_AOF( m_bEarlySkip ); 
@@ -1958,4 +1964,4 @@
 }
 #endif
-#endif // H_3D
-
+#endif // NH_3D
+
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenSingleModel.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 1200)
@@ -51,5 +51,5 @@
 #include <cstring>
 
-#if H_3D_VSO
+#if NH_3D_VSO
 using namespace std;
 
@@ -82,17 +82,17 @@
   // Set Data
 #if H_3D_VSO_EARLY_SKIP
-  virtual Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel* piOrgData, Int iOrgStride )  = 0;
-#else
-  virtual Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )  = 0;
-#endif
-  virtual Void   setVideo  ( Int iViewPos,     Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData ) = 0;
+  virtual Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel* piOrgData, Int iOrgStride )  = 0;
+#else
+  virtual Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData )  = 0;
+#endif
+  virtual Void   setVideo  ( Int iViewPos,     Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData ) = 0;
 
   // Get Distortion
 #if H_3D_VSO_EARLY_SKIP
-  virtual RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel * piOrgData , Int iOrgStride)=0;
-#else
-  virtual RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData ) = 0;
-#endif
-  virtual RMDist getDistVideo  ( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData ) = 0;
+  virtual RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel * piOrgData , Int iOrgStride)=0;
+#else
+  virtual RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData ) = 0;
+#endif
+  virtual RMDist getDistVideo  ( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData ) = 0;
 
   virtual Void   getSynthVideo  ( Int iViewPos, TComPicYuv* pcPicYuv ) = 0;  
@@ -172,17 +172,17 @@
 
 #if H_3D_VSO_EARLY_SKIP
-  Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel* piOrgData, Int iOrgStride );
-#else
-  Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
-#endif
-  Void   setVideo  ( Int iViewPos,     Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
-
-  // Get Distortion
-#if H_3D_VSO_EARLY_SKIP
-  RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel * piOrgData , Int iOrgStride);
-#else
-  RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
-#endif
-  RMDist getDistVideo  ( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+  Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel* piOrgData, Int iOrgStride );
+#else                                                                                                                    
+  Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData );
+#endif                                                                                                                   
+  Void   setVideo  ( Int iViewPos,     Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData );
+                                                                                                                         
+  // Get Distortion                                                                                                      
+#if H_3D_VSO_EARLY_SKIP                                                                                                  
+  RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel * piOrgData , Int iOrgStride);
+#else                                                                                                                    
+  RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData );
+#endif                                                                                                                   
+  RMDist getDistVideo  ( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData );
 
   Void   getSynthVideo  ( Int iViewPos, TComPicYuv* pcPicYuv );  
@@ -198,11 +198,11 @@
   // Left to Right
 #if H_3D_VSO_EARLY_SKIP
-                      __inline Bool   xDetectEarlySkipL   ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData,Pel* piOrgData, Int iOrgStride );
-                      __inline Bool   xDetectEarlySkipR   ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData,Pel* piOrgData, Int iOrgStride );
-  template<Bool bSet> __inline RMDist xRenderL            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bFast );
-  template<Bool bSet> __inline RMDist xRenderR            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bFast );
-#else
-  template<Bool bSet> __inline RMDist xRenderR            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
-  template<Bool bSet> __inline RMDist xRenderL            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+                      __inline Bool   xDetectEarlySkipL   ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel* piOrgData, Int iOrgStride );
+                      __inline Bool   xDetectEarlySkipR   ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, const Pel* piOrgData, Int iOrgStride );
+  template<Bool bSet> __inline RMDist xRenderL            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, Bool bFast );
+  template<Bool bSet> __inline RMDist xRenderR            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData, Bool bFast );
+#else
+  template<Bool bSet> __inline RMDist xRenderR            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData );
+  template<Bool bSet> __inline RMDist xRenderL            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, const Pel* piNewData );
 #endif
                       __inline Void   xInitRenderPartL    ( Int iEndChangePos, Int iLastSPos  );
@@ -353,5 +353,5 @@
   Int   m_iCurViewPos;                 // Current View Position 0: Left, 1: Right
   Int   m_iOtherViewPos;               // Other View Position 0: Left, 1: Right
-  Pel*  m_piNewDepthData;              // Pointer to new depth data
+  const Pel*  m_piNewDepthData;              // Pointer to new depth data
   Int   m_iStartChangePosX;            // Start Position of new data
   Int   m_iNewDataWidth;               // Width of new data
@@ -389,5 +389,5 @@
 };
 
-#endif // H_3D
+#endif // NH_3D
 #endif //__TRENSINGLEMODEL__
 
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenTop.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenTop.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenTop.cpp	(revision 1200)
@@ -40,5 +40,5 @@
 #include <math.h>
 #include "../TLibCommon/CommonDef.h"
-#if H_3D
+#if NH_3D
 
 
@@ -114,5 +114,5 @@
     if (uiPlane == 0)
     {
-      TRenFilter::sampleHorUp    ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+      TRenFilter<REN_BIT_DEPTH>::sampleHorUp    ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
     }
     else
@@ -120,9 +120,9 @@
       if ( m_bUVUp )
       {
-        TRenFilter::sampleCUpHorUp( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+        TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
       }
       else
       {
-        TRenFilter::sampleCHorUp   ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+        TRenFilter<REN_BIT_DEPTH>::sampleCHorUp   ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
       }
     }
@@ -147,5 +147,5 @@
   AOT( iLog2SamplingFactor > 2);
 
-  TRenFilter::sampleHorUp(iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+  TRenFilter<REN_BIT_DEPTH>::sampleHorUp(iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
 
   if ( !m_bUVUp ) //GT: depth down
@@ -154,14 +154,14 @@
     PelImagePlane* pcTempPlane = new PelImagePlane(pcOrgInputImage->getPlane(0)->getWidth(), ( pcOrgInputImage->getPlane(0)->getHeight() >> 1), REN_LUMA_MARGIN );
 
-    TRenFilter::sampleVerDown2Tap13(pcOrgInputImage->getPlane(0), pcTempPlane, PICYUV_PAD);
+    TRenFilter<REN_BIT_DEPTH>::sampleVerDown2Tap13(pcOrgInputImage->getPlane(0), pcTempPlane, PICYUV_PAD);
     pcConvPlane = pcConvInputImage->getPlane(1);
 
     if ( iLog2SamplingFactor == 0 )
     {
-      TRenFilter::sampleHorDown2Tap13(pcTempPlane, pcConvPlane, 0 );
+      TRenFilter<REN_BIT_DEPTH>::sampleHorDown2Tap13(pcTempPlane, pcConvPlane, 0 );
     }
     else
     {
-      TRenFilter::sampleHorUp    ( iLog2SamplingFactor - 1, pcTempPlane->getPlaneData(), pcTempPlane->getStride(), pcTempPlane->getWidth(), pcTempPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+      TRenFilter<REN_BIT_DEPTH>::sampleHorUp    ( iLog2SamplingFactor - 1, pcTempPlane->getPlaneData(), pcTempPlane->getStride(), pcTempPlane->getWidth(), pcTempPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
     }
     delete pcTempPlane;
@@ -175,10 +175,10 @@
   {
     m_pcTempImage->assign( pcOrgInputImage );
-    TRenFilter::mirrorHor( m_pcTempImage );
+    TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcTempImage );
     m_pcTempImage->extendMargin();
     xConvertInputVideo(    m_pcTempImage, pcConvInputImage );
 
     m_pcTempImage->getPlane(0)->assign( pcOrgInputDepth->getPlane(0) );
-    TRenFilter::mirrorHor( m_pcTempImage->getPlane(0) );
+    TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcTempImage->getPlane(0) );
     m_pcTempImage->getPlane(0)->extendMargin();
     xConvertInputDepth( m_pcTempImage, pcConvInputDepth );
@@ -209,5 +209,5 @@
     if ( uiPlane == 0 )
     {
-      TRenFilter::sampleHorDown( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+      TRenFilter<REN_BIT_DEPTH>::sampleHorDown( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
     }
     else
@@ -215,9 +215,9 @@
       if ( m_bUVUp )
       {
-        TRenFilter::sampleCDownHorDown( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+        TRenFilter<REN_BIT_DEPTH>::sampleCDownHorDown( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
       }
       else
       {
-        TRenFilter::sampleCHorDown    ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+        TRenFilter<REN_BIT_DEPTH>::sampleCHorDown    ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
       }
     }
@@ -226,5 +226,5 @@
   if ( bMirror )
   {
-    TRenFilter::mirrorHor( pcConvOutputImage );
+    TRenFilter<REN_BIT_DEPTH>::mirrorHor( pcConvOutputImage );
   }
 
@@ -253,5 +253,5 @@
   if ( !m_bExtrapolate )
   {
-    TRenFilter::setupZLUT( m_bBlendUseDistWeight, m_iBlendZThresPerc, iRelDistToLeft, ppiBaseShiftLUTLeft, ppiBaseShiftLUTRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight);
+    TRenFilter<REN_BIT_DEPTH>::setupZLUT( m_bBlendUseDistWeight, m_iBlendZThresPerc, iRelDistToLeft, ppiBaseShiftLUTLeft, ppiBaseShiftLUTRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight);
   }
 }
@@ -261,6 +261,6 @@
   AOF( m_bExtrapolate );
   AOF( bRenderFromLeft ? m_ppiShiftLUTLeft || m_ppdShiftLUTLeft : m_ppiShiftLUTRight || m_ppdShiftLUTRight );
-  AOF( m_auiInputResolution[0] == pcPicYuvVideo->getWidth ());
-  AOF( m_auiInputResolution[1] == pcPicYuvVideo->getHeight());
+  AOF( m_auiInputResolution[0] == pcPicYuvVideo->getWidth ( COMPONENT_Y ));
+  AOF( m_auiInputResolution[1] == pcPicYuvVideo->getHeight( COMPONENT_Y ));
 
   PelImage cInputImage ( pcPicYuvVideo    );
@@ -284,6 +284,6 @@
 {
   AOF( bRenderFromLeft ? m_ppiShiftLUTLeft && m_ppdShiftLUTLeft : m_ppiShiftLUTRight && m_ppdShiftLUTRight );
-  AOF(m_auiInputResolution[0] == pcPicYuvDepth->getWidth ());
-  AOF(m_auiInputResolution[1] == pcPicYuvDepth->getHeight());
+  AOF(m_auiInputResolution[0] == pcPicYuvDepth->getWidth (COMPONENT_Y));
+  AOF(m_auiInputResolution[1] == pcPicYuvDepth->getHeight(COMPONENT_Y));
 
   PelImage cInputDepth ( pcPicYuvDepth    , true);
@@ -300,8 +300,8 @@
   if ( !bRenderFromLeft )
   {
-    TRenFilter::mirrorHor( m_pcFilled );
-  }
-
-  TRenFilter::filledToUsedPelMap( m_pcFilled, &cOutputImage, m_iUsedPelMapMarExt );
+    TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcFilled );
+  }
+
+  TRenFilter<REN_BIT_DEPTH>::filledToUsedPelMap( m_pcFilled, &cOutputImage, m_iUsedPelMapMarExt );
 };
 
@@ -310,6 +310,6 @@
 {
   assert( !m_bExtrapolate );
-  assert( m_auiInputResolution[0] == pcPicYuvVideoLeft ->getWidth () );
-  assert( m_auiInputResolution[1] == pcPicYuvVideoRight->getHeight() );
+  assert( m_auiInputResolution[0] == pcPicYuvVideoLeft ->getWidth ( COMPONENT_Y ) );
+  assert( m_auiInputResolution[1] == pcPicYuvVideoRight->getHeight( COMPONENT_Y ) );
 
   AOT( iBlendMode == 3);
@@ -363,7 +363,7 @@
   xCreateAlphaMap( m_pcRightFilled,      m_pcRightFilled, false );
 
-  TRenFilter::mirrorHor( m_pcRightOutputImage );
-  TRenFilter::mirrorHor( m_pcRightOutputDepth );
-  TRenFilter::mirrorHor( m_pcRightFilled      );
+  TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcRightOutputImage );
+  TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcRightOutputDepth );
+  TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcRightFilled      );
 
   xEnhSimilarity( m_pcLeftOutputImage, m_pcRightOutputImage, m_pcLeftFilled, m_pcRightFilled );
@@ -377,11 +377,11 @@
     xCreateAlphaMap      ( m_pcLeftFilled,       m_pcLeftFilled,       true );
 
-    TRenFilter::mirrorHor( m_pcRightInputImage );
+    TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcRightInputImage );
     xBackShiftPixels     ( m_pcRightInputImage,  m_pcOutputDepth,      m_pcRightOutputImage, m_pcRightFilled , true );
     xFillHoles           ( m_pcRightOutputImage, m_pcRightFilled,      m_pcRightOutputImage, true);
 
-    TRenFilter::mirrorHor( m_pcRightFilled );
+    TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcRightFilled );
     xCreateAlphaMap      ( m_pcRightFilled,      m_pcRightFilled,      true );
-    TRenFilter::mirrorHor( m_pcRightFilled );
+    TRenFilter<REN_BIT_DEPTH>::mirrorHor( m_pcRightFilled );
   }
 
@@ -415,5 +415,5 @@
   {
     case eRenPreProBinom:
-      TRenFilter::binominal(pcOutImage, pcTemp, m_iPreFilterSize);
+      TRenFilter<REN_BIT_DEPTH>::binominal(pcOutImage, pcTemp, m_iPreFilterSize);
       break;
     case eRenPreProNone:
@@ -607,5 +607,5 @@
     {
       apcDiffPlane[uiCurPlane] = new IntImagePlane( iWidth, iHeight, apcInputPlanes[uiCurPlane]->getPad());
-      TRenFilter::diffHorSym(apcInputPlanes[uiCurPlane] , apcDiffPlane[uiCurPlane]);
+      TRenFilter<REN_BIT_DEPTH>::diffHorSym(apcInputPlanes[uiCurPlane] , apcDiffPlane[uiCurPlane]);
       ppiDiffPlanes[uiCurPlane] = apcDiffPlane[uiCurPlane]->getPlaneData();
     }
@@ -659,5 +659,5 @@
               for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
               {
-                cVal  = TRenFilter::interpCHSpline(iInterPolPos, dShiftedPos, dPrevShiftedPos, apcInputData[uiCurPlane][iPosX - 1], ppiDiffPlanes[uiCurPlane][iPosX - 1], apcInputData[uiCurPlane][iPosX], ppiDiffPlanes[uiCurPlane][iPosX] );
+                cVal  = TRenFilter<REN_BIT_DEPTH>::interpCHSpline(iInterPolPos, dShiftedPos, dPrevShiftedPos, apcInputData[uiCurPlane][iPosX - 1], ppiDiffPlanes[uiCurPlane][iPosX - 1], apcInputData[uiCurPlane][iPosX], ppiDiffPlanes[uiCurPlane][iPosX] );
                 apcOutputData[uiCurPlane][iInterPolPos]  = cVal;
               }
@@ -1516,5 +1516,5 @@
   {
   case eRenPostProMed:
-    TRenFilter::lineMedian3(pcTemp);
+    TRenFilter<REN_BIT_DEPTH>::lineMedian3(pcTemp);
     break;
   case eRenPostProNone:
@@ -1599,17 +1599,16 @@
 
 Void TRenTop::xEnhSimilarityPlane       ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, UInt uiNumberOfPlanes )
-{
-  AOF( g_bitDepthC == g_bitDepthY ); 
+{  
   AOT( m_iSimEnhBaseView != 1 && m_iSimEnhBaseView != 2 );
   Int iWidth  = (*apcRightPlane)->getWidth ();
   Int iHeight = (*apcRightPlane)->getHeight();
 
-  Int* aiHistLeft  = new Int[ ((Int64)1 ) << g_bitDepthY ];
-  Int* aiHistRight = new Int[ ((Int64)1 ) << g_bitDepthY ];
-  Pel* aiConvLUT   = new Pel[ ((Int64)1 ) << g_bitDepthY ];
+  Int* aiHistLeft  = new Int[ ((Int64)1 ) << REN_BIT_DEPTH ];
+  Int* aiHistRight = new Int[ ((Int64)1 ) << REN_BIT_DEPTH ];
+  Pel* aiConvLUT   = new Pel[ ((Int64)1 ) << REN_BIT_DEPTH ];
 
   for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
   {
-    for (Int iCurVal = 0 ; iCurVal < ( 1 << g_bitDepthY ); iCurVal++)
+    for (Int iCurVal = 0 ; iCurVal < ( 1 << REN_BIT_DEPTH ); iCurVal++)
     {
       aiHistLeft [iCurVal] = 0;
@@ -1658,5 +1657,5 @@
     Int iCheckSumRight = 0;
 
-    for (Int iCurVal = 0 ; iCurVal < ( 1 << g_bitDepthY ); iCurVal++)
+    for (Int iCurVal = 0 ; iCurVal < ( 1 << REN_BIT_DEPTH ); iCurVal++)
     {
       iCheckSumLeft  += aiHistLeft [iCurVal];
@@ -1665,13 +1664,13 @@
 
 
-    while( iCurChangeVal < ( 1 << g_bitDepthY ) )
+    while( iCurChangeVal < ( 1 << REN_BIT_DEPTH ) )
     {
       if ( iCumSumBase == iCumSumChange )
       {
-        aiConvLUT[iCurChangeVal] = std::min( iCurBaseVal,  ( 1 << g_bitDepthY ) - 1 );
+        aiConvLUT[iCurChangeVal] = std::min( iCurBaseVal,  ( 1 << REN_BIT_DEPTH ) - 1 );
         iCurBaseVal  ++;
         iCurChangeVal++;
         iCumSumChange += aiHistChange[iCurChangeVal];
-        if (iCurBaseVal <  ( 1 << g_bitDepthY ) )
+        if (iCurBaseVal <  ( 1 << REN_BIT_DEPTH ) )
         {
           iCumSumBase   += aiHistBase  [iCurBaseVal]  ;
@@ -1681,5 +1680,5 @@
       {
         iCurBaseVal++;
-        if (iCurBaseVal < ( 1 << g_bitDepthY ) )
+        if (iCurBaseVal < ( 1 << REN_BIT_DEPTH ) )
         {
           iCumSumBase   += aiHistBase  [iCurBaseVal]  ;
@@ -1688,5 +1687,5 @@
       else if ( iCumSumBase > iCumSumChange)
       {
-        aiConvLUT[iCurChangeVal] = std::min(iCurBaseVal, ( 1 << g_bitDepthY )-1);
+        aiConvLUT[iCurChangeVal] = std::min(iCurBaseVal, ( 1 << REN_BIT_DEPTH )-1);
         iCurChangeVal++;
         iCumSumChange += aiHistChange  [iCurChangeVal]  ;
@@ -1897,5 +1896,4 @@
 Void TRenTop::temporalFilterVSRS( TComPicYuv* pcPicYuvVideoCur, TComPicYuv* pcPicYuvDepthCur, TComPicYuv* pcPicYuvVideoLast, TComPicYuv* pcPicYuvDepthLast, Bool bFirstFrame )
 {
-  AOF( g_bitDepthY == g_bitDepthC ); 
   Int iSADThres  = 100 ;  //threshold of sad in 4*4 block motion detection
 
@@ -1906,13 +1904,13 @@
   Int* piFlagMoving =  m_aiBlkMoving + 2;
 
-  Int iVideoCurStride     = pcPicYuvVideoCur ->getStride();
-  Int iVideoLastStride    = pcPicYuvVideoLast->getStride();
-  Int iDepthCurStride     = pcPicYuvDepthCur ->getStride();
-  Int iDepthLastStride    = pcPicYuvDepthLast->getStride();
-
-  Pel* pcVideoCurData     = pcPicYuvVideoCur ->getLumaAddr();
-  Pel* pcVideoLastData    = pcPicYuvVideoLast->getLumaAddr();
-  Pel* pcDepthCurData     = pcPicYuvDepthCur ->getLumaAddr();
-  Pel* pcDepthLastData    = pcPicYuvDepthLast->getLumaAddr();
+  Int iVideoCurStride     = pcPicYuvVideoCur ->getStride( COMPONENT_Y );
+  Int iVideoLastStride    = pcPicYuvVideoLast->getStride( COMPONENT_Y );
+  Int iDepthCurStride     = pcPicYuvDepthCur ->getStride( COMPONENT_Y );
+  Int iDepthLastStride    = pcPicYuvDepthLast->getStride( COMPONENT_Y );
+
+  Pel* pcVideoCurData     = pcPicYuvVideoCur ->getAddr( COMPONENT_Y );
+  Pel* pcVideoLastData    = pcPicYuvVideoLast->getAddr( COMPONENT_Y );
+  Pel* pcDepthCurData     = pcPicYuvDepthCur ->getAddr( COMPONENT_Y );
+  Pel* pcDepthLastData    = pcPicYuvDepthLast->getAddr( COMPONENT_Y );
 
   Pel* pcVideoCurDataFrm  = pcVideoCurData ;
@@ -1964,5 +1962,5 @@
             { //Weight: 0.75
               Int iFilt = (( (pcDepthLastDataBlk[iCurPosX] << 1 ) + pcDepthLastDataBlk[iCurPosX] + pcDepthCurDataBlk[iCurPosX] + 2 ) >> 2 );
-              assert( (iFilt >= 0) && (iFilt <  ( 1 << g_bitDepthY ) ) );
+              assert( (iFilt >= 0) && (iFilt <  ( 1 << REN_BIT_DEPTH ) ) );
               pcDepthCurDataBlk[iCurPosX] = pcDepthLastDataBlk[iCurPosX];
               pcDepthCurDataBlk[iCurPosX] = iFilt;
@@ -2169,5 +2167,5 @@
     }
 
-    TRenFilter::setSubPelShiftLUT(m_iRelShiftLUTPrec, m_aaiSubPelShift, -1);
+    TRenFilter<REN_BIT_DEPTH>::setSubPelShiftLUT(m_iRelShiftLUTPrec, m_aaiSubPelShift, -1);
   }
 
@@ -2235,4 +2233,4 @@
   if(m_aiBlkMoving         != NULL ) delete[] m_aiBlkMoving;
 }
-#endif // H_3D
-
+#endif // NH_3D
+
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenTop.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenTop.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibRenderer/TRenTop.h	(revision 1200)
@@ -39,5 +39,5 @@
 #include "../TLibCommon/TComPicYuv.h"
 
-#if H_3D
+#if NH_3D
 #include <list>
 #include <vector>
@@ -270,4 +270,4 @@
 };
 
-#endif // H_3D
+#endif // NH_3D
 #endif //__TRENTOP__
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1200)
@@ -2,7 +2,7 @@
  * 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) 2010-2015, ITU/ISO/IEC
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -42,4 +42,5 @@
 #include <fstream>
 #include <iostream>
+#include <memory.h>
 
 #include "TLibCommon/TComRom.h"
@@ -48,52 +49,7 @@
 using namespace std;
 
-/**
- * Perform division with rounding of all pixels in img by
- * 2<sup>shiftbits</sup>. All pixels are clipped to [minval, maxval]
- *
- * @param img        pointer to image to be transformed
- * @param stride     distance between vertically adjacent pixels of img.
- * @param width      width of active area in img.
- * @param height     height of active area in img.
- * @param shiftbits  number of rounding bits
- * @param minval     minimum clipping value
- * @param maxval     maximum clipping value
- */
-static void invScalePlane(Pel* img, UInt stride, UInt width, UInt height,
-                       UInt shiftbits, Pel minval, Pel maxval)
-{
-  Pel offset = 1 << (shiftbits-1);
-  for (UInt y = 0; y < height; y++)
-  {
-    for (UInt x = 0; x < width; x++)
-    {
-      Pel val = (img[x] + offset) >> shiftbits;
-      img[x] = Clip3(minval, maxval, val);
-    }
-    img += stride;
-  }
-}
-
-/**
- * Multiply all pixels in img by 2<sup>shiftbits</sup>.
- *
- * @param img        pointer to image to be transformed
- * @param stride     distance between vertically adjacent pixels of img.
- * @param width      width of active area in img.
- * @param height     height of active area in img.
- * @param shiftbits  number of bits to shift
- */
-static void scalePlane(Pel* img, UInt stride, UInt width, UInt height,
-                       UInt shiftbits)
-{
-  for (UInt y = 0; y < height; y++)
-  {
-    for (UInt x = 0; x < width; x++)
-    {
-      img[x] <<= shiftbits;
-    }
-    img += stride;
-  }
-}
+// ====================================================================================================================
+// Local Functions
+// ====================================================================================================================
 
 /**
@@ -112,19 +68,28 @@
  * @param maxval  maximum clipping value when dividing.
  */
-static void scalePlane(Pel* img, UInt stride, UInt width, UInt height,
-                       Int shiftbits, Pel minval, Pel maxval)
-{
-  if (shiftbits == 0)
-  {
-    return;
-  }
-
+static Void scalePlane(Pel* img, const UInt stride, const UInt width, const UInt height, Int shiftbits, Pel minval, Pel maxval)
+{
   if (shiftbits > 0)
   {
-    scalePlane(img, stride, width, height, shiftbits);
-  }
-  else
-  {
-    invScalePlane(img, stride, width, height, -shiftbits, minval, maxval);
+    for (UInt y = 0; y < height; y++, img+=stride)
+    {
+      for (UInt x = 0; x < width; x++)
+      {
+        img[x] <<= shiftbits;
+      }
+    }
+  }
+  else if (shiftbits < 0)
+  {
+    shiftbits=-shiftbits;
+
+    Pel rounding = 1 << (shiftbits-1);
+    for (UInt y = 0; y < height; y++, img+=stride)
+    {
+      for (UInt x = 0; x < width; x++)
+      {
+        img[x] = Clip3(minval, maxval, Pel((img[x] + rounding) >> shiftbits));
+      }
+    }
   }
 }
@@ -146,21 +111,36 @@
  *
  * \param pchFile          file name string
- * \param bWriteMode       file open mode: true=read, false=write
- * \param fileBitDepthY     bit-depth of input/output file data (luma component).
- * \param fileBitDepthC     bit-depth of input/output file data (chroma components).
- * \param internalBitDepthY bit-depth to scale image data to/from when reading/writing (luma component).
- * \param internalBitDepthC bit-depth to scale image data to/from when reading/writing (chroma components).
+ * \param bWriteMode       file open mode: true=write, false=read
+ * \param fileBitDepth     bit-depth array of input/output file data.
+ * \param MSBExtendedBitDepth
+ * \param internalBitDepth bit-depth array to scale image data to/from when reading/writing.
  */
-Void TVideoIOYuv::open( Char* pchFile, Bool bWriteMode, Int fileBitDepthY, Int fileBitDepthC, Int internalBitDepthY, Int internalBitDepthC)
-{
-  m_bitDepthShiftY = internalBitDepthY - fileBitDepthY;
-  m_bitDepthShiftC = internalBitDepthC - fileBitDepthC;
-  m_fileBitDepthY = fileBitDepthY;
-  m_fileBitDepthC = fileBitDepthC;
+Void TVideoIOYuv::open( Char* pchFile, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] )
+{
+  //NOTE: files cannot have bit depth greater than 16
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_fileBitdepth       [ch] = std::min<UInt>(fileBitDepth[ch], 16);
+    m_MSBExtendedBitDepth[ch] = MSBExtendedBitDepth[ch];
+    m_bitdepthShift      [ch] = internalBitDepth[ch] - m_MSBExtendedBitDepth[ch];
+
+    if (m_fileBitdepth[ch] > 16)
+    {
+      if (bWriteMode)
+      {
+        std::cerr << "\nWARNING: Cannot write a yuv file of bit depth greater than 16 - output will be right-shifted down to 16-bit precision\n" << std::endl;
+      }
+      else
+      {
+        std::cerr << "\nERROR: Cannot read a yuv file of bit depth greater than 16\n" << std::endl;
+        exit(0);
+      }
+    }
+  }
 
   if ( bWriteMode )
   {
     m_cHandle.open( pchFile, ios::binary | ios::out );
-    
+
     if( m_cHandle.fail() )
     {
@@ -172,5 +152,5 @@
   {
     m_cHandle.open( pchFile, ios::binary | ios::in );
-    
+
     if( m_cHandle.fail() )
     {
@@ -179,5 +159,5 @@
     }
   }
-  
+
   return;
 }
@@ -204,21 +184,39 @@
  * seekable, by consuming bytes.
  */
-void TVideoIOYuv::skipFrames(UInt numFrames, UInt width, UInt height)
+Void TVideoIOYuv::skipFrames(UInt numFrames, UInt width, UInt height, ChromaFormat format)
 {
   if (!numFrames)
+  {
     return;
-
-  const UInt wordsize = (m_fileBitDepthY > 8 || m_fileBitDepthC > 8) ? 2 : 1;
-  const streamoff framesize = wordsize * width * height * 3 / 2;
-  const streamoff offset = framesize * numFrames;
+  }
+
+  //------------------
+  //set the frame size according to the chroma format
+  streamoff frameSize = 0;
+  UInt wordsize=1; // default to 8-bit, unless a channel with more than 8-bits is detected.
+  for (UInt component = 0; component < getNumberValidComponents(format); component++)
+  {
+    ComponentID compID=ComponentID(component);
+    frameSize += (width >> getComponentScaleX(compID, format)) * (height >> getComponentScaleY(compID, format));
+    if (m_fileBitdepth[toChannelType(compID)] > 8)
+    {
+      wordsize=2;
+    }
+  }
+  frameSize *= wordsize;
+  //------------------
+
+  const streamoff offset = frameSize * numFrames;
 
   /* attempt to seek */
   if (!!m_cHandle.seekg(offset, ios::cur))
+  {
     return; /* success */
+  }
   m_cHandle.clear();
 
   /* fall back to consuming the input */
   Char buf[512];
-  const UInt offset_mod_bufsize = offset % sizeof(buf);
+  const streamoff offset_mod_bufsize = offset % sizeof(buf);
   for (streamoff i = 0; i < offset - offset_mod_bufsize; i += sizeof(buf))
   {
@@ -233,58 +231,153 @@
  * either 8bit or 16bit little-endian lsb-aligned words.
  *
- * @param dst     destination image
- * @param fd      input file stream
- * @param is16bit true if input file carries > 8bit data, false otherwise.
- * @param stride  distance between vertically adjacent pixels of dst.
- * @param width   width of active area in dst.
- * @param height  height of active area in dst.
- * @param pad_x   length of horizontal padding.
- * @param pad_y   length of vertical padding.
+ * @param dst          destination image plane
+ * @param fd           input file stream
+ * @param is16bit      true if input file carries > 8bit data, false otherwise.
+ * @param stride444    distance between vertically adjacent pixels of dst.
+ * @param width444     width of active area in dst.
+ * @param height444    height of active area in dst.
+ * @param pad_x444     length of horizontal padding.
+ * @param pad_y444     length of vertical padding.
+ * @param compID       chroma component
+ * @param destFormat   chroma format of image
+ * @param fileFormat   chroma format of file
+ * @param fileBitDepth component bit depth in file
  * @return true for success, false in case of error
  */
-static Bool readPlane(Pel* dst, istream& fd, Bool is16bit,
-                      UInt stride,
-                      UInt width, UInt height,
-                      UInt pad_x, UInt pad_y)
-{
-  Int read_len = width * (is16bit ? 2 : 1);
-  UChar *buf = new UChar[read_len];
-  for (Int y = 0; y < height; y++)
-  {
-    fd.read(reinterpret_cast<Char*>(buf), read_len);
-    if (fd.eof() || fd.fail() )
-    {
-      delete[] buf;
-      return false;
-    }
-
-    if (!is16bit)
-    {
-      for (Int x = 0; x < width; x++)
-      {
-        dst[x] = buf[x];
-      }
-    }
-    else
-    {
-      for (Int x = 0; x < width; x++)
-      {
-        dst[x] = (buf[2*x+1] << 8) | buf[2*x];
-      }
-    }
-
-    for (Int x = width; x < width + pad_x; x++)
-    {
-      dst[x] = dst[width - 1];
-    }
-    dst += stride;
-  }
-  for (Int y = height; y < height + pad_y; y++)
-  {
-    for (Int x = 0; x < width + pad_x; x++)
-    {
-      dst[x] = (dst - stride)[x];
-    }
-    dst += stride;
+static Bool readPlane(Pel* dst,
+                      istream& fd,
+                      Bool is16bit,
+                      UInt stride444,
+                      UInt width444,
+                      UInt height444,
+                      UInt pad_x444,
+                      UInt pad_y444,
+                      const ComponentID compID,
+                      const ChromaFormat destFormat,
+                      const ChromaFormat fileFormat,
+                      const UInt fileBitDepth)
+{
+  const UInt csx_file =getComponentScaleX(compID, fileFormat);
+  const UInt csy_file =getComponentScaleY(compID, fileFormat);
+  const UInt csx_dest =getComponentScaleX(compID, destFormat);
+  const UInt csy_dest =getComponentScaleY(compID, destFormat);
+
+  const UInt width_dest       = width444 >>csx_dest;
+  const UInt height_dest      = height444>>csy_dest;
+  const UInt pad_x_dest       = pad_x444>>csx_dest;
+  const UInt pad_y_dest       = pad_y444>>csy_dest;
+  const UInt stride_dest      = stride444>>csx_dest;
+
+  const UInt full_width_dest  = width_dest+pad_x_dest;
+  const UInt full_height_dest = height_dest+pad_y_dest;
+
+  const UInt stride_file      = (width444 * (is16bit ? 2 : 1)) >> csx_file;
+
+  UChar  *buf   = new UChar[stride_file];
+
+  if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || destFormat==CHROMA_400))
+  {
+    if (destFormat!=CHROMA_400)
+    {
+      // set chrominance data to mid-range: (1<<(fileBitDepth-1))
+      const Pel value=Pel(1<<(fileBitDepth-1));
+      for (UInt y = 0; y < full_height_dest; y++, dst+=stride_dest)
+      {
+        for (UInt x = 0; x < full_width_dest; x++)
+        {
+          dst[x] = value;
+        }
+      }
+    }
+
+    if (fileFormat!=CHROMA_400)
+    {
+      const UInt height_file      = height444>>csy_file;
+      fd.seekg(height_file*stride_file, ios::cur);
+      if (fd.eof() || fd.fail() )
+      {
+        delete[] buf;
+        return false;
+      }
+    }
+  }
+  else
+  {
+    const UInt mask_y_file=(1<<csy_file)-1;
+    const UInt mask_y_dest=(1<<csy_dest)-1;
+    for(UInt y444=0; y444<height444; y444++)
+    {
+      if ((y444&mask_y_file)==0)
+      {
+        // read a new line
+        fd.read(reinterpret_cast<Char*>(buf), stride_file);
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+
+      if ((y444&mask_y_dest)==0)
+      {
+        // process current destination line
+        if (csx_file < csx_dest)
+        {
+          // eg file is 444, dest is 422.
+          const UInt sx=csx_dest-csx_file;
+          if (!is16bit)
+          {
+            for (UInt x = 0; x < width_dest; x++)
+            {
+              dst[x] = buf[x<<sx];
+            }
+          }
+          else
+          {
+            for (UInt x = 0; x < width_dest; x++)
+            {
+              dst[x] = Pel(buf[(x<<sx)*2+0]) | (Pel(buf[(x<<sx)*2+1])<<8);
+            }
+          }
+        }
+        else
+        {
+          // eg file is 422, dest is 444.
+          const UInt sx=csx_file-csx_dest;
+          if (!is16bit)
+          {
+            for (UInt x = 0; x < width_dest; x++)
+            {
+              dst[x] = buf[x>>sx];
+            }
+          }
+          else
+          {
+            for (UInt x = 0; x < width_dest; x++)
+            {
+              dst[x] = Pel(buf[(x>>sx)*2+0]) | (Pel(buf[(x>>sx)*2+1])<<8);
+            }
+          }
+        }
+
+        // process right hand side padding
+        const Pel val=dst[width_dest-1];
+        for (UInt x = width_dest; x < full_width_dest; x++)
+        {
+          dst[x] = val;
+        }
+
+        dst += stride_dest;
+      }
+    }
+
+    // process lower padding
+    for (UInt y = height_dest; y < full_height_dest; y++, dst+=stride_dest)
+    {
+      for (UInt x = 0; x < full_width_dest; x++)
+      {
+        dst[x] = (dst - stride_dest)[x];
+      }
+    }
   }
   delete[] buf;
@@ -293,45 +386,138 @@
 
 /**
- * Write width*height pixels info fd from src.
- *
- * @param fd      output file stream
- * @param src     source image
- * @param is16bit true if input file carries > 8bit data, false otherwise.
- * @param stride  distance between vertically adjacent pixels of src.
- * @param width   width of active area in src.
- * @param height  height of active area in src.
+ * Write an image plane (width444*height444 pixels) from src into output stream fd.
+ *
+ * @param fd         output file stream
+ * @param src        source image
+ * @param is16bit    true if input file carries > 8bit data, false otherwise.
+ * @param stride444  distance between vertically adjacent pixels of src.
+ * @param width444   width of active area in src.
+ * @param height444  height of active area in src.
+ * @param compID       chroma component
+ * @param srcFormat    chroma format of image
+ * @param fileFormat   chroma format of file
+ * @param fileBitDepth component bit depth in file
  * @return true for success, false in case of error
  */
 static Bool writePlane(ostream& fd, Pel* src, Bool is16bit,
-                       UInt stride,
-                       UInt width, UInt height)
-{
-  Int write_len = width * (is16bit ? 2 : 1);
-  UChar *buf = new UChar[write_len];
-  for (Int y = 0; y < height; y++)
-  {
-    if (!is16bit) 
-    {
-      for (Int x = 0; x < width; x++)
-      {
-        buf[x] = (UChar) src[x];
-      }
-    }
-    else 
-    {
-      for (Int x = 0; x < width; x++)
-      {
-        buf[2*x] = src[x] & 0xff;
-        buf[2*x+1] = (src[x] >> 8) & 0xff;
-      }
-    }
-
-    fd.write(reinterpret_cast<Char*>(buf), write_len);
-    if (fd.eof() || fd.fail() )
-    {
-      delete[] buf;
-      return false;
-    }
-    src += stride;
+                       UInt stride444,
+                       UInt width444, UInt height444,
+                       const ComponentID compID,
+                       const ChromaFormat srcFormat,
+                       const ChromaFormat fileFormat,
+                       const UInt fileBitDepth)
+{
+  const UInt csx_file =getComponentScaleX(compID, fileFormat);
+  const UInt csy_file =getComponentScaleY(compID, fileFormat);
+  const UInt csx_src  =getComponentScaleX(compID, srcFormat);
+  const UInt csy_src  =getComponentScaleY(compID, srcFormat);
+
+  const UInt stride_src      = stride444>>csx_src;
+
+  const UInt stride_file      = (width444 * (is16bit ? 2 : 1)) >> csx_file;
+  const UInt width_file       = width444 >>csx_file;
+  const UInt height_file      = height444>>csy_file;
+
+  UChar  *buf   = new UChar[stride_file];
+
+  if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || srcFormat==CHROMA_400))
+  {
+    if (fileFormat!=CHROMA_400)
+    {
+      const UInt value=1<<(fileBitDepth-1);
+
+      for(UInt y=0; y< height_file; y++)
+      {
+        if (!is16bit)
+        {
+          UChar val(value);
+          for (UInt x = 0; x < width_file; x++)
+          {
+            buf[x]=val;
+          }
+        }
+        else
+        {
+          UShort val(value);
+          for (UInt x = 0; x < width_file; x++)
+          {
+            buf[2*x+0]= (val>>0) & 0xff;
+            buf[2*x+1]= (val>>8) & 0xff;
+          }
+        }
+
+        fd.write(reinterpret_cast<Char*>(buf), stride_file);
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+    }
+  }
+  else
+  {
+    const UInt mask_y_file=(1<<csy_file)-1;
+    const UInt mask_y_src =(1<<csy_src )-1;
+    for(UInt y444=0; y444<height444; y444++)
+    {
+      if ((y444&mask_y_file)==0)
+      {
+        // write a new line
+        if (csx_file < csx_src)
+        {
+          // eg file is 444, source is 422.
+          const UInt sx=csx_src-csx_file;
+          if (!is16bit)
+          {
+            for (UInt x = 0; x < width_file; x++)
+            {
+              buf[x] = (UChar)(src[x>>sx]);
+            }
+          }
+          else
+          {
+            for (UInt x = 0; x < width_file; x++)
+            {
+              buf[2*x  ] = (src[x>>sx]>>0) & 0xff;
+              buf[2*x+1] = (src[x>>sx]>>8) & 0xff;
+            }
+          }
+        }
+        else
+        {
+          // eg file is 422, src is 444.
+          const UInt sx=csx_file-csx_src;
+          if (!is16bit)
+          {
+            for (UInt x = 0; x < width_file; x++)
+            {
+              buf[x] = (UChar)(src[x<<sx]);
+            }
+          }
+          else
+          {
+            for (UInt x = 0; x < width_file; x++)
+            {
+              buf[2*x  ] = (src[x<<sx]>>0) & 0xff;
+              buf[2*x+1] = (src[x<<sx]>>8) & 0xff;
+            }
+          }
+        }
+
+        fd.write(reinterpret_cast<Char*>(buf), stride_file);
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+
+      if ((y444&mask_y_src)==0)
+      {
+        src += stride_src;
+      }
+
+    }
   }
   delete[] buf;
@@ -340,43 +526,140 @@
 
 static Bool writeField(ostream& fd, Pel* top, Pel* bottom, Bool is16bit,
-                       UInt stride,
-                       UInt width, UInt height, bool isTff)
-{
-  Int write_len = width * (is16bit ? 2 : 1)*2;
-  UChar *buf = new UChar[write_len];
-  for (Int y = 0; y < height; y++)
-  {
-    if (!is16bit)
-    {
-      for (Int x = 0; x < width; x++)
-      {
-        buf[x] = isTff ? (UChar) top[x] : (UChar) bottom[x];
-        buf[width+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
-      }
-    }
-    else
-    {
-      for (Int x = 0; x < width; x++)
-      {
-        buf[2*x] = isTff ? top[x] & 0xff : bottom[x] & 0xff;
-        buf[2*x+1] = isTff ? (top[x] >> 8) & 0xff : (bottom[x] >> 8) & 0xff;
-        
-        buf[width+2*x] = isTff ? bottom[x] & 0xff : top[x] & 0xff;
-        buf[width+2*x+1] = isTff ? (bottom[x] >> 8) & 0xff : (top[x] >> 8) & 0xff;
-      }
-    }
-    
-    fd.write(reinterpret_cast<Char*>(buf), write_len);
-    if (fd.eof() || fd.fail() )
-    {
-      delete[] buf;
-      return false;
-    }
-    top += stride;
-    bottom += stride;
+                       UInt stride444,
+                       UInt width444, UInt height444,
+                       const ComponentID compID,
+                       const ChromaFormat srcFormat,
+                       const ChromaFormat fileFormat,
+                       const UInt fileBitDepth, const Bool isTff)
+{
+  const UInt csx_file =getComponentScaleX(compID, fileFormat);
+  const UInt csy_file =getComponentScaleY(compID, fileFormat);
+  const UInt csx_src  =getComponentScaleX(compID, srcFormat);
+  const UInt csy_src  =getComponentScaleY(compID, srcFormat);
+
+  const UInt stride_src      = stride444>>csx_src;
+
+  const UInt stride_file      = (width444 * (is16bit ? 2 : 1)) >> csx_file;
+  const UInt width_file       = width444 >>csx_file;
+  const UInt height_file      = height444>>csy_file;
+
+  UChar  *buf   = new UChar[stride_file * 2];
+
+  if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || srcFormat==CHROMA_400))
+  {
+    if (fileFormat!=CHROMA_400)
+    {
+      const UInt value=1<<(fileBitDepth-1);
+
+      for(UInt y=0; y< height_file; y++)
+      {
+        for (UInt field = 0; field < 2; field++)
+        {
+          UChar *fieldBuffer = buf + (field * stride_file);
+
+          if (!is16bit)
+          {
+            UChar val(value);
+            for (UInt x = 0; x < width_file; x++)
+            {
+              fieldBuffer[x]=val;
+            }
+          }
+          else
+          {
+            UShort val(value);
+            for (UInt x = 0; x < width_file; x++)
+            {
+              fieldBuffer[2*x+0]= (val>>0) & 0xff;
+              fieldBuffer[2*x+1]= (val>>8) & 0xff;
+            }
+          }
+        }
+
+        fd.write(reinterpret_cast<Char*>(buf), (stride_file * 2));
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+    }
+  }
+  else
+  {
+    const UInt mask_y_file=(1<<csy_file)-1;
+    const UInt mask_y_src =(1<<csy_src )-1;
+    for(UInt y444=0; y444<height444; y444++)
+    {
+      if ((y444&mask_y_file)==0)
+      {
+        for (UInt field = 0; field < 2; field++)
+        {
+          UChar *fieldBuffer = buf + (field * stride_file);
+          Pel   *src         = (((field == 0) && isTff) || ((field == 1) && (!isTff))) ? top : bottom;
+
+          // write a new line
+          if (csx_file < csx_src)
+          {
+            // eg file is 444, source is 422.
+            const UInt sx=csx_src-csx_file;
+            if (!is16bit)
+            {
+              for (UInt x = 0; x < width_file; x++)
+              {
+                fieldBuffer[x] = (UChar)(src[x>>sx]);
+              }
+            }
+            else
+            {
+              for (UInt x = 0; x < width_file; x++)
+              {
+                fieldBuffer[2*x  ] = (src[x>>sx]>>0) & 0xff;
+                fieldBuffer[2*x+1] = (src[x>>sx]>>8) & 0xff;
+              }
+            }
+          }
+          else
+          {
+            // eg file is 422, src is 444.
+            const UInt sx=csx_file-csx_src;
+            if (!is16bit)
+            {
+              for (UInt x = 0; x < width_file; x++)
+              {
+                fieldBuffer[x] = (UChar)(src[x<<sx]);
+              }
+            }
+            else
+            {
+              for (UInt x = 0; x < width_file; x++)
+              {
+                fieldBuffer[2*x  ] = (src[x<<sx]>>0) & 0xff;
+                fieldBuffer[2*x+1] = (src[x<<sx]>>8) & 0xff;
+              }
+            }
+          }
+        }
+
+        fd.write(reinterpret_cast<Char*>(buf), (stride_file * 2));
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+
+      if ((y444&mask_y_src)==0)
+      {
+        top    += stride_src;
+        bottom += stride_src;
+      }
+
+    }
   }
   delete[] buf;
   return true;
 }
+
 /**
  * Read one Y'CbCr frame, performing any required input scaling to change
@@ -388,64 +671,71 @@
  * file had been provided at the lower-bitdepth compliant to Rec601/709.
  *
- * @param pPicYuv      input picture YUV buffer class pointer
- * @param aiPad        source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @param pPicYuvUser      input picture YUV buffer class pointer
+ * @param pPicYuvTrueOrg
+ * @param ipcsc
+ * @param aiPad            source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @param format           chroma format
  * @return true for success, false in case of error
  */
-Bool TVideoIOYuv::read ( TComPicYuv*  pPicYuv, Int aiPad[2] )
+Bool TVideoIOYuv::read ( TComPicYuv*  pPicYuvUser, TComPicYuv* pPicYuvTrueOrg, const InputColourSpaceConversion ipcsc, Int aiPad[2], ChromaFormat format, const Bool bClipToRec709 )
 {
   // check end-of-file
-  if ( isEof() ) return false;
-  
-  Int   iStride = pPicYuv->getStride();
-  
+  if ( isEof() )
+  {
+    return false;
+  }
+  TComPicYuv *pPicYuv=pPicYuvTrueOrg;
+  if (format>=NUM_CHROMA_FORMAT)
+  {
+    format=pPicYuv->getChromaFormat();
+  }
+
+  Bool is16bit = false;
+
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    if (m_fileBitdepth[ch] > 8)
+    {
+      is16bit=true;
+    }
+  }
+
+  const UInt stride444      = pPicYuv->getStride(COMPONENT_Y);
+
   // compute actual YUV width & height excluding padding size
-  UInt pad_h = aiPad[0];
-  UInt pad_v = aiPad[1];
-  UInt width_full = pPicYuv->getWidth();
-  UInt height_full = pPicYuv->getHeight();
-  UInt width  = width_full - pad_h;
-  UInt height = height_full - pad_v;
-  Bool is16bit = m_fileBitDepthY > 8 || m_fileBitDepthC > 8;
-
-  Int desired_bitdepthY = m_fileBitDepthY + m_bitDepthShiftY;
-  Int desired_bitdepthC = m_fileBitDepthC + m_bitDepthShiftC;
-  Pel minvalY = 0;
-  Pel minvalC = 0;
-  Pel maxvalY = (1 << desired_bitdepthY) - 1;
-  Pel maxvalC = (1 << desired_bitdepthC) - 1;
-#if CLIP_TO_709_RANGE
-  if (m_bitdepthShiftY < 0 && desired_bitdepthY >= 8)
-  {
-    /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
-    minvalY = 1 << (desired_bitdepthY - 8);
-    maxvalY = (0xff << (desired_bitdepthY - 8)) -1;
-  }
-  if (m_bitdepthShiftC < 0 && desired_bitdepthC >= 8)
-  {
-    /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
-    minvalC = 1 << (desired_bitdepthC - 8);
-    maxvalC = (0xff << (desired_bitdepthC - 8)) -1;
-  }
-#endif
-  
-  if (! readPlane(pPicYuv->getLumaAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
-    return false;
-  scalePlane(pPicYuv->getLumaAddr(), iStride, width_full, height_full, m_bitDepthShiftY, minvalY, maxvalY);
-
-  iStride >>= 1;
-  width_full >>= 1;
-  height_full >>= 1;
-  width >>= 1;
-  height >>= 1;
-  pad_h >>= 1;
-  pad_v >>= 1;
-
-  if (! readPlane(pPicYuv->getCbAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
-    return false;
-  scalePlane(pPicYuv->getCbAddr(), iStride, width_full, height_full, m_bitDepthShiftC, minvalC, maxvalC);
-
-  if (! readPlane(pPicYuv->getCrAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
-    return false;
-  scalePlane(pPicYuv->getCrAddr(), iStride, width_full, height_full, m_bitDepthShiftC, minvalC, maxvalC);
+  const UInt pad_h444       = aiPad[0];
+  const UInt pad_v444       = aiPad[1];
+
+  const UInt width_full444  = pPicYuv->getWidth(COMPONENT_Y);
+  const UInt height_full444 = pPicYuv->getHeight(COMPONENT_Y);
+
+  const UInt width444       = width_full444 - pad_h444;
+  const UInt height444      = height_full444 - pad_v444;
+
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    const ComponentID compID = ComponentID(comp);
+    const ChannelType chType=toChannelType(compID);
+
+    const Int desired_bitdepth = m_MSBExtendedBitDepth[chType] + m_bitdepthShift[chType];
+
+    const Bool b709Compliance=(bClipToRec709) && (m_bitdepthShift[chType] < 0 && desired_bitdepth >= 8);     /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+    const Pel minval = b709Compliance? ((   1 << (desired_bitdepth - 8))   ) : 0;
+    const Pel maxval = b709Compliance? ((0xff << (desired_bitdepth - 8)) -1) : (1 << desired_bitdepth) - 1;
+
+    if (! readPlane(pPicYuv->getAddr(compID), m_cHandle, is16bit, stride444, width444, height444, pad_h444, pad_v444, compID, pPicYuv->getChromaFormat(), format, m_fileBitdepth[chType]))
+    {
+      return false;
+    }
+
+    if (compID < pPicYuv->getNumberValidComponents() )
+    {
+      const UInt csx=getComponentScaleX(compID, pPicYuv->getChromaFormat());
+      const UInt csy=getComponentScaleY(compID, pPicYuv->getChromaFormat());
+      scalePlane(pPicYuv->getAddr(compID), stride444>>csx, width_full444>>csx, height_full444>>csy, m_bitdepthShift[chType], minval, maxval);
+    }
+  }
+
+  ColourSpaceConvert(*pPicYuvTrueOrg, *pPicYuvUser, ipcsc, true);
 
   return true;
@@ -456,203 +746,301 @@
  * assumed to be at TVideoIO::m_fileBitdepth depth.
  *
- * @param pPicYuv     input picture YUV buffer class pointer
- * @param aiPad       source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @param pPicYuvUser      input picture YUV buffer class pointer
+ * @param ipCSC
+ * @param confLeft         conformance window left border
+ * @param confRight        conformance window right border
+ * @param confTop          conformance window top border
+ * @param confBottom       conformance window bottom border
+ * @param format           chroma format
  * @return true for success, false in case of error
  */
-Bool TVideoIOYuv::write( TComPicYuv* pPicYuv, Int confLeft, Int confRight, Int confTop, Int confBottom )
-{
+Bool TVideoIOYuv::write( TComPicYuv* pPicYuvUser, const InputColourSpaceConversion ipCSC, Int confLeft, Int confRight, Int confTop, Int confBottom, ChromaFormat format, const Bool bClipToRec709 )
+{
+  TComPicYuv cPicYuvCSCd;
+  if (ipCSC!=IPCOLOURSPACE_UNCHANGED)
+  {
+    cPicYuvCSCd.create(pPicYuvUser->getWidth(COMPONENT_Y), pPicYuvUser->getHeight(COMPONENT_Y), pPicYuvUser->getChromaFormat(), pPicYuvUser->getWidth(COMPONENT_Y), pPicYuvUser->getHeight(COMPONENT_Y), 0, false);
+    ColourSpaceConvert(*pPicYuvUser, cPicYuvCSCd, ipCSC, false);
+  }
+  TComPicYuv *pPicYuv=(ipCSC==IPCOLOURSPACE_UNCHANGED) ? pPicYuvUser : &cPicYuvCSCd;
+
   // compute actual YUV frame size excluding padding size
-  Int   iStride = pPicYuv->getStride();
-  UInt  width  = pPicYuv->getWidth()  - confLeft - confRight;
-  UInt  height = pPicYuv->getHeight() - confTop  - confBottom;
-  Bool is16bit = m_fileBitDepthY > 8 || m_fileBitDepthC > 8;
+  const Int   iStride444 = pPicYuv->getStride(COMPONENT_Y);
+  const UInt width444  = pPicYuv->getWidth(COMPONENT_Y) - confLeft - confRight;
+  const UInt height444 = pPicYuv->getHeight(COMPONENT_Y) -  confTop  - confBottom;
+  Bool is16bit = false;
+  Bool nonZeroBitDepthShift=false;
+
+  if ((width444 == 0) || (height444 == 0))
+  {
+    printf ("\nWarning: writing %d x %d luma sample output picture!", width444, height444);
+  }
+
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    if (m_fileBitdepth[ch] > 8)
+    {
+      is16bit=true;
+    }
+    if (m_bitdepthShift[ch] != 0)
+    {
+      nonZeroBitDepthShift=true;
+    }
+  }
+
   TComPicYuv *dstPicYuv = NULL;
   Bool retval = true;
-
-  if ((width==0)||(height==0))
-  {
-    printf ("\nWarning: writing %d x %d luma sample output picture!", width, height);
-  }
-
-  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
+  if (format>=NUM_CHROMA_FORMAT)
+  {
+    format=pPicYuv->getChromaFormat();
+  }
+
+  if (nonZeroBitDepthShift)
   {
     dstPicYuv = new TComPicYuv;
-    dstPicYuv->create( pPicYuv->getWidth(), pPicYuv->getHeight(), 1, 1, 0 );
+    dstPicYuv->create( pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), pPicYuv->getChromaFormat(), pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), 0, false );
     pPicYuv->copyToPic(dstPicYuv);
 
-    Pel minvalY = 0;
-    Pel minvalC = 0;
-    Pel maxvalY = (1 << m_fileBitDepthY) - 1;
-    Pel maxvalC = (1 << m_fileBitDepthC) - 1;
-#if CLIP_TO_709_RANGE
-    if (-m_bitDepthShiftY < 0 && m_fileBitDepthY >= 8)
-    {
-      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
-      minvalY = 1 << (m_fileBitDepthY - 8);
-      maxvalY = (0xff << (m_fileBitDepthY - 8)) -1;
-    }
-    if (-m_bitDepthShiftC < 0 && m_fileBitDepthC >= 8)
-    {
-      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
-      minvalC = 1 << (m_fileBitDepthC - 8);
-      maxvalC = (0xff << (m_fileBitDepthC - 8)) -1;
-    }
+    for(UInt comp=0; comp<dstPicYuv->getNumberValidComponents(); comp++)
+    {
+      const ComponentID compID=ComponentID(comp);
+      const ChannelType ch=toChannelType(compID);
+      const Bool b709Compliance = bClipToRec709 && (-m_bitdepthShift[ch] < 0 && m_MSBExtendedBitDepth[ch] >= 8);     /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      const Pel minval = b709Compliance? ((   1 << (m_MSBExtendedBitDepth[ch] - 8))   ) : 0;
+      const Pel maxval = b709Compliance? ((0xff << (m_MSBExtendedBitDepth[ch] - 8)) -1) : (1 << m_MSBExtendedBitDepth[ch]) - 1;
+
+      scalePlane(dstPicYuv->getAddr(compID), dstPicYuv->getStride(compID), dstPicYuv->getWidth(compID), dstPicYuv->getHeight(compID), -m_bitdepthShift[ch], minval, maxval);
+    }
+  }
+  else
+  {
+    dstPicYuv = pPicYuv;
+  }
+#if NH_3D
+  for(UInt comp=0; retval && comp< ::getNumberValidComponents(format); comp++)
+#else
+  for(UInt comp=0; retval && comp<dstPicYuv->getNumberValidComponents(); comp++)
 #endif
-    scalePlane(dstPicYuv->getLumaAddr(), dstPicYuv->getStride(), dstPicYuv->getWidth(), dstPicYuv->getHeight(), -m_bitDepthShiftY, minvalY, maxvalY);
-    scalePlane(dstPicYuv->getCbAddr(), dstPicYuv->getCStride(), dstPicYuv->getWidth()>>1, dstPicYuv->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
-    scalePlane(dstPicYuv->getCrAddr(), dstPicYuv->getCStride(), dstPicYuv->getWidth()>>1, dstPicYuv->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
-  }
-  else
-  {
-    dstPicYuv = pPicYuv;
-  }
-  // location of upper left pel in a plane
-  Int planeOffset = confLeft + confTop * iStride;
-  
-  if (! writePlane(m_cHandle, dstPicYuv->getLumaAddr() + planeOffset, is16bit, iStride, width, height))
-  {
-    retval=false; 
-    goto exit;
-  }
-
-  width >>= 1;
-  height >>= 1;
-  iStride >>= 1;
-  confLeft >>= 1;
-  confRight >>= 1;
-  confTop >>= 1;
-  confBottom >>= 1;
-
-  planeOffset = confLeft + confTop * iStride;
-
-  if (! writePlane(m_cHandle, dstPicYuv->getCbAddr() + planeOffset, is16bit, iStride, width, height))
-  {
-    retval=false; 
-    goto exit;
-  }
-  if (! writePlane(m_cHandle, dstPicYuv->getCrAddr() + planeOffset, is16bit, iStride, width, height))
-  {
-    retval=false; 
-    goto exit;
-  }
-  
-exit:
-  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
+  {
+    const ComponentID compID = ComponentID(comp);
+    const ChannelType ch=toChannelType(compID);
+    const UInt csx = pPicYuv->getComponentScaleX(compID);
+    const UInt csy = pPicYuv->getComponentScaleY(compID);
+    const Int planeOffset =  (confLeft>>csx) + (confTop>>csy) * pPicYuv->getStride(compID);
+    if (! writePlane(m_cHandle, dstPicYuv->getAddr(compID) + planeOffset, is16bit, iStride444, width444, height444, compID, dstPicYuv->getChromaFormat(), format, m_fileBitdepth[ch]))
+    {
+      retval=false;
+    }
+  }
+
+  if (nonZeroBitDepthShift)
   {
     dstPicYuv->destroy();
     delete dstPicYuv;
-  }  
+  }
+
+  cPicYuvCSCd.destroy();
+
   return retval;
 }
 
-
-/**
- * Write one Y'CbCr frame. No bit-depth conversion is performed, pcPicYuv is
- * assumed to be at TVideoIO::m_fileBitdepth depth.
- *
- * @param pPicTop     input top field YUV buffer class pointer
- * @param pPicBottom  input bottom field YUV buffer class pointer
- * @param aiPad       source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
- * @return true for success, false in case of error
- */
-Bool TVideoIOYuv::write( TComPicYuv* pPicTop, TComPicYuv* pPicBottom, Int cropLeft, Int cropRight, Int cropTop, Int cropBottom , bool isTff)
-{
-  // compute actual YUV frame size excluding padding size
-  Int   iStride = pPicTop->getStride();
-  UInt  width  = pPicTop->getWidth()  - cropLeft - cropRight;
-  UInt  height = pPicTop->getHeight() - cropTop  - cropBottom;
-  Bool is16bit = m_fileBitDepthY > 8 || m_fileBitDepthC > 8;
-  
-  TComPicYuv *dstPicTop = NULL;
-  TComPicYuv *dstPicBottom = NULL;
-  
+Bool TVideoIOYuv::write( TComPicYuv* pPicYuvUserTop, TComPicYuv* pPicYuvUserBottom, const InputColourSpaceConversion ipCSC, Int confLeft, Int confRight, Int confTop, Int confBottom, ChromaFormat format, const Bool isTff, const Bool bClipToRec709 )
+{
+
+  TComPicYuv cPicYuvTopCSCd;
+  TComPicYuv cPicYuvBottomCSCd;
+  if (ipCSC!=IPCOLOURSPACE_UNCHANGED)
+  {
+    cPicYuvTopCSCd   .create(pPicYuvUserTop   ->getWidth(COMPONENT_Y), pPicYuvUserTop   ->getHeight(COMPONENT_Y), pPicYuvUserTop   ->getChromaFormat(), pPicYuvUserTop   ->getWidth(COMPONENT_Y), pPicYuvUserTop   ->getHeight(COMPONENT_Y), 0, false);
+    cPicYuvBottomCSCd.create(pPicYuvUserBottom->getWidth(COMPONENT_Y), pPicYuvUserBottom->getHeight(COMPONENT_Y), pPicYuvUserBottom->getChromaFormat(), pPicYuvUserBottom->getWidth(COMPONENT_Y), pPicYuvUserBottom->getHeight(COMPONENT_Y), 0, false);
+    ColourSpaceConvert(*pPicYuvUserTop,    cPicYuvTopCSCd,    ipCSC, false);
+    ColourSpaceConvert(*pPicYuvUserBottom, cPicYuvBottomCSCd, ipCSC, false);
+  }
+  TComPicYuv *pPicYuvTop    = (ipCSC==IPCOLOURSPACE_UNCHANGED) ? pPicYuvUserTop    : &cPicYuvTopCSCd;
+  TComPicYuv *pPicYuvBottom = (ipCSC==IPCOLOURSPACE_UNCHANGED) ? pPicYuvUserBottom : &cPicYuvBottomCSCd;
+
+  Bool is16bit = false;
+  Bool nonZeroBitDepthShift=false;
+
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    if (m_fileBitdepth[ch] > 8)
+    {
+      is16bit=true;
+    }
+    if (m_bitdepthShift[ch] != 0)
+    {
+      nonZeroBitDepthShift=true;
+    }
+  }
+
+  TComPicYuv *dstPicYuvTop    = NULL;
+  TComPicYuv *dstPicYuvBottom = NULL;
+
+  for (UInt field = 0; field < 2; field++)
+  {
+    TComPicYuv *pPicYuv = (field == 0) ? pPicYuvTop : pPicYuvBottom;
+
+    if (format>=NUM_CHROMA_FORMAT)
+    {
+      format=pPicYuv->getChromaFormat();
+    }
+
+    TComPicYuv* &dstPicYuv = (field == 0) ? dstPicYuvTop : dstPicYuvBottom;
+
+    if (nonZeroBitDepthShift)
+    {
+      dstPicYuv = new TComPicYuv;
+      dstPicYuv->create( pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), pPicYuv->getChromaFormat(), pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), 0, false );
+      pPicYuv->copyToPic(dstPicYuv);
+
+      for(UInt comp=0; comp<dstPicYuv->getNumberValidComponents(); comp++)
+      {
+        const ComponentID compID=ComponentID(comp);
+        const ChannelType ch=toChannelType(compID);
+        const Bool b709Compliance=bClipToRec709 && (-m_bitdepthShift[ch] < 0 && m_MSBExtendedBitDepth[ch] >= 8);     /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+        const Pel minval = b709Compliance? ((   1 << (m_MSBExtendedBitDepth[ch] - 8))   ) : 0;
+        const Pel maxval = b709Compliance? ((0xff << (m_MSBExtendedBitDepth[ch] - 8)) -1) : (1 << m_MSBExtendedBitDepth[ch]) - 1;
+
+        scalePlane(dstPicYuv->getAddr(compID), dstPicYuv->getStride(compID), dstPicYuv->getWidth(compID), dstPicYuv->getHeight(compID), -m_bitdepthShift[ch], minval, maxval);
+      }
+    }
+    else
+    {
+      dstPicYuv = pPicYuv;
+    }
+  }
+
   Bool retval = true;
-  
-  if ((width==0)||(height==0))
-  {
-    printf ("\nWarning: writing %d x %d luma sample output picture!", width, height);
-  }
-  
-  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
-  {
-    dstPicTop = new TComPicYuv;
-    dstPicTop->create( pPicTop->getWidth(), pPicTop->getHeight(), 1, 1, 0 );
-    pPicTop->copyToPic(dstPicTop);
-    
-    dstPicBottom = new TComPicYuv;
-    dstPicBottom->create( pPicBottom->getWidth(), pPicBottom->getHeight(), 1, 1, 0 );
-    pPicBottom->copyToPic(dstPicBottom);
-    
-    Pel minvalY = 0;
-    Pel minvalC = 0;
-    Pel maxvalY = (1 << m_fileBitDepthY) - 1;
-    Pel maxvalC = (1 << m_fileBitDepthC) - 1;
-#if CLIP_TO_709_RANGE
-    if (-m_bitDepthShiftY < 0 && m_fileBitDepthY >= 8)
-    {
-      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
-      minvalY = 1 << (m_fileBitDepthY - 8);
-      maxvalY = (0xff << (m_fileBitDepthY - 8)) -1;
-    }
-    if (-m_bitDepthShiftC < 0 && m_fileBitDepthC >= 8)
-    {
-      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
-      minvalC = 1 << (m_fileBitDepthC - 8);
-      maxvalC = (0xff << (m_fileBitDepthC - 8)) -1;
-    }
-#endif
-    scalePlane(dstPicTop->getLumaAddr(), dstPicTop->getStride(), dstPicTop->getWidth(), dstPicTop->getHeight(), -m_bitDepthShiftY, minvalY, maxvalY);
-    scalePlane(dstPicTop->getCbAddr(), dstPicTop->getCStride(), dstPicTop->getWidth()>>1, dstPicTop->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
-    scalePlane(dstPicTop->getCrAddr(), dstPicTop->getCStride(), dstPicTop->getWidth()>>1, dstPicTop->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
-    
-    scalePlane(dstPicBottom->getLumaAddr(), dstPicBottom->getStride(), dstPicBottom->getWidth(), dstPicBottom->getHeight(), -m_bitDepthShiftY, minvalY, maxvalY);
-    scalePlane(dstPicBottom->getCbAddr(), dstPicBottom->getCStride(), dstPicBottom->getWidth()>>1, dstPicBottom->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
-    scalePlane(dstPicBottom->getCrAddr(), dstPicBottom->getCStride(), dstPicBottom->getWidth()>>1, dstPicBottom->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
-  }
-  else
-  {
-    dstPicTop = pPicTop;
-    dstPicBottom = pPicBottom;
-  }
-  // location of upper left pel in a plane
-  Int planeOffset = 0; //cropLeft + cropTop * iStride;
-  //Write luma
-  if (! writeField(m_cHandle, dstPicTop->getLumaAddr() + planeOffset,  dstPicBottom->getLumaAddr() + planeOffset, is16bit, iStride, width, height, isTff))
-  {
-    retval=false;
-    goto exit;
-  }
-  
-  width >>= 1;
-  height >>= 1;
-  iStride >>= 1;
-  cropLeft >>= 1;
-  cropRight >>= 1;
-  
-  planeOffset = 0; // cropLeft + cropTop * iStride;
-  
-  //Write chroma U
-  if (! writeField(m_cHandle, dstPicTop->getCbAddr() + planeOffset, dstPicBottom->getCbAddr() + planeOffset, is16bit, iStride, width, height, isTff))
-  {
-    retval=false;
-    goto exit;
-  }
-  
-  //Write chroma V
-  if (! writeField(m_cHandle, dstPicTop->getCrAddr() + planeOffset, dstPicBottom->getCrAddr() + planeOffset, is16bit, iStride, width, height, isTff))
-    
-  {
-    retval=false;
-    goto exit;
-  }
-  
-exit:
-  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
-  {
-    dstPicTop->destroy();
-    delete dstPicTop;
-    dstPicBottom->destroy();
-    delete dstPicBottom;
-  }  
+
+  assert(dstPicYuvTop->getNumberValidComponents() == dstPicYuvBottom->getNumberValidComponents());
+  assert(dstPicYuvTop->getChromaFormat()          == dstPicYuvBottom->getChromaFormat()         );
+  assert(dstPicYuvTop->getWidth(COMPONENT_Y)      == dstPicYuvBottom->getWidth(COMPONENT_Y)    );
+  assert(dstPicYuvTop->getHeight(COMPONENT_Y)     == dstPicYuvBottom->getHeight(COMPONENT_Y)    );
+  assert(dstPicYuvTop->getStride(COMPONENT_Y)     == dstPicYuvBottom->getStride(COMPONENT_Y)    );
+
+  for(UInt comp=0; retval && comp<dstPicYuvTop->getNumberValidComponents(); comp++)
+  {
+    const ComponentID compID = ComponentID(comp);
+    const ChannelType ch=toChannelType(compID);
+
+    assert(dstPicYuvTop->getComponentScaleX(compID) == dstPicYuvBottom->getComponentScaleX(compID));
+    assert(dstPicYuvTop->getComponentScaleY(compID) == dstPicYuvBottom->getComponentScaleY(compID));
+    assert(dstPicYuvTop->getStride         (compID) == dstPicYuvBottom->getStride         (compID));
+
+    const UInt width444   = dstPicYuvTop->getWidth(COMPONENT_Y)  - (confLeft + confRight);
+    const UInt height444  = dstPicYuvTop->getHeight(COMPONENT_Y) - (confTop + confBottom);
+
+    if ((width444 == 0) || (height444 == 0))
+    {
+      printf ("\nWarning: writing %d x %d luma sample output picture!", width444, height444);
+    }
+
+    const UInt csx = dstPicYuvTop->getComponentScaleX(compID);
+    const UInt csy = dstPicYuvTop->getComponentScaleY(compID);
+    const Int planeOffset  = (confLeft>>csx) + ( confTop>>csy) * dstPicYuvTop->getStride(compID); //offset is for entire frame - round up for top field and down for bottom field
+
+    if (! writeField(m_cHandle,
+                     (dstPicYuvTop   ->getAddr(compID) + planeOffset),
+                     (dstPicYuvBottom->getAddr(compID) + planeOffset),
+                     is16bit,
+                     dstPicYuvTop->getStride(COMPONENT_Y),
+                     width444, height444, compID, dstPicYuvTop->getChromaFormat(), format, m_fileBitdepth[ch], isTff))
+    {
+      retval=false;
+    }
+  }
+
+  if (nonZeroBitDepthShift)
+  {
+    dstPicYuvTop->destroy();
+    dstPicYuvBottom->destroy();
+    delete dstPicYuvTop;
+    delete dstPicYuvBottom;
+  }
+
+  cPicYuvTopCSCd.destroy();
+  cPicYuvBottomCSCd.destroy();
+
   return retval;
 }
+
+static Void
+copyPlane(const TComPicYuv &src, const ComponentID srcPlane, TComPicYuv &dest, const ComponentID destPlane)
+{
+  const UInt width=src.getWidth(srcPlane);
+  const UInt height=src.getHeight(srcPlane);
+  assert(dest.getWidth(destPlane) == width);
+  assert(dest.getHeight(destPlane) == height);
+  const Pel *pSrc=src.getAddr(srcPlane);
+  Pel *pDest=dest.getAddr(destPlane);
+  const UInt strideSrc=src.getStride(srcPlane);
+  const UInt strideDest=dest.getStride(destPlane);
+  for(UInt y=0; y<height; y++, pSrc+=strideSrc, pDest+=strideDest)
+  {
+    memcpy(pDest, pSrc, width*sizeof(Pel));
+  }
+}
+
+// static member
+Void TVideoIOYuv::ColourSpaceConvert(const TComPicYuv &src, TComPicYuv &dest, const InputColourSpaceConversion conversion, Bool bIsForwards)
+{
+  const ChromaFormat  format=src.getChromaFormat();
+  const UInt          numValidComp=src.getNumberValidComponents();
+
+  switch (conversion)
+  {
+    case IPCOLOURSPACE_YCbCrtoYYY:
+      if (format!=CHROMA_444)
+      {
+        // only 444 is handled.
+        assert(format==CHROMA_444);
+        exit(1);
+      }
+
+      {
+        for(UInt comp=0; comp<numValidComp; comp++)
+        {
+          copyPlane(src, ComponentID(bIsForwards?0:comp), dest, ComponentID(comp));
+        }
+      }
+      break;
+    case IPCOLOURSPACE_YCbCrtoYCrCb:
+      {
+        for(UInt comp=0; comp<numValidComp; comp++)
+        {
+          copyPlane(src, ComponentID(comp), dest, ComponentID((numValidComp-comp)%numValidComp));
+        }
+      }
+      break;
+
+    case IPCOLOURSPACE_RGBtoGBR:
+      {
+        if (format!=CHROMA_444)
+        {
+          // only 444 is handled.
+          assert(format==CHROMA_444);
+          exit(1);
+        }
+
+        // channel re-mapping
+        for(UInt comp=0; comp<numValidComp; comp++)
+        {
+          const ComponentID compIDsrc=ComponentID((comp+1)%numValidComp);
+          const ComponentID compIDdst=ComponentID(comp);
+          copyPlane(src, bIsForwards?compIDsrc:compIDdst, dest, bIsForwards?compIDdst:compIDsrc);
+        }
+      }
+      break;
+
+    case IPCOLOURSPACE_UNCHANGED:
+    default:
+      {
+        for(UInt comp=0; comp<numValidComp; comp++)
+        {
+          copyPlane(src, ComponentID(comp), dest, ComponentID(comp));
+        }
+      }
+      break;
+  }
+}
Index: branches/HTM-14.1-update-dev0/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -56,25 +56,34 @@
 private:
   fstream   m_cHandle;                                      ///< file handle
-  Int m_fileBitDepthY; ///< bitdepth of input/output video file luma component
-  Int m_fileBitDepthC; ///< bitdepth of input/output video file chroma component
-  Int m_bitDepthShiftY;  ///< number of bits to increase or decrease luma by before/after write/read
-  Int m_bitDepthShiftC;  ///< number of bits to increase or decrease chroma by before/after write/read
-  
+  Int       m_fileBitdepth[MAX_NUM_CHANNEL_TYPE]; ///< bitdepth of input/output video file
+  Int       m_MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE];  ///< bitdepth after addition of MSBs (with value 0)
+  Int       m_bitdepthShift[MAX_NUM_CHANNEL_TYPE];  ///< number of bits to increase or decrease image by before/after write/read
+
 public:
   TVideoIOYuv()           {}
   virtual ~TVideoIOYuv()  {}
-  
-  Void  open  ( Char* pchFile, Bool bWriteMode, Int fileBitDepthY, Int fileBitDepthC, Int internalBitDepthY, Int internalBitDepthC ); ///< open or create file
+
+  Void  open  ( Char* pchFile, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] ); ///< open or create file
   Void  close ();                                           ///< close file
 
-  void skipFrames(UInt numFrames, UInt width, UInt height);
-  
-  Bool  read  ( TComPicYuv*   pPicYuv, Int aiPad[2] );     ///< read  one YUV frame with padding parameter
-  Bool  write( TComPicYuv*    pPicYuv, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0 );
-  Bool  write( TComPicYuv*    pPicYuv, TComPicYuv*    pPicYuv2, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0  , bool isTff=false); 
-  
+  Void skipFrames(UInt numFrames, UInt width, UInt height, ChromaFormat format);
+
+  // if fileFormat<NUM_CHROMA_FORMAT, the format of the file is that format specified, else it is the format of the TComPicYuv.
+
+
+  // If fileFormat=NUM_CHROMA_FORMAT, use the format defined by pPicYuvTrueOrg
+  Bool  read  ( TComPicYuv* pPicYuv, TComPicYuv* pPicYuvTrueOrg, const InputColourSpaceConversion ipcsc, Int aiPad[2], ChromaFormat fileFormat=NUM_CHROMA_FORMAT, const Bool bClipToRec709=false );     ///< read one frame with padding parameter
+
+  // If fileFormat=NUM_CHROMA_FORMAT, use the format defined by pPicYuv
+  Bool  write ( TComPicYuv* pPicYuv, const InputColourSpaceConversion ipCSC, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0, ChromaFormat fileFormat=NUM_CHROMA_FORMAT, const Bool bClipToRec709=false );     ///< write one YUV frame with padding parameter
+
+  // If fileFormat=NUM_CHROMA_FORMAT, use the format defined by pPicYuvTop and pPicYuvBottom
+  Bool  write ( TComPicYuv* pPicYuvTop, TComPicYuv* pPicYuvBottom, const InputColourSpaceConversion ipCSC, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0, ChromaFormat fileFormat=NUM_CHROMA_FORMAT, const Bool isTff=false, const Bool bClipToRec709=false);
+  static Void ColourSpaceConvert(const TComPicYuv &src, TComPicYuv &dest, const InputColourSpaceConversion conversion, Bool bIsForwards);
+
   Bool  isEof ();                                           ///< check for end-of-file
   Bool  isFail();                                           ///< check for failure
-  
+
+
 };
 
Index: branches/HTM-14.1-update-dev0/source/Lib/libmd5/MD5.h
===================================================================
--- branches/HTM-14.1-update-dev0/source/Lib/libmd5/MD5.h	(revision 1199)
+++ branches/HTM-14.1-update-dev0/source/Lib/libmd5/MD5.h	(revision 1200)
@@ -2,7 +2,7 @@
  * 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.  
+ * granted under this license.
  *
-* Copyright (c) 2010-2015, ITU/ISO/IEC
+ * Copyright (c) 2010-2015, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -33,7 +33,10 @@
 #pragma once
 #include "libmd5.h"
+#include <string>
 
 //! \ingroup libMD5
 //! \{
+
+static const UInt MD5_DIGEST_STRING_LENGTH=16;
 
 class MD5
@@ -60,5 +63,5 @@
    * flush any outstanding MD5 data, write the digest into digest.
    */
-  void finalize(unsigned char digest[16])
+  void finalize(unsigned char digest[MD5_DIGEST_STRING_LENGTH])
   {
     MD5Final(digest, &m_state);
@@ -70,27 +73,3 @@
 
 
-/**
- * Produce an ascii(hex) representation of picture digest.
- *
- * Returns: a statically allocated null-terminated string.  DO NOT FREE.
- */
-inline const char*
-digestToString(const unsigned char digest[3][16], int numChar)
-{
-  const char* hex = "0123456789abcdef";
-  static char string[99];
-  int cnt=0;
-  for(int yuvIdx=0; yuvIdx<3; yuvIdx++)
-  {
-    for (int i = 0; i < numChar; i++)
-    {
-      string[cnt++] = hex[digest[yuvIdx][i] >> 4];
-      string[cnt++] = hex[digest[yuvIdx][i] & 0xf];
-    }
-    string[cnt++] = ',';
-  }
-
-  string[cnt-1] = '\0';
-  return string;
-}
 //! \}
